diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index dd31b618c..b4e02a025 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,6 +1,6 @@ { "ImportPath": "k8s.io/contrib/ingress", - "GoVersion": "go1.5.3", + "GoVersion": "go1.5", "Packages": [ "./..." ], @@ -8,7 +8,7 @@ { "ImportPath": "bitbucket.org/ww/goautoneg", "Comment": "null-5", - "Rev": "75cd24fc2f2c2a2088577d12123ddee5f54e0675" + "Rev": "'75cd24fc2f2c2a2088577d12123ddee5f54e0675'" }, { "ImportPath": "github.com/beorn7/perks/quantile", @@ -21,7 +21,7 @@ }, { "ImportPath": "github.com/cpuguy83/go-md2man/md2man", - "Comment": "v1.0.3-2-g71acacd", + "Comment": "v1.0.4", "Rev": "71acacd42f85e5e82f70a55327789582a5200a90" }, { @@ -48,17 +48,95 @@ "Comment": "v1.2", "Rev": "777bb3f19bcafe2575ffb2a3e46af92509ae9594" }, + { + "ImportPath": "github.com/emicklei/go-restful/log", + "Comment": "v1.2", + "Rev": "777bb3f19bcafe2575ffb2a3e46af92509ae9594" + }, + { + "ImportPath": "github.com/emicklei/go-restful/swagger", + "Comment": "v1.2", + "Rev": "777bb3f19bcafe2575ffb2a3e46af92509ae9594" + }, { "ImportPath": "github.com/evanphx/json-patch", "Rev": "7dd4489c2eb6073e5a9d7746c3274c5b5f0387df" }, { "ImportPath": "github.com/fatih/structs", - "Rev": "d2e1722acaab51fc7fc55686706d08bbf9e4fafb" + "Rev": "a924a2250d1033753512e95dce41dca3fd793ad9" }, { "ImportPath": "github.com/fsouza/go-dockerclient", - "Rev": "25bc220b299845ae5489fd19bf89c5278864b050" + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/docker/go-units", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" + }, + { + "ImportPath": "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix", + "Rev": "0099401a7342ad77e71ca9f9a57c5e72fb80f6b2" }, { "ImportPath": "github.com/ghodss/yaml", @@ -74,12 +152,12 @@ }, { "ImportPath": "github.com/golang/protobuf/proto", - "Rev": "7f07925444bb51fa4cf9dfe6f7661876f8852275" + "Rev": "b982704f8bb716bb608144408cff30e15fbde841" }, { "ImportPath": "github.com/google/cadvisor/info/v1", - "Comment": "v0.21.1", - "Rev": "49a08d5139ae0111757a110ea3b55fe9a607873d" + "Comment": "v0.22.2", + "Rev": "546a3771589bdb356777c646c6eca24914fdd48b" }, { "ImportPath": "github.com/google/gofuzz", @@ -107,6 +185,11 @@ "Comment": "v0.0.7", "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" }, + { + "ImportPath": "github.com/opencontainers/runc/libcontainer/cgroups/fs", + "Comment": "v0.0.7", + "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/configs", "Comment": "v0.0.7", @@ -152,6 +235,18 @@ "ImportPath": "github.com/scalingdata/gcfg", "Rev": "37aabad69cfd3d20b8390d902a8b10e245c615ff" }, + { + "ImportPath": "github.com/scalingdata/gcfg/scanner", + "Rev": "37aabad69cfd3d20b8390d902a8b10e245c615ff" + }, + { + "ImportPath": "github.com/scalingdata/gcfg/token", + "Rev": "37aabad69cfd3d20b8390d902a8b10e245c615ff" + }, + { + "ImportPath": "github.com/scalingdata/gcfg/types", + "Rev": "37aabad69cfd3d20b8390d902a8b10e245c615ff" + }, { "ImportPath": "github.com/shurcooL/sanitized_anchor_name", "Rev": "9a8b7d4e8f347bfa230879db9d7d4e4d9e19f962" @@ -166,16 +261,36 @@ }, { "ImportPath": "github.com/ugorji/go/codec", - "Rev": "f1f1a805ed361a0e078bb537e4ea78cd37dcf065" + "Rev": "f4485b318aadd133842532f841dc205a8e339d74" }, { "ImportPath": "golang.org/x/net/context", "Rev": "c2528b2dd8352441850638a8bb678c2ad056fd3e" }, + { + "ImportPath": "golang.org/x/net/context/ctxhttp", + "Rev": "c2528b2dd8352441850638a8bb678c2ad056fd3e" + }, { "ImportPath": "golang.org/x/oauth2", "Rev": "b5adcc2dcdf009d0391547edc6ecbaff889f5bb9" }, + { + "ImportPath": "golang.org/x/oauth2/google", + "Rev": "b5adcc2dcdf009d0391547edc6ecbaff889f5bb9" + }, + { + "ImportPath": "golang.org/x/oauth2/internal", + "Rev": "b5adcc2dcdf009d0391547edc6ecbaff889f5bb9" + }, + { + "ImportPath": "golang.org/x/oauth2/jws", + "Rev": "b5adcc2dcdf009d0391547edc6ecbaff889f5bb9" + }, + { + "ImportPath": "golang.org/x/oauth2/jwt", + "Rev": "b5adcc2dcdf009d0391547edc6ecbaff889f5bb9" + }, { "ImportPath": "google.golang.org/api/compute/v1", "Rev": "77e7d383beb96054547729f49c372b3d01e196ff" @@ -192,6 +307,10 @@ "ImportPath": "google.golang.org/api/googleapi", "Rev": "77e7d383beb96054547729f49c372b3d01e196ff" }, + { + "ImportPath": "google.golang.org/api/googleapi/internal/uritemplates", + "Rev": "77e7d383beb96054547729f49c372b3d01e196ff" + }, { "ImportPath": "google.golang.org/cloud/compute/metadata", "Rev": "2e43671e4ad874a7bca65746ff3edb38e6e93762" @@ -206,178 +325,498 @@ }, { "ImportPath": "k8s.io/kubernetes/pkg/api", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/endpoints", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/errors", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/install", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/meta", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/pod", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/resource", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/service", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/testapi", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/unversioned", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/util", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/v1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/api/validation", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/apimachinery", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apimachinery/registered", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/authorization", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/authorization/install", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/authorization/v1beta1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/autoscaling", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/autoscaling/install", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/autoscaling/v1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/batch", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/batch/install", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/batch/v1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/componentconfig", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/componentconfig/install", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/extensions", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/extensions/install", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/extensions/v1beta1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/metrics", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/metrics/install", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/metrics/v1alpha1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/user", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/capabilities", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/cache", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/metrics", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/record", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/restclient", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/transport", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/typed/discovery", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/auth", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/gce", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/controller", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/framework", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/conversion", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/conversion/queryparams", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/credentialprovider", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/fieldpath", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/fields", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubectl", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/kubectl/cmd/util", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/kubectl/resource", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/qos", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/kubelet/qos/util", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/labels", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/master/ports", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/json", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/recognizer", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/versioning", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/types", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/util", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/deployment", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/errors", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/hash", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/integer", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/intstr", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/jsonpath", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/labels", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/net", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/net/sets", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/parsers", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/pod", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/rand", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/runtime", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/sets", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/strategicpatch", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/validation", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/validation/field", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/wait", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/workqueue", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/yaml", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/version", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/pkg/watch", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/watch/json", + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/third_party/forked/json", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/third_party/forked/reflect", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "k8s.io/kubernetes/third_party/golang/template", - "Comment": "v1.2.0-alpha.8-71-g1ce188e", - "Rev": "1ce188e557769353063dc2233c89f4fa02133ecc" + "Comment": "v1.2.1-beta.0", + "Rev": "fd557a2c9f47c655f9c07d9cf9dee2539e935703" }, { "ImportPath": "speter.net/go/exp/math/dec/inf", diff --git a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go b/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go deleted file mode 100644 index 41d328f1d..000000000 --- a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package goautoneg - -import ( - "testing" -) - -var chrome = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" - -func TestParseAccept(t *testing.T) { - alternatives := []string{"text/html", "image/png"} - content_type := Negotiate(chrome, alternatives) - if content_type != "image/png" { - t.Errorf("got %s expected image/png", content_type) - } - - alternatives = []string{"text/html", "text/plain", "text/n3"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/html" { - t.Errorf("got %s expected text/html", content_type) - } - - alternatives = []string{"text/n3", "text/plain"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/plain" { - t.Errorf("got %s expected text/plain", content_type) - } - - alternatives = []string{"text/n3", "application/rdf+xml"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/n3" { - t.Errorf("got %s expected text/n3", content_type) - } -} diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go deleted file mode 100644 index 0bd0e4e77..000000000 --- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package quantile - -import ( - "testing" -) - -func BenchmarkInsertTargeted(b *testing.B) { - b.ReportAllocs() - - s := NewTargeted(Targets) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiased(b *testing.B) { - s := NewLowBiased(0.01) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) { - s := NewLowBiased(0.0001) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkQuery(b *testing.B) { - s := NewTargeted(Targets) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} - -func BenchmarkQuerySmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go deleted file mode 100644 index ab3293aaf..000000000 --- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// +build go1.1 - -package quantile_test - -import ( - "bufio" - "fmt" - "log" - "os" - "strconv" - "time" - - "github.com/beorn7/perks/quantile" -) - -func Example_simple() { - ch := make(chan float64) - go sendFloats(ch) - - // Compute the 50th, 90th, and 99th percentile. - q := quantile.NewTargeted(map[float64]float64{ - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - }) - for v := range ch { - q.Insert(v) - } - - fmt.Println("perc50:", q.Query(0.50)) - fmt.Println("perc90:", q.Query(0.90)) - fmt.Println("perc99:", q.Query(0.99)) - fmt.Println("count:", q.Count()) - // Output: - // perc50: 5 - // perc90: 16 - // perc99: 223 - // count: 2388 -} - -func Example_mergeMultipleStreams() { - // Scenario: - // We have multiple database shards. On each shard, there is a process - // collecting query response times from the database logs and inserting - // them into a Stream (created via NewTargeted(0.90)), much like the - // Simple example. These processes expose a network interface for us to - // ask them to serialize and send us the results of their - // Stream.Samples so we may Merge and Query them. - // - // NOTES: - // * These sample sets are small, allowing us to get them - // across the network much faster than sending the entire list of data - // points. - // - // * For this to work correctly, we must supply the same quantiles - // a priori the process collecting the samples supplied to NewTargeted, - // even if we do not plan to query them all here. - ch := make(chan quantile.Samples) - getDBQuerySamples(ch) - q := quantile.NewTargeted(map[float64]float64{0.90: 0.001}) - for samples := range ch { - q.Merge(samples) - } - fmt.Println("perc90:", q.Query(0.90)) -} - -func Example_window() { - // Scenario: We want the 90th, 95th, and 99th percentiles for each - // minute. - - ch := make(chan float64) - go sendStreamValues(ch) - - tick := time.NewTicker(1 * time.Minute) - q := quantile.NewTargeted(map[float64]float64{ - 0.90: 0.001, - 0.95: 0.0005, - 0.99: 0.0001, - }) - for { - select { - case t := <-tick.C: - flushToDB(t, q.Samples()) - q.Reset() - case v := <-ch: - q.Insert(v) - } - } -} - -func sendStreamValues(ch chan float64) { - // Use your imagination -} - -func flushToDB(t time.Time, samples quantile.Samples) { - // Use your imagination -} - -// This is a stub for the above example. In reality this would hit the remote -// servers via http or something like it. -func getDBQuerySamples(ch chan quantile.Samples) {} - -func sendFloats(ch chan<- float64) { - f, err := os.Open("exampledata.txt") - if err != nil { - log.Fatal(err) - } - sc := bufio.NewScanner(f) - for sc.Scan() { - b := sc.Bytes() - v, err := strconv.ParseFloat(string(b), 64) - if err != nil { - log.Fatal(err) - } - ch <- v - } - if sc.Err() != nil { - log.Fatal(sc.Err()) - } - close(ch) -} diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go deleted file mode 100644 index 4dba05449..000000000 --- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package quantile - -import ( - "math" - "math/rand" - "sort" - "testing" -) - -var ( - Targets = map[float64]float64{ - 0.01: 0.001, - 0.10: 0.01, - 0.50: 0.05, - 0.90: 0.01, - 0.99: 0.001, - } - TargetsSmallEpsilon = map[float64]float64{ - 0.01: 0.0001, - 0.10: 0.001, - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - } - LowQuantiles = []float64{0.01, 0.1, 0.5} - HighQuantiles = []float64{0.99, 0.9, 0.5} -) - -const RelativeEpsilon = 0.01 - -func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for quantile, epsilon := range Targets { - n := float64(len(a)) - k := int(quantile * n) - lower := int((quantile - epsilon) * n) - if lower < 1 { - lower = 1 - } - upper := int(math.Ceil((quantile + epsilon) * n)) - if upper > len(a) { - upper = len(a) - } - w, min, max := a[k-1], a[lower-1], a[upper-1] - if g := s.Query(quantile); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g) - } - } -} - -func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range LowQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - RelativeEpsilon) * qu * n) - upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range HighQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n) - upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func populateStream(s *Stream) []float64 { - a := make([]float64, 0, 1e5+100) - for i := 0; i < cap(a); i++ { - v := rand.NormFloat64() - // Add 5% asymmetric outliers. - if i%20 == 0 { - v = v*v + 1 - } - s.Insert(v) - a = append(a, v) - } - return a -} - -func TestTargetedQuery(t *testing.T) { - rand.Seed(42) - s := NewTargeted(Targets) - a := populateStream(s) - verifyPercsWithAbsoluteEpsilon(t, a, s) -} - -func TestLowBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewLowBiased(RelativeEpsilon) - a := populateStream(s) - verifyLowPercsWithRelativeEpsilon(t, a, s) -} - -func TestHighBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewHighBiased(RelativeEpsilon) - a := populateStream(s) - verifyHighPercsWithRelativeEpsilon(t, a, s) -} - -// BrokenTestTargetedMerge is broken, see Merge doc comment. -func BrokenTestTargetedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewTargeted(Targets) - s2 := NewTargeted(Targets) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyPercsWithAbsoluteEpsilon(t, a, s1) -} - -// BrokenTestLowBiasedMerge is broken, see Merge doc comment. -func BrokenTestLowBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewLowBiased(RelativeEpsilon) - s2 := NewLowBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyLowPercsWithRelativeEpsilon(t, a, s2) -} - -// BrokenTestHighBiasedMerge is broken, see Merge doc comment. -func BrokenTestHighBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewHighBiased(RelativeEpsilon) - s2 := NewHighBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyHighPercsWithRelativeEpsilon(t, a, s2) -} - -func TestUncompressed(t *testing.T) { - q := NewTargeted(Targets) - for i := 100; i > 0; i-- { - q.Insert(float64(i)) - } - if g := q.Count(); g != 100 { - t.Errorf("want count 100, got %d", g) - } - // Before compression, Query should have 100% accuracy. - for quantile := range Targets { - w := quantile * 100 - if g := q.Query(quantile); g != w { - t.Errorf("want %f, got %f", w, g) - } - } -} - -func TestUncompressedSamples(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.001}) - for i := 1; i <= 100; i++ { - q.Insert(float64(i)) - } - if g := q.Samples().Len(); g != 100 { - t.Errorf("want count 100, got %d", g) - } -} - -func TestUncompressedOne(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.01}) - q.Insert(3.14) - if g := q.Query(0.90); g != 3.14 { - t.Error("want PI, got", g) - } -} - -func TestDefaults(t *testing.T) { - if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 { - t.Errorf("want 0, got %f", g) - } -} diff --git a/Godeps/_workspace/src/github.com/blang/semver/examples/main.go b/Godeps/_workspace/src/github.com/blang/semver/examples/main.go deleted file mode 100644 index f36c983d9..000000000 --- a/Godeps/_workspace/src/github.com/blang/semver/examples/main.go +++ /dev/null @@ -1,83 +0,0 @@ -package main - -import ( - "fmt" - "github.com/blang/semver" -) - -func main() { - v, err := semver.Parse("0.0.1-alpha.preview.222+123.github") - if err != nil { - fmt.Printf("Error while parsing (not valid): %q", err) - } - fmt.Printf("Version to string: %q\n", v) - - fmt.Printf("Major: %d\n", v.Major) - fmt.Printf("Minor: %d\n", v.Minor) - fmt.Printf("Patch: %d\n", v.Patch) - - // Prerelease versions - if len(v.Pre) > 0 { - fmt.Println("Prerelease versions:") - for i, pre := range v.Pre { - fmt.Printf("%d: %q\n", i, pre) - } - } - - // Build meta data - if len(v.Build) > 0 { - fmt.Println("Build meta data:") - for i, build := range v.Build { - fmt.Printf("%d: %q\n", i, build) - } - } - - // Make == Parse (Value), New for Pointer - v001, err := semver.Make("0.0.1") - - fmt.Println("\nUse Version.Compare for comparisons (-1, 0, 1):") - fmt.Printf("%q is greater than %q: Compare == %d\n", v001, v, v001.Compare(v)) - fmt.Printf("%q is less than %q: Compare == %d\n", v, v001, v.Compare(v001)) - fmt.Printf("%q is equal to %q: Compare == %d\n", v, v, v.Compare(v)) - - fmt.Println("\nUse comparison helpers returning booleans:") - fmt.Printf("%q is greater than %q: %t\n", v001, v, v001.GT(v)) - fmt.Printf("%q is greater than equal %q: %t\n", v001, v, v001.GTE(v)) - fmt.Printf("%q is greater than equal %q: %t\n", v, v, v.GTE(v)) - fmt.Printf("%q is less than %q: %t\n", v, v001, v.LT(v001)) - fmt.Printf("%q is less than equal %q: %t\n", v, v001, v.LTE(v001)) - fmt.Printf("%q is less than equal %q: %t\n", v, v, v.LTE(v)) - - fmt.Println("\nManipulate Version in place:") - v.Pre[0], err = semver.NewPRVersion("beta") - if err != nil { - fmt.Printf("Error parsing pre release version: %q", err) - } - fmt.Printf("Version to string: %q\n", v) - - fmt.Println("\nCompare Prerelease versions:") - pre1, _ := semver.NewPRVersion("123") - pre2, _ := semver.NewPRVersion("alpha") - pre3, _ := semver.NewPRVersion("124") - fmt.Printf("%q is less than %q: Compare == %d\n", pre1, pre2, pre1.Compare(pre2)) - fmt.Printf("%q is greater than %q: Compare == %d\n", pre3, pre1, pre3.Compare(pre1)) - fmt.Printf("%q is equal to %q: Compare == %d\n", pre1, pre1, pre1.Compare(pre1)) - - fmt.Println("\nValidate versions:") - v.Build[0] = "?" - - err = v.Validate() - if err != nil { - fmt.Printf("Validation failed: %s\n", err) - } - - fmt.Println("Create valid build meta data:") - b1, _ := semver.NewBuildVersion("build123") - v.Build[0] = b1 - fmt.Printf("Version with new build version %q\n", v) - - _, err = semver.NewBuildVersion("build?123") - if err != nil { - fmt.Printf("Create build version failed: %s\n", err) - } -} diff --git a/Godeps/_workspace/src/github.com/blang/semver/json_test.go b/Godeps/_workspace/src/github.com/blang/semver/json_test.go deleted file mode 100644 index 039117da9..000000000 --- a/Godeps/_workspace/src/github.com/blang/semver/json_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package semver - -import ( - "encoding/json" - "strconv" - "testing" -) - -func TestJSONMarshal(t *testing.T) { - versionString := "3.1.4-alpha.1.5.9+build.2.6.5" - v, err := Parse(versionString) - if err != nil { - t.Fatal(err) - } - - versionJSON, err := json.Marshal(v) - if err != nil { - t.Fatal(err) - } - - quotedVersionString := strconv.Quote(versionString) - - if string(versionJSON) != quotedVersionString { - t.Fatalf("JSON marshaled semantic version not equal: expected %q, got %q", quotedVersionString, string(versionJSON)) - } -} - -func TestJSONUnmarshal(t *testing.T) { - versionString := "3.1.4-alpha.1.5.9+build.2.6.5" - quotedVersionString := strconv.Quote(versionString) - - var v Version - if err := json.Unmarshal([]byte(quotedVersionString), &v); err != nil { - t.Fatal(err) - } - - if v.String() != versionString { - t.Fatalf("JSON unmarshaled semantic version not equal: expected %q, got %q", versionString, v.String()) - } - - badVersionString := strconv.Quote("3.1.4.1.5.9.2.6.5-other-digits-of-pi") - if err := json.Unmarshal([]byte(badVersionString), &v); err == nil { - t.Fatal("expected JSON unmarshal error, got nil") - } -} diff --git a/Godeps/_workspace/src/github.com/blang/semver/semver_test.go b/Godeps/_workspace/src/github.com/blang/semver/semver_test.go deleted file mode 100644 index e56ebce05..000000000 --- a/Godeps/_workspace/src/github.com/blang/semver/semver_test.go +++ /dev/null @@ -1,417 +0,0 @@ -package semver - -import ( - "testing" -) - -func prstr(s string) PRVersion { - return PRVersion{s, 0, false} -} - -func prnum(i uint64) PRVersion { - return PRVersion{"", i, true} -} - -type formatTest struct { - v Version - result string -} - -var formatTests = []formatTest{ - {Version{1, 2, 3, nil, nil}, "1.2.3"}, - {Version{0, 0, 1, nil, nil}, "0.0.1"}, - {Version{0, 0, 1, []PRVersion{prstr("alpha"), prstr("preview")}, []string{"123", "456"}}, "0.0.1-alpha.preview+123.456"}, - {Version{1, 2, 3, []PRVersion{prstr("alpha"), prnum(1)}, []string{"123", "456"}}, "1.2.3-alpha.1+123.456"}, - {Version{1, 2, 3, []PRVersion{prstr("alpha"), prnum(1)}, nil}, "1.2.3-alpha.1"}, - {Version{1, 2, 3, nil, []string{"123", "456"}}, "1.2.3+123.456"}, - // Prereleases and build metadata hyphens - {Version{1, 2, 3, []PRVersion{prstr("alpha"), prstr("b-eta")}, []string{"123", "b-uild"}}, "1.2.3-alpha.b-eta+123.b-uild"}, - {Version{1, 2, 3, nil, []string{"123", "b-uild"}}, "1.2.3+123.b-uild"}, - {Version{1, 2, 3, []PRVersion{prstr("alpha"), prstr("b-eta")}, nil}, "1.2.3-alpha.b-eta"}, -} - -func TestStringer(t *testing.T) { - for _, test := range formatTests { - if res := test.v.String(); res != test.result { - t.Errorf("Stringer, expected %q but got %q", test.result, res) - } - } -} - -func TestParse(t *testing.T) { - for _, test := range formatTests { - if v, err := Parse(test.result); err != nil { - t.Errorf("Error parsing %q: %q", test.result, err) - } else if comp := v.Compare(test.v); comp != 0 { - t.Errorf("Parsing, expected %q but got %q, comp: %d ", test.v, v, comp) - } else if err := v.Validate(); err != nil { - t.Errorf("Error validating parsed version %q: %q", test.v, err) - } - } -} - -func TestMustParse(t *testing.T) { - _ = MustParse("32.2.1-alpha") -} - -func TestMustParse_panic(t *testing.T) { - defer func() { - if recover() == nil { - t.Errorf("Should have panicked") - } - }() - _ = MustParse("invalid version") -} - -func TestValidate(t *testing.T) { - for _, test := range formatTests { - if err := test.v.Validate(); err != nil { - t.Errorf("Error validating %q: %q", test.v, err) - } - } -} - -type compareTest struct { - v1 Version - v2 Version - result int -} - -var compareTests = []compareTest{ - {Version{1, 0, 0, nil, nil}, Version{1, 0, 0, nil, nil}, 0}, - {Version{2, 0, 0, nil, nil}, Version{1, 0, 0, nil, nil}, 1}, - {Version{0, 1, 0, nil, nil}, Version{0, 1, 0, nil, nil}, 0}, - {Version{0, 2, 0, nil, nil}, Version{0, 1, 0, nil, nil}, 1}, - {Version{0, 0, 1, nil, nil}, Version{0, 0, 1, nil, nil}, 0}, - {Version{0, 0, 2, nil, nil}, Version{0, 0, 1, nil, nil}, 1}, - {Version{1, 2, 3, nil, nil}, Version{1, 2, 3, nil, nil}, 0}, - {Version{2, 2, 4, nil, nil}, Version{1, 2, 4, nil, nil}, 1}, - {Version{1, 3, 3, nil, nil}, Version{1, 2, 3, nil, nil}, 1}, - {Version{1, 2, 4, nil, nil}, Version{1, 2, 3, nil, nil}, 1}, - - // Spec Examples #11 - {Version{1, 0, 0, nil, nil}, Version{2, 0, 0, nil, nil}, -1}, - {Version{2, 0, 0, nil, nil}, Version{2, 1, 0, nil, nil}, -1}, - {Version{2, 1, 0, nil, nil}, Version{2, 1, 1, nil, nil}, -1}, - - // Spec Examples #9 - {Version{1, 0, 0, nil, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, 1}, - {Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha"), prnum(1)}, nil}, -1}, - {Version{1, 0, 0, []PRVersion{prstr("alpha"), prnum(1)}, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha"), prstr("beta")}, nil}, -1}, - {Version{1, 0, 0, []PRVersion{prstr("alpha"), prstr("beta")}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta")}, nil}, -1}, - {Version{1, 0, 0, []PRVersion{prstr("beta")}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(2)}, nil}, -1}, - {Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(2)}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(11)}, nil}, -1}, - {Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(11)}, nil}, Version{1, 0, 0, []PRVersion{prstr("rc"), prnum(1)}, nil}, -1}, - {Version{1, 0, 0, []PRVersion{prstr("rc"), prnum(1)}, nil}, Version{1, 0, 0, nil, nil}, -1}, - - // Ignore Build metadata - {Version{1, 0, 0, nil, []string{"1", "2", "3"}}, Version{1, 0, 0, nil, nil}, 0}, -} - -func TestCompare(t *testing.T) { - for _, test := range compareTests { - if res := test.v1.Compare(test.v2); res != test.result { - t.Errorf("Comparing %q : %q, expected %d but got %d", test.v1, test.v2, test.result, res) - } - //Test counterpart - if res := test.v2.Compare(test.v1); res != -test.result { - t.Errorf("Comparing %q : %q, expected %d but got %d", test.v2, test.v1, -test.result, res) - } - } -} - -type wrongformatTest struct { - v *Version - str string -} - -var wrongformatTests = []wrongformatTest{ - {nil, ""}, - {nil, "."}, - {nil, "1."}, - {nil, ".1"}, - {nil, "a.b.c"}, - {nil, "1.a.b"}, - {nil, "1.1.a"}, - {nil, "1.a.1"}, - {nil, "a.1.1"}, - {nil, ".."}, - {nil, "1.."}, - {nil, "1.1."}, - {nil, "1..1"}, - {nil, "1.1.+123"}, - {nil, "1.1.-beta"}, - {nil, "-1.1.1"}, - {nil, "1.-1.1"}, - {nil, "1.1.-1"}, - // giant numbers - {nil, "20000000000000000000.1.1"}, - {nil, "1.20000000000000000000.1"}, - {nil, "1.1.20000000000000000000"}, - {nil, "1.1.1-20000000000000000000"}, - // Leading zeroes - {nil, "01.1.1"}, - {nil, "001.1.1"}, - {nil, "1.01.1"}, - {nil, "1.001.1"}, - {nil, "1.1.01"}, - {nil, "1.1.001"}, - {nil, "1.1.1-01"}, - {nil, "1.1.1-001"}, - {nil, "1.1.1-beta.01"}, - {nil, "1.1.1-beta.001"}, - {&Version{0, 0, 0, []PRVersion{prstr("!")}, nil}, "0.0.0-!"}, - {&Version{0, 0, 0, nil, []string{"!"}}, "0.0.0+!"}, - // empty prversion - {&Version{0, 0, 0, []PRVersion{prstr(""), prstr("alpha")}, nil}, "0.0.0-.alpha"}, - // empty build meta data - {&Version{0, 0, 0, []PRVersion{prstr("alpha")}, []string{""}}, "0.0.0-alpha+"}, - {&Version{0, 0, 0, []PRVersion{prstr("alpha")}, []string{"test", ""}}, "0.0.0-alpha+test."}, -} - -func TestWrongFormat(t *testing.T) { - for _, test := range wrongformatTests { - - if res, err := Parse(test.str); err == nil { - t.Errorf("Parsing wrong format version %q, expected error but got %q", test.str, res) - } - - if test.v != nil { - if err := test.v.Validate(); err == nil { - t.Errorf("Validating wrong format version %q (%q), expected error", test.v, test.str) - } - } - } -} - -func TestCompareHelper(t *testing.T) { - v := Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil} - v1 := Version{1, 0, 0, nil, nil} - if !v.EQ(v) { - t.Errorf("%q should be equal to %q", v, v) - } - if !v.Equals(v) { - t.Errorf("%q should be equal to %q", v, v) - } - if !v1.NE(v) { - t.Errorf("%q should not be equal to %q", v1, v) - } - if !v.GTE(v) { - t.Errorf("%q should be greater than or equal to %q", v, v) - } - if !v.LTE(v) { - t.Errorf("%q should be less than or equal to %q", v, v) - } - if !v.LT(v1) { - t.Errorf("%q should be less than %q", v, v1) - } - if !v.LTE(v1) { - t.Errorf("%q should be less than or equal %q", v, v1) - } - if !v.LE(v1) { - t.Errorf("%q should be less than or equal %q", v, v1) - } - if !v1.GT(v) { - t.Errorf("%q should be greater than %q", v1, v) - } - if !v1.GTE(v) { - t.Errorf("%q should be greater than or equal %q", v1, v) - } - if !v1.GE(v) { - t.Errorf("%q should be greater than or equal %q", v1, v) - } -} - -func TestPreReleaseVersions(t *testing.T) { - p1, err := NewPRVersion("123") - if !p1.IsNumeric() { - t.Errorf("Expected numeric prversion, got %q", p1) - } - if p1.VersionNum != 123 { - t.Error("Wrong prversion number") - } - if err != nil { - t.Errorf("Not expected error %q", err) - } - p2, err := NewPRVersion("alpha") - if p2.IsNumeric() { - t.Errorf("Expected non-numeric prversion, got %q", p2) - } - if p2.VersionStr != "alpha" { - t.Error("Wrong prversion string") - } - if err != nil { - t.Errorf("Not expected error %q", err) - } -} - -func TestBuildMetaDataVersions(t *testing.T) { - _, err := NewBuildVersion("123") - if err != nil { - t.Errorf("Unexpected error %q", err) - } - - _, err = NewBuildVersion("build") - if err != nil { - t.Errorf("Unexpected error %q", err) - } - - _, err = NewBuildVersion("test?") - if err == nil { - t.Error("Expected error, got none") - } - - _, err = NewBuildVersion("") - if err == nil { - t.Error("Expected error, got none") - } -} - -func TestNewHelper(t *testing.T) { - v, err := New("1.2.3") - if err != nil { - t.Fatalf("Unexpected error %q", err) - } - - // New returns pointer - if v == nil { - t.Fatal("Version is nil") - } - if v.Compare(Version{1, 2, 3, nil, nil}) != 0 { - t.Fatal("Unexpected comparison problem") - } -} - -func TestMakeHelper(t *testing.T) { - v, err := Make("1.2.3") - if err != nil { - t.Fatalf("Unexpected error %q", err) - } - if v.Compare(Version{1, 2, 3, nil, nil}) != 0 { - t.Fatal("Unexpected comparison problem") - } -} - -func BenchmarkParseSimple(b *testing.B) { - const VERSION = "0.0.1" - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - Parse(VERSION) - } -} - -func BenchmarkParseComplex(b *testing.B) { - const VERSION = "0.0.1-alpha.preview+123.456" - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - Parse(VERSION) - } -} - -func BenchmarkParseAverage(b *testing.B) { - l := len(formatTests) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - Parse(formatTests[n%l].result) - } -} - -func BenchmarkStringSimple(b *testing.B) { - const VERSION = "0.0.1" - v, _ := Parse(VERSION) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - v.String() - } -} - -func BenchmarkStringLarger(b *testing.B) { - const VERSION = "11.15.2012" - v, _ := Parse(VERSION) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - v.String() - } -} - -func BenchmarkStringComplex(b *testing.B) { - const VERSION = "0.0.1-alpha.preview+123.456" - v, _ := Parse(VERSION) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - v.String() - } -} - -func BenchmarkStringAverage(b *testing.B) { - l := len(formatTests) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - formatTests[n%l].v.String() - } -} - -func BenchmarkValidateSimple(b *testing.B) { - const VERSION = "0.0.1" - v, _ := Parse(VERSION) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - v.Validate() - } -} - -func BenchmarkValidateComplex(b *testing.B) { - const VERSION = "0.0.1-alpha.preview+123.456" - v, _ := Parse(VERSION) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - v.Validate() - } -} - -func BenchmarkValidateAverage(b *testing.B) { - l := len(formatTests) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - formatTests[n%l].v.Validate() - } -} - -func BenchmarkCompareSimple(b *testing.B) { - const VERSION = "0.0.1" - v, _ := Parse(VERSION) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - v.Compare(v) - } -} - -func BenchmarkCompareComplex(b *testing.B) { - const VERSION = "0.0.1-alpha.preview+123.456" - v, _ := Parse(VERSION) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - v.Compare(v) - } -} - -func BenchmarkCompareAverage(b *testing.B) { - l := len(compareTests) - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - compareTests[n%l].v1.Compare((compareTests[n%l].v2)) - } -} diff --git a/Godeps/_workspace/src/github.com/blang/semver/sort_test.go b/Godeps/_workspace/src/github.com/blang/semver/sort_test.go deleted file mode 100644 index 68893972a..000000000 --- a/Godeps/_workspace/src/github.com/blang/semver/sort_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package semver - -import ( - "reflect" - "testing" -) - -func TestSort(t *testing.T) { - v100, _ := Parse("1.0.0") - v010, _ := Parse("0.1.0") - v001, _ := Parse("0.0.1") - versions := []Version{v010, v100, v001} - Sort(versions) - - correct := []Version{v001, v010, v100} - if !reflect.DeepEqual(versions, correct) { - t.Fatalf("Sort returned wrong order: %s", versions) - } -} - -func BenchmarkSort(b *testing.B) { - v100, _ := Parse("1.0.0") - v010, _ := Parse("0.1.0") - v001, _ := Parse("0.0.1") - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - Sort([]Version{v010, v100, v001}) - } -} diff --git a/Godeps/_workspace/src/github.com/blang/semver/sql_test.go b/Godeps/_workspace/src/github.com/blang/semver/sql_test.go deleted file mode 100644 index ebf48b584..000000000 --- a/Godeps/_workspace/src/github.com/blang/semver/sql_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package semver - -import ( - "testing" -) - -type scanTest struct { - val interface{} - shouldError bool - expected string -} - -var scanTests = []scanTest{ - {"1.2.3", false, "1.2.3"}, - {[]byte("1.2.3"), false, "1.2.3"}, - {7, true, ""}, - {7e4, true, ""}, - {true, true, ""}, -} - -func TestScanString(t *testing.T) { - for _, tc := range scanTests { - s := &Version{} - err := s.Scan(tc.val) - if tc.shouldError { - if err == nil { - t.Fatalf("Scan did not return an error on %v (%T)", tc.val, tc.val) - } - } else { - if err != nil { - t.Fatalf("Scan returned an unexpected error: %s (%T) on %v (%T)", tc.val, tc.val, tc.val, tc.val) - } - if val, _ := s.Value(); val != tc.expected { - t.Errorf("Wrong Value returned, expected %q, got %q", tc.expected, val) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/cpuguy83/go-md2man/LICENSE.md b/Godeps/_workspace/src/github.com/cpuguy83/go-md2man/LICENSE.md new file mode 100644 index 000000000..1cade6cef --- /dev/null +++ b/Godeps/_workspace/src/github.com/cpuguy83/go-md2man/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Brian Goff + +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/Godeps/_workspace/src/github.com/davecgh/go-spew/LICENSE b/Godeps/_workspace/src/github.com/davecgh/go-spew/LICENSE new file mode 100644 index 000000000..2a7cfd2bf --- /dev/null +++ b/Godeps/_workspace/src/github.com/davecgh/go-spew/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2012-2013 Dave Collins + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go deleted file mode 100644 index 39b7525b3..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// custom type to test Stinger interface on non-pointer receiver. -type stringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with non-pointer receivers. -func (s stringer) String() string { - return "stringer " + string(s) -} - -// custom type to test Stinger interface on pointer receiver. -type pstringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with only pointer receivers. -func (s *pstringer) String() string { - return "stringer " + string(*s) -} - -// xref1 and xref2 are cross referencing structs for testing circular reference -// detection. -type xref1 struct { - ps2 *xref2 -} -type xref2 struct { - ps1 *xref1 -} - -// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular -// reference for testing detection. -type indirCir1 struct { - ps2 *indirCir2 -} -type indirCir2 struct { - ps3 *indirCir3 -} -type indirCir3 struct { - ps1 *indirCir1 -} - -// embed is used to test embedded structures. -type embed struct { - a string -} - -// embedwrap is used to test embedded structures. -type embedwrap struct { - *embed - e *embed -} - -// panicer is used to intentionally cause a panic for testing spew properly -// handles them -type panicer int - -func (p panicer) String() string { - panic("test panic") -} - -// customError is used to test custom error interface invocation. -type customError int - -func (e customError) Error() string { - return fmt.Sprintf("error: %d", int(e)) -} - -// stringizeWants converts a slice of wanted test output into a format suitable -// for a test error message. -func stringizeWants(wants []string) string { - s := "" - for i, want := range wants { - if i > 0 { - s += fmt.Sprintf("want%d: %s", i+1, want) - } else { - s += "want: " + want - } - } - return s -} - -// testFailed returns whether or not a test failed by checking if the result -// of the test is in the slice of wanted strings. -func testFailed(result string, wants []string) bool { - for _, want := range wants { - if result == want { - return false - } - } - return true -} - -type sortableStruct struct { - x int -} - -func (ss sortableStruct) String() string { - return fmt.Sprintf("ss.%d", ss.x) -} - -type unsortableStruct struct { - x int -} - -type sortTestCase struct { - input []reflect.Value - expected []reflect.Value -} - -func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { - getInterfaces := func(values []reflect.Value) []interface{} { - interfaces := []interface{}{} - for _, v := range values { - interfaces = append(interfaces, v.Interface()) - } - return interfaces - } - - for _, test := range tests { - spew.SortValues(test.input, cs) - // reflect.DeepEqual cannot really make sense of reflect.Value, - // probably because of all the pointer tricks. For instance, - // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} - // instead. - input := getInterfaces(test.input) - expected := getInterfaces(test.expected) - if !reflect.DeepEqual(input, expected) { - t.Errorf("Sort mismatch:\n %v != %v", input, expected) - } - } -} - -// TestSortValues ensures the sort functionality for relect.Value based sorting -// works as intended. -func TestSortValues(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - embedA := v(embed{"a"}) - embedB := v(embed{"b"}) - embedC := v(embed{"c"}) - tests := []sortTestCase{ - // No values. - { - []reflect.Value{}, - []reflect.Value{}, - }, - // Bools. - { - []reflect.Value{v(false), v(true), v(false)}, - []reflect.Value{v(false), v(false), v(true)}, - }, - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Uints. - { - []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, - []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, - }, - // Floats. - { - []reflect.Value{v(2.0), v(1.0), v(3.0)}, - []reflect.Value{v(1.0), v(2.0), v(3.0)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // Array - { - []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, - []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, - }, - // Uintptrs. - { - []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, - []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, - }, - // SortableStructs. - { - // Note: not sorted - DisableMethods is set. - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - // Invalid. - { - []reflect.Value{embedB, embedA, embedC}, - []reflect.Value{embedB, embedA, embedC}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithMethods ensures the sort functionality for relect.Value -// based sorting works as intended when using string methods. -func TestSortValuesWithMethods(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithSpew ensures the sort functionality for relect.Value -// based sorting works as intended when using spew to stringify keys. -func TestSortValuesWithSpew(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} - helpTestSortValues(tests, &cs, t) -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go deleted file mode 100644 index 3dd908917..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go +++ /dev/null @@ -1,1021 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Array containing bytes -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Slice containing bytes -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// dumpTest is used to describe a test to be perfomed against the Dump method. -type dumpTest struct { - in interface{} - wants []string -} - -// dumpTests houses all of the tests to be performed against the Dump method. -var dumpTests = make([]dumpTest, 0) - -// addDumpTest is a helper method to append the passed input and desired result -// to dumpTests -func addDumpTest(in interface{}, wants ...string) { - test := dumpTest{in, wants} - dumpTests = append(dumpTests, test) -} - -func addIntDumpTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addUintDumpTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addBoolDumpTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFloatDumpTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addComplexDumpTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addArrayDumpTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + - vt + ") 2,\n (" + vt + ") 3\n}" - addDumpTest(v, "([3]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[3]"+vt+")()\n") - - // Array containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := [3]pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[3]"+v2t+")()\n") - - // Array containing interfaces. - v3i0 := "one" - v3 := [3]interface{}{v3i0, int(2), uint(3)} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Array containing bytes. - v4 := [34]byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[34]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[34]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addSliceDumpTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + - vt + ") 6.28,\n (" + vt + ") 12.56\n}" - addDumpTest(v, "([]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[]"+vt+")()\n") - - // Slice containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := []pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[]"+v2t+")()\n") - - // Slice containing interfaces. - v3i0 := "one" - v3 := []interface{}{v3i0, int(2), uint(3), nil} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3,\n (" + v3t5 + ") \n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Slice containing bytes. - v4 := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Nil slice. - v5 := []int(nil) - nv5 := (*[]int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "[]int" - v5s := "" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addStringDumpTests() { - // Standard string. - v := "test" - vLen := fmt.Sprintf("%d", len(v)) - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "(len=" + vLen + ") \"test\"" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addInterfaceDumpTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addMapDumpTests() { - // Map with string keys and int vals. - k := "one" - kk := "two" - m := map[string]int{k: 1, kk: 2} - klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up - kkLen := fmt.Sprintf("%d", len(kk)) - mLen := fmt.Sprintf("%d", len(m)) - nilMap := map[string]int(nil) - nm := (*map[string]int)(nil) - pm := &m - mAddr := fmt.Sprintf("%p", pm) - pmAddr := fmt.Sprintf("%p", &pm) - mt := "map[string]int" - mt1 := "string" - mt2 := "int" - ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + - "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + - ") \"two\": (" + mt2 + ") 2\n}" - ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + - "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + - ") \"one\": (" + mt2 + ") 1\n}" - addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") - addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", - "(*"+mt+")("+mAddr+")("+ms2+")\n") - addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", - "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") - addDumpTest(nm, "(*"+mt+")()\n") - addDumpTest(nilMap, "("+mt+") \n") - - // Map with custom formatter type on pointer receiver only keys and vals. - k2 := pstringer("one") - v2 := pstringer("1") - m2 := map[pstringer]pstringer{k2: v2} - k2Len := fmt.Sprintf("%d", len(k2)) - v2Len := fmt.Sprintf("%d", len(v2)) - m2Len := fmt.Sprintf("%d", len(m2)) - nilMap2 := map[pstringer]pstringer(nil) - nm2 := (*map[pstringer]pstringer)(nil) - pm2 := &m2 - m2Addr := fmt.Sprintf("%p", pm2) - pm2Addr := fmt.Sprintf("%p", &pm2) - m2t := "map[spew_test.pstringer]spew_test.pstringer" - m2t1 := "spew_test.pstringer" - m2t2 := "spew_test.pstringer" - m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + - "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" - addDumpTest(m2, "("+m2t+") "+m2s+"\n") - addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") - addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") - addDumpTest(nm2, "(*"+m2t+")()\n") - addDumpTest(nilMap2, "("+m2t+") \n") - - // Map with interface keys and values. - k3 := "one" - k3Len := fmt.Sprintf("%d", len(k3)) - m3 := map[interface{}]interface{}{k3: 1} - m3Len := fmt.Sprintf("%d", len(m3)) - nilMap3 := map[interface{}]interface{}(nil) - nm3 := (*map[interface{}]interface{})(nil) - pm3 := &m3 - m3Addr := fmt.Sprintf("%p", pm3) - pm3Addr := fmt.Sprintf("%p", &pm3) - m3t := "map[interface {}]interface {}" - m3t1 := "string" - m3t2 := "int" - m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + - "\"one\": (" + m3t2 + ") 1\n}" - addDumpTest(m3, "("+m3t+") "+m3s+"\n") - addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") - addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") - addDumpTest(nm3, "(*"+m3t+")()\n") - addDumpTest(nilMap3, "("+m3t+") \n") - - // Map with nil interface value. - k4 := "nil" - k4Len := fmt.Sprintf("%d", len(k4)) - m4 := map[string]interface{}{k4: nil} - m4Len := fmt.Sprintf("%d", len(m4)) - nilMap4 := map[string]interface{}(nil) - nm4 := (*map[string]interface{})(nil) - pm4 := &m4 - m4Addr := fmt.Sprintf("%p", pm4) - pm4Addr := fmt.Sprintf("%p", &pm4) - m4t := "map[string]interface {}" - m4t1 := "string" - m4t2 := "interface {}" - m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + - " \"nil\": (" + m4t2 + ") \n}" - addDumpTest(m4, "("+m4t+") "+m4s+"\n") - addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") - addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") - addDumpTest(nm4, "(*"+m4t+")()\n") - addDumpTest(nilMap4, "("+m4t+") \n") -} - -func addStructDumpTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + - v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + - ") (len=5) stringer test2\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - eLen := fmt.Sprintf("%d", len("embedstr")) - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + - ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + - ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + - " \"embedstr\"\n })\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addUintptrDumpTests() { - // Null pointer. - v := uintptr(0) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - nv2 := (*uintptr)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addUnsafePointerDumpTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addChanDumpTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFuncDumpTests() { - // Function with no params and no returns. - v := addIntDumpTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Function with param and no returns. - v2 := TestDump - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") -} - -func addCircularDumpTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + - vAddr + ")()\n })\n}" - vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + - ")()\n })\n })\n}" - v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")()\n })\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + - ")()\n })\n })\n })\n}" - v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")()\n })\n })\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") -} - -func addPanicDumpTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addErrorDumpTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -// TestDump executes all of the tests described by dumpTests. -func TestDump(t *testing.T) { - // Setup tests. - addIntDumpTests() - addUintDumpTests() - addBoolDumpTests() - addFloatDumpTests() - addComplexDumpTests() - addArrayDumpTests() - addSliceDumpTests() - addStringDumpTests() - addInterfaceDumpTests() - addMapDumpTests() - addStructDumpTests() - addUintptrDumpTests() - addUnsafePointerDumpTests() - addChanDumpTests() - addFuncDumpTests() - addCircularDumpTests() - addPanicDumpTests() - addErrorDumpTests() - addCgoDumpTests() - - t.Logf("Running %d tests", len(dumpTests)) - for i, test := range dumpTests { - buf := new(bytes.Buffer) - spew.Fdump(buf, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) - continue - } - } -} - -func TestDumpSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := `(map[int]string) (len=3) { -(int) 1: (string) (len=1) "1", -(int) 2: (string) (len=1) "2", -(int) 3: (string) (len=1) "3" -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = `(map[spew_test.stringer]int) (len=3) { -(spew_test.stringer) (len=1) stringer 1: (int) 1, -(spew_test.stringer) (len=1) stringer 2: (int) 2, -(spew_test.stringer) (len=1) stringer 3: (int) 3 -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = `(map[spew_test.pstringer]int) (len=3) { -(spew_test.pstringer) (len=1) stringer 1: (int) 1, -(spew_test.pstringer) (len=1) stringer 2: (int) 2, -(spew_test.pstringer) (len=1) stringer 3: (int) 3 -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = `(map[spew_test.customError]int) (len=3) { -(spew_test.customError) error: 1: (int) 1, -(spew_test.customError) error: 2: (int) 2, -(spew_test.customError) error: 3: (int) 3 -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go deleted file mode 100644 index 9b8a358ec..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This means the cgo tests are only added (and hence run) when -// specifially requested. This configuration is used because spew itself -// does not require cgo to run even though it does handle certain cgo types -// specially. Rather than forcing all clients to require cgo and an external -// C compiler just to run the tests, this scheme makes them optional. -// +build cgo,testcgo - -package spew_test - -import ( - "fmt" - "github.com/davecgh/go-spew/spew/testdata" -) - -func addCgoDumpTests() { - // C char pointer. - v := testdata.GetCgoCharPointer() - nv := testdata.GetCgoNullCharPointer() - pv := &v - vcAddr := fmt.Sprintf("%p", v) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "*testdata._Ctype_char" - vs := "116" - addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(nv, "("+vt+")()\n") - - // C char array. - v2, v2l, v2c := testdata.GetCgoCharArray() - v2Len := fmt.Sprintf("%d", v2l) - v2Cap := fmt.Sprintf("%d", v2c) - v2t := "[6]testdata._Ctype_char" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + - "{\n 00000000 74 65 73 74 32 00 " + - " |test2.|\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - - // C unsigned char array. - v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() - v3Len := fmt.Sprintf("%d", v3l) - v3Cap := fmt.Sprintf("%d", v3c) - v3t := "[6]testdata._Ctype_unsignedchar" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + - "{\n 00000000 74 65 73 74 33 00 " + - " |test3.|\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - - // C signed char array. - v4, v4l, v4c := testdata.GetCgoSignedCharArray() - v4Len := fmt.Sprintf("%d", v4l) - v4Cap := fmt.Sprintf("%d", v4c) - v4t := "[6]testdata._Ctype_schar" - v4t2 := "testdata._Ctype_schar" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + - ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + - ") 0\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - - // C uint8_t array. - v5, v5l, v5c := testdata.GetCgoUint8tArray() - v5Len := fmt.Sprintf("%d", v5l) - v5Cap := fmt.Sprintf("%d", v5c) - v5t := "[6]testdata._Ctype_uint8_t" - v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + - "{\n 00000000 74 65 73 74 35 00 " + - " |test5.|\n}" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - - // C typedefed unsigned char array. - v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() - v6Len := fmt.Sprintf("%d", v6l) - v6Cap := fmt.Sprintf("%d", v6c) - v6t := "[6]testdata._Ctype_custom_uchar_t" - v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + - "{\n 00000000 74 65 73 74 36 00 " + - " |test6.|\n}" - addDumpTest(v6, "("+v6t+") "+v6s+"\n") -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go deleted file mode 100644 index 52a0971fb..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when either cgo is not supported or "-tags testcgo" is not added to the go -// test command line. This file intentionally does not setup any cgo tests in -// this scenario. -// +build !cgo !testcgo - -package spew_test - -func addCgoDumpTests() { - // Don't add any tests for cgo since this file is only compiled when - // there should not be any cgo tests. -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go deleted file mode 100644 index a7acd1412..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "github.com/davecgh/go-spew/spew" -) - -type Flag int - -const ( - flagOne Flag = iota - flagTwo -) - -var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", -} - -func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) -} - -type Bar struct { - flag Flag - data uintptr -} - -type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} -} - -// This example demonstrates how to use Dump to dump variables to stdout. -func ExampleDump() { - // The following package level declarations are assumed for this example: - /* - type Flag int - - const ( - flagOne Flag = iota - flagTwo - ) - - var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", - } - - func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) - } - - type Bar struct { - flag Flag - data uintptr - } - - type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} - } - */ - - // Setup some sample data structures for the example. - bar := Bar{Flag(flagTwo), uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - f := Flag(5) - b := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - - // Dump! - spew.Dump(s1, f, b) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // flag: (spew_test.Flag) flagTwo, - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Flag) Unknown flag (5) - // ([]uint8) (len=34 cap=34) { - // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - // 00000020 31 32 |12| - // } - // -} - -// This example demonstrates how to use Printf to display a variable with a -// format string and inline formatting. -func ExamplePrintf() { - // Create a double pointer to a uint 8. - ui8 := uint8(5) - pui8 := &ui8 - ppui8 := &pui8 - - // Create a circular data type. - type circular struct { - ui8 uint8 - c *circular - } - c := circular{ui8: 1} - c.c = &c - - // Print! - spew.Printf("ppui8: %v\n", ppui8) - spew.Printf("circular: %v\n", c) - - // Output: - // ppui8: <**>5 - // circular: {1 <*>{1 <*>}} -} - -// This example demonstrates how to use a ConfigState. -func ExampleConfigState() { - // Modify the indent level of the ConfigState only. The global - // configuration is not modified. - scs := spew.ConfigState{Indent: "\t"} - - // Output using the ConfigState instance. - v := map[string]int{"one": 1} - scs.Printf("v: %v\n", v) - scs.Dump(v) - - // Output: - // v: map[one:1] - // (map[string]int) (len=1) { - // (string) (len=3) "one": (int) 1 - // } -} - -// This example demonstrates how to use ConfigState.Dump to dump variables to -// stdout -func ExampleConfigState_Dump() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances with different indentation. - scs := spew.ConfigState{Indent: "\t"} - scs2 := spew.ConfigState{Indent: " "} - - // Setup some sample data structures for the example. - bar := Bar{Flag(flagTwo), uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - - // Dump using the ConfigState instances. - scs.Dump(s1) - scs2.Dump(s1) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // flag: (spew_test.Flag) flagTwo, - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // flag: (spew_test.Flag) flagTwo, - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // -} - -// This example demonstrates how to use ConfigState.Printf to display a variable -// with a format string and inline formatting. -func ExampleConfigState_Printf() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances and modify the method handling of the - // first ConfigState only. - scs := spew.NewDefaultConfig() - scs2 := spew.NewDefaultConfig() - scs.DisableMethods = true - - // Alternatively - // scs := spew.ConfigState{Indent: " ", DisableMethods: true} - // scs2 := spew.ConfigState{Indent: " "} - - // This is of type Flag which implements a Stringer and has raw value 1. - f := flagTwo - - // Dump using the ConfigState instances. - scs.Printf("f: %v\n", f) - scs2.Printf("f: %v\n", f) - - // Output: - // f: 1 - // f: flagTwo -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go deleted file mode 100644 index b0f9761a4..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go +++ /dev/null @@ -1,1535 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -- Type that has a custom Error interface -- %x passthrough with uint -- %#x passthrough with uint -- %f passthrough with precision -- %f passthrough with width and precision -- %d passthrough with width -- %q passthrough with string -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// formatterTest is used to describe a test to be perfomed against NewFormatter. -type formatterTest struct { - format string - in interface{} - wants []string -} - -// formatterTests houses all of the tests to be performed against NewFormatter. -var formatterTests = make([]formatterTest, 0) - -// addFormatterTest is a helper method to append the passed input and desired -// result to formatterTests. -func addFormatterTest(format string, in interface{}, wants ...string) { - test := formatterTest{format, in, wants} - formatterTests = append(formatterTests, test) -} - -func addIntFormatterTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") -} - -func addUintFormatterTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") -} - -func addBoolFormatterTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFloatFormatterTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addComplexFormatterTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addArrayFormatterTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[3]int" - vs := "[1 2 3]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Array containing type with custom formatter on pointer receiver only. - v2 := [3]pstringer{"1", "2", "3"} - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[3]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Array containing interfaces. - v3 := [3]interface{}{"one", int(2), uint(3)} - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "[one 2 3]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addSliceFormatterTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[]float32" - vs := "[3.14 6.28 12.56]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Slice containing type with custom formatter on pointer receiver only. - v2 := []pstringer{"1", "2", "3"} - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Slice containing interfaces. - v3 := []interface{}{"one", int(2), uint(3), nil} - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "[one 2 3 ]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + - ")]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Nil slice. - var v4 []int - nv4 := (*[]int)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]int" - v4s := "" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStringFormatterTests() { - // Standard string. - v := "test" - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "test" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addInterfaceFormatterTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addMapFormatterTests() { - // Map with string keys and int vals. - v := map[string]int{"one": 1, "two": 2} - nilMap := map[string]int(nil) - nv := (*map[string]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "map[string]int" - vs := "map[one:1 two:2]" - vs2 := "map[two:2 one:1]" - addFormatterTest("%v", v, vs, vs2) - addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, - "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) - addFormatterTest("%#v", nilMap, "("+vt+")"+"") - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, - "(*"+vt+")("+vAddr+")"+vs2) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, - "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%#+v", nilMap, "("+vt+")"+"") - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Map with custom formatter type on pointer receiver only keys and vals. - v2 := map[pstringer]pstringer{"one": "1"} - nv2 := (*map[pstringer]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "map[spew_test.pstringer]spew_test.pstringer" - v2s := "map[stringer one:stringer 1]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Map with interface keys and values. - v3 := map[interface{}]interface{}{"one": 1} - nv3 := (*map[interface{}]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "map[interface {}]interface {}" - v3t1 := "string" - v3t2 := "int" - v3s := "map[one:1]" - v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Map with nil interface value - v4 := map[string]interface{}{"nil": nil} - nv4 := (*map[string]interface{})(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "map[string]interface {}" - v4t1 := "interface {}" - v4s := "map[nil:]" - v4s2 := "map[nil:(" + v4t1 + ")]" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStructFormatterTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{127 255}" - vs2 := "{a:127 b:255}" - vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs3) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs3) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{{127 255} true}" - v2s2 := "{s1:{a:127 b:255} b:true}" - v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + - v2t5 + ")true}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s2) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{stringer test stringer test2}" - v3s2 := "{s:stringer test S:stringer test2}" - v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s2) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{<*>{embedstr} <*>{embedstr}}" - v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + - "){a:embedstr}}" - v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + - "){a:(" + v4t3 + ")embedstr}}" - v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + - ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s2) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addUintptrFormatterTests() { - // Null pointer. - v := uintptr(0) - nv := (*uintptr)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addUnsafePointerFormatterTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addChanFormatterTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFuncFormatterTests() { - // Function with no params and no returns. - v := addIntFormatterTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Function with param and no returns. - v2 := TestFormatter - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addCircularFormatterTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{<*>{<*>}}" - vs2 := "{<*>}" - vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" - vs4 := "{c:<*>(" + vAddr + ")}" - vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" - vs6 := "{c:(*" + vt + ")}" - vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + - ")}}" - vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs2) - addFormatterTest("%+v", v, vs3) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) - addFormatterTest("%#v", v, "("+vt+")"+vs5) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) - addFormatterTest("%#+v", v, "("+vt+")"+vs7) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{<*>{<*>{<*>}}}" - v2s2 := "{<*>{<*>}}" - v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + - ts2Addr + ")}}}" - v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" - v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + - ")}}}" - v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" - v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + - ")}}}" - v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + ")}}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s2) - addFormatterTest("%v", &pv2, "<**>"+v2s2) - addFormatterTest("%+v", v2, v2s3) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{<*>{<*>{<*>{<*>}}}}" - v3s2 := "{<*>{<*>{<*>}}}" - v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" - v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + ")}}}" - v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - "){ps2:(*" + v3t2 + ")}}}}" - v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - ")}}}" - v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + - ")(" + tic2Addr + ")}}}}" - v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s2) - addFormatterTest("%v", &pv3, "<**>"+v3s2) - addFormatterTest("%+v", v3, v3s3) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) - addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) -} - -func addPanicFormatterTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addErrorFormatterTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addPassthroughFormatterTests() { - // %x passthrough with uint. - v := uint(4294967295) - pv := &v - vAddr := fmt.Sprintf("%x", pv) - pvAddr := fmt.Sprintf("%x", &pv) - vs := "ffffffff" - addFormatterTest("%x", v, vs) - addFormatterTest("%x", pv, vAddr) - addFormatterTest("%x", &pv, pvAddr) - - // %#x passthrough with uint. - v2 := int(2147483647) - pv2 := &v2 - v2Addr := fmt.Sprintf("%#x", pv2) - pv2Addr := fmt.Sprintf("%#x", &pv2) - v2s := "0x7fffffff" - addFormatterTest("%#x", v2, v2s) - addFormatterTest("%#x", pv2, v2Addr) - addFormatterTest("%#x", &pv2, pv2Addr) - - // %f passthrough with precision. - addFormatterTest("%.2f", 3.1415, "3.14") - addFormatterTest("%.3f", 3.1415, "3.142") - addFormatterTest("%.4f", 3.1415, "3.1415") - - // %f passthrough with width and precision. - addFormatterTest("%5.2f", 3.1415, " 3.14") - addFormatterTest("%6.3f", 3.1415, " 3.142") - addFormatterTest("%7.4f", 3.1415, " 3.1415") - - // %d passthrough with width. - addFormatterTest("%3d", 127, "127") - addFormatterTest("%4d", 127, " 127") - addFormatterTest("%5d", 127, " 127") - - // %q passthrough with string. - addFormatterTest("%q", "test", "\"test\"") -} - -// TestFormatter executes all of the tests described by formatterTests. -func TestFormatter(t *testing.T) { - // Setup tests. - addIntFormatterTests() - addUintFormatterTests() - addBoolFormatterTests() - addFloatFormatterTests() - addComplexFormatterTests() - addArrayFormatterTests() - addSliceFormatterTests() - addStringFormatterTests() - addInterfaceFormatterTests() - addMapFormatterTests() - addStructFormatterTests() - addUintptrFormatterTests() - addUnsafePointerFormatterTests() - addChanFormatterTests() - addFuncFormatterTests() - addCircularFormatterTests() - addPanicFormatterTests() - addErrorFormatterTests() - addPassthroughFormatterTests() - - t.Logf("Running %d tests", len(formatterTests)) - for i, test := range formatterTests { - buf := new(bytes.Buffer) - spew.Fprintf(buf, test.format, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, - stringizeWants(test.wants)) - continue - } - } -} - -type testStruct struct { - x int -} - -func (ts testStruct) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -type testStructP struct { - x int -} - -func (ts *testStructP) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -func TestPrintSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "map[1:1 2:2 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "map[error: 1:1 error: 2:2 error: 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go deleted file mode 100644 index b583bfdef..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" - "unsafe" -) - -// dummyFmtState implements a fake fmt.State to use for testing invalid -// reflect.Value handling. This is necessary because the fmt package catches -// invalid values before invoking the formatter on them. -type dummyFmtState struct { - bytes.Buffer -} - -func (dfs *dummyFmtState) Flag(f int) bool { - if f == int('+') { - return true - } - return false -} - -func (dfs *dummyFmtState) Precision() (int, bool) { - return 0, false -} - -func (dfs *dummyFmtState) Width() (int, bool) { - return 0, false -} - -// TestInvalidReflectValue ensures the dump and formatter code handles an -// invalid reflect value properly. This needs access to internal state since it -// should never happen in real code and therefore can't be tested via the public -// API. -func TestInvalidReflectValue(t *testing.T) { - i := 1 - - // Dump invalid reflect value. - v := new(reflect.Value) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(*v) - s := buf.String() - want := "" - if s != want { - t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter invalid reflect value. - buf2 := new(dummyFmtState) - f := formatState{value: *v, cs: &Config, fs: buf2} - f.format(*v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) - } -} - -// changeKind uses unsafe to intentionally change the kind of a reflect.Value to -// the maximum kind value which does not exist. This is needed to test the -// fallback code which punts to the standard fmt library for new types that -// might get added to the language. -func changeKind(v *reflect.Value, readOnly bool) { - rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag)) - *rvf = *rvf | ((1< - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "bytes" - "fmt" - "github.com/davecgh/go-spew/spew" - "io/ioutil" - "os" - "testing" -) - -// spewFunc is used to identify which public function of the spew package or -// ConfigState a test applies to. -type spewFunc int - -const ( - fCSFdump spewFunc = iota - fCSFprint - fCSFprintf - fCSFprintln - fCSPrint - fCSPrintln - fCSSdump - fCSSprint - fCSSprintf - fCSSprintln - fCSErrorf - fCSNewFormatter - fErrorf - fFprint - fFprintln - fPrint - fPrintln - fSdump - fSprint - fSprintf - fSprintln -) - -// Map of spewFunc values to names for pretty printing. -var spewFuncStrings = map[spewFunc]string{ - fCSFdump: "ConfigState.Fdump", - fCSFprint: "ConfigState.Fprint", - fCSFprintf: "ConfigState.Fprintf", - fCSFprintln: "ConfigState.Fprintln", - fCSSdump: "ConfigState.Sdump", - fCSPrint: "ConfigState.Print", - fCSPrintln: "ConfigState.Println", - fCSSprint: "ConfigState.Sprint", - fCSSprintf: "ConfigState.Sprintf", - fCSSprintln: "ConfigState.Sprintln", - fCSErrorf: "ConfigState.Errorf", - fCSNewFormatter: "ConfigState.NewFormatter", - fErrorf: "spew.Errorf", - fFprint: "spew.Fprint", - fFprintln: "spew.Fprintln", - fPrint: "spew.Print", - fPrintln: "spew.Println", - fSdump: "spew.Sdump", - fSprint: "spew.Sprint", - fSprintf: "spew.Sprintf", - fSprintln: "spew.Sprintln", -} - -func (f spewFunc) String() string { - if s, ok := spewFuncStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) -} - -// spewTest is used to describe a test to be performed against the public -// functions of the spew package or ConfigState. -type spewTest struct { - cs *spew.ConfigState - f spewFunc - format string - in interface{} - want string -} - -// spewTests houses the tests to be performed against the public functions of -// the spew package and ConfigState. -// -// These tests are only intended to ensure the public functions are exercised -// and are intentionally not exhaustive of types. The exhaustive type -// tests are handled in the dump and format tests. -var spewTests []spewTest - -// redirStdout is a helper function to return the standard output from f as a -// byte slice. -func redirStdout(f func()) ([]byte, error) { - tempFile, err := ioutil.TempFile("", "ss-test") - if err != nil { - return nil, err - } - fileName := tempFile.Name() - defer os.Remove(fileName) // Ignore error - - origStdout := os.Stdout - os.Stdout = tempFile - f() - os.Stdout = origStdout - tempFile.Close() - - return ioutil.ReadFile(fileName) -} - -func initSpewTests() { - // Config states with various settings. - scsDefault := spew.NewDefaultConfig() - scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} - scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} - scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} - scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} - - // Variables for tests on types which implement Stringer interface with and - // without a pointer receiver. - ts := stringer("test") - tps := pstringer("test") - - // depthTester is used to test max depth handling for structs, array, slices - // and maps. - type depthTester struct { - ic indirCir1 - arr [1]string - slice []string - m map[string]int - } - dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, - map[string]int{"one": 1}} - - // Variable for tests on types which implement error interface. - te := customError(10) - - spewTests = []spewTest{ - {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, - {scsDefault, fCSFprint, "", int16(32767), "32767"}, - {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, - {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, - {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, - {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, - {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, - {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, - {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, - {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, - {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, - {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, - {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, - {scsDefault, fFprint, "", float32(3.14), "3.14"}, - {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, - {scsDefault, fPrint, "", true, "true"}, - {scsDefault, fPrintln, "", false, "false\n"}, - {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, - {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, - {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, - {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, - {scsNoMethods, fCSFprint, "", ts, "test"}, - {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, - {scsNoMethods, fCSFprint, "", tps, "test"}, - {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, - {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, - {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, - {scsNoPmethods, fCSFprint, "", tps, "test"}, - {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, - {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, - {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + - " ic: (spew_test.indirCir1) {\n \n },\n" + - " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + - " slice: ([]string) (len=1 cap=1) {\n \n },\n" + - " m: (map[string]int) (len=1) {\n \n }\n}\n"}, - {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, - {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + - "(len=4) (stringer test) \"test\"\n"}, - {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, - {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + - "(error: 10) 10\n"}, - } -} - -// TestSpew executes all of the tests described by spewTests. -func TestSpew(t *testing.T) { - initSpewTests() - - t.Logf("Running %d tests", len(spewTests)) - for i, test := range spewTests { - buf := new(bytes.Buffer) - switch test.f { - case fCSFdump: - test.cs.Fdump(buf, test.in) - - case fCSFprint: - test.cs.Fprint(buf, test.in) - - case fCSFprintf: - test.cs.Fprintf(buf, test.format, test.in) - - case fCSFprintln: - test.cs.Fprintln(buf, test.in) - - case fCSPrint: - b, err := redirStdout(func() { test.cs.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSPrintln: - b, err := redirStdout(func() { test.cs.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSSdump: - str := test.cs.Sdump(test.in) - buf.WriteString(str) - - case fCSSprint: - str := test.cs.Sprint(test.in) - buf.WriteString(str) - - case fCSSprintf: - str := test.cs.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fCSSprintln: - str := test.cs.Sprintln(test.in) - buf.WriteString(str) - - case fCSErrorf: - err := test.cs.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fCSNewFormatter: - fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) - - case fErrorf: - err := spew.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fFprint: - spew.Fprint(buf, test.in) - - case fFprintln: - spew.Fprintln(buf, test.in) - - case fPrint: - b, err := redirStdout(func() { spew.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fPrintln: - b, err := redirStdout(func() { spew.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fSdump: - str := spew.Sdump(test.in) - buf.WriteString(str) - - case fSprint: - str := spew.Sprint(test.in) - buf.WriteString(str) - - case fSprintf: - str := spew.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fSprintln: - str := spew.Sprintln(test.in) - buf.WriteString(str) - - default: - t.Errorf("%v #%d unrecognized function", test.f, i) - continue - } - s := buf.String() - if test.want != s { - t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) - continue - } - } -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go deleted file mode 100644 index 5c87dd456..000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This code should really only be in the dumpcgo_test.go file, -// but unfortunately Go will not allow cgo in test files, so this is a -// workaround to allow cgo types to be tested. This configuration is used -// because spew itself does not require cgo to run even though it does handle -// certain cgo types specially. Rather than forcing all clients to require cgo -// and an external C compiler just to run the tests, this scheme makes them -// optional. -// +build cgo,testcgo - -package testdata - -/* -#include -typedef unsigned char custom_uchar_t; - -char *ncp = 0; -char *cp = "test"; -char ca[6] = {'t', 'e', 's', 't', '2', '\0'}; -unsigned char uca[6] = {'t', 'e', 's', 't', '3', '\0'}; -signed char sca[6] = {'t', 'e', 's', 't', '4', '\0'}; -uint8_t ui8ta[6] = {'t', 'e', 's', 't', '5', '\0'}; -custom_uchar_t tuca[6] = {'t', 'e', 's', 't', '6', '\0'}; -*/ -import "C" - -// GetCgoNullCharPointer returns a null char pointer via cgo. This is only -// used for tests. -func GetCgoNullCharPointer() interface{} { - return C.ncp -} - -// GetCgoCharPointer returns a char pointer via cgo. This is only used for -// tests. -func GetCgoCharPointer() interface{} { - return C.cp -} - -// GetCgoCharArray returns a char array via cgo and the array's len and cap. -// This is only used for tests. -func GetCgoCharArray() (interface{}, int, int) { - return C.ca, len(C.ca), cap(C.ca) -} - -// GetCgoUnsignedCharArray returns an unsigned char array via cgo and the -// array's len and cap. This is only used for tests. -func GetCgoUnsignedCharArray() (interface{}, int, int) { - return C.uca, len(C.uca), cap(C.uca) -} - -// GetCgoSignedCharArray returns a signed char array via cgo and the array's len -// and cap. This is only used for tests. -func GetCgoSignedCharArray() (interface{}, int, int) { - return C.sca, len(C.sca), cap(C.sca) -} - -// GetCgoUint8tArray returns a uint8_t array via cgo and the array's len and -// cap. This is only used for tests. -func GetCgoUint8tArray() (interface{}, int, int) { - return C.ui8ta, len(C.ui8ta), cap(C.ui8ta) -} - -// GetCgoTypdefedUnsignedCharArray returns a typedefed unsigned char array via -// cgo and the array's len and cap. This is only used for tests. -func GetCgoTypdefedUnsignedCharArray() (interface{}, int, int) { - return C.tuca, len(C.tuca), cap(C.tuca) -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/LICENSE b/Godeps/_workspace/src/github.com/docker/docker/LICENSE new file mode 100644 index 000000000..c7a3f0cfd --- /dev/null +++ b/Godeps/_workspace/src/github.com/docker/docker/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://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 2013-2015 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Godeps/_workspace/src/github.com/docker/docker/NOTICE b/Godeps/_workspace/src/github.com/docker/docker/NOTICE new file mode 100644 index 000000000..6e6f469ab --- /dev/null +++ b/Godeps/_workspace/src/github.com/docker/docker/NOTICE @@ -0,0 +1,19 @@ +Docker +Copyright 2012-2015 Docker, Inc. + +This product includes software developed at Docker, Inc. (https://www.docker.com). + +This product contains software (https://github.com/kr/pty) developed +by Keith Rarick, licensed under the MIT License. + +The following is courtesy of our legal counsel: + + +Use and transfer of Docker may be subject to certain restrictions by the +United States and other governments. +It is your responsibility to ensure that your use and/or transfer does not +violate applicable laws. + +For more information, please see https://www.bis.doc.gov + +See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount_test.go deleted file mode 100644 index 5c7f1b86a..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package mount - -import ( - "os" - "path" - "testing" -) - -func TestMountOptionsParsing(t *testing.T) { - options := "noatime,ro,size=10k" - - flag, data := parseOptions(options) - - if data != "size=10k" { - t.Fatalf("Expected size=10 got %s", data) - } - - expectedFlag := NOATIME | RDONLY - - if flag != expectedFlag { - t.Fatalf("Expected %d got %d", expectedFlag, flag) - } -} - -func TestMounted(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - sourcePath = path.Join(sourceDir, "file.txt") - targetPath = path.Join(targetDir, "file.txt") - ) - - os.Mkdir(sourceDir, 0777) - os.Mkdir(targetDir, 0777) - - f, err := os.Create(sourcePath) - if err != nil { - t.Fatal(err) - } - f.WriteString("hello") - f.Close() - - f, err = os.Create(targetPath) - if err != nil { - t.Fatal(err) - } - f.Close() - - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - mounted, err := Mounted(targetDir) - if err != nil { - t.Fatal(err) - } - if !mounted { - t.Fatalf("Expected %s to be mounted", targetDir) - } - if _, err := os.Stat(targetDir); err != nil { - t.Fatal(err) - } -} - -func TestMountReadonly(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - sourcePath = path.Join(sourceDir, "file.txt") - targetPath = path.Join(targetDir, "file.txt") - ) - - os.Mkdir(sourceDir, 0777) - os.Mkdir(targetDir, 0777) - - f, err := os.Create(sourcePath) - if err != nil { - t.Fatal(err) - } - f.WriteString("hello") - f.Close() - - f, err = os.Create(targetPath) - if err != nil { - t.Fatal(err) - } - f.Close() - - if err := Mount(sourceDir, targetDir, "none", "bind,ro"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - f, err = os.OpenFile(targetPath, os.O_RDWR, 0777) - if err == nil { - t.Fatal("Should not be able to open a ro file as rw") - } -} - -func TestGetMounts(t *testing.T) { - mounts, err := GetMounts() - if err != nil { - t.Fatal(err) - } - - root := false - for _, entry := range mounts { - if entry.Mountpoint == "/" { - root = true - } - } - - if !root { - t.Fatal("/ should be mounted at least") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go deleted file mode 100644 index 812d12e82..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go +++ /dev/null @@ -1,477 +0,0 @@ -// +build linux - -package mount - -import ( - "bytes" - "testing" -) - -const ( - fedoraMountinfo = `15 35 0:3 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw - 16 35 0:14 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw,seclabel - 17 35 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,seclabel,size=8056484k,nr_inodes=2014121,mode=755 - 18 16 0:15 / /sys/kernel/security rw,nosuid,nodev,noexec,relatime shared:7 - securityfs securityfs rw - 19 16 0:13 / /sys/fs/selinux rw,relatime shared:8 - selinuxfs selinuxfs rw - 20 17 0:16 / /dev/shm rw,nosuid,nodev shared:3 - tmpfs tmpfs rw,seclabel - 21 17 0:10 / /dev/pts rw,nosuid,noexec,relatime shared:4 - devpts devpts rw,seclabel,gid=5,mode=620,ptmxmode=000 - 22 35 0:17 / /run rw,nosuid,nodev shared:21 - tmpfs tmpfs rw,seclabel,mode=755 - 23 16 0:18 / /sys/fs/cgroup rw,nosuid,nodev,noexec shared:9 - tmpfs tmpfs rw,seclabel,mode=755 - 24 23 0:19 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime shared:10 - cgroup cgroup rw,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd - 25 16 0:20 / /sys/fs/pstore rw,nosuid,nodev,noexec,relatime shared:20 - pstore pstore rw - 26 23 0:21 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:11 - cgroup cgroup rw,cpuset,clone_children - 27 23 0:22 / /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:12 - cgroup cgroup rw,cpuacct,cpu,clone_children - 28 23 0:23 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:13 - cgroup cgroup rw,memory,clone_children - 29 23 0:24 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime shared:14 - cgroup cgroup rw,devices,clone_children - 30 23 0:25 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime shared:15 - cgroup cgroup rw,freezer,clone_children - 31 23 0:26 / /sys/fs/cgroup/net_cls rw,nosuid,nodev,noexec,relatime shared:16 - cgroup cgroup rw,net_cls,clone_children - 32 23 0:27 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime shared:17 - cgroup cgroup rw,blkio,clone_children - 33 23 0:28 / /sys/fs/cgroup/perf_event rw,nosuid,nodev,noexec,relatime shared:18 - cgroup cgroup rw,perf_event,clone_children - 34 23 0:29 / /sys/fs/cgroup/hugetlb rw,nosuid,nodev,noexec,relatime shared:19 - cgroup cgroup rw,hugetlb,clone_children - 35 1 253:2 / / rw,relatime shared:1 - ext4 /dev/mapper/ssd-root--f20 rw,seclabel,data=ordered - 36 15 0:30 / /proc/sys/fs/binfmt_misc rw,relatime shared:22 - autofs systemd-1 rw,fd=38,pgrp=1,timeout=300,minproto=5,maxproto=5,direct - 37 17 0:12 / /dev/mqueue rw,relatime shared:23 - mqueue mqueue rw,seclabel - 38 35 0:31 / /tmp rw shared:24 - tmpfs tmpfs rw,seclabel - 39 17 0:32 / /dev/hugepages rw,relatime shared:25 - hugetlbfs hugetlbfs rw,seclabel - 40 16 0:7 / /sys/kernel/debug rw,relatime shared:26 - debugfs debugfs rw - 41 16 0:33 / /sys/kernel/config rw,relatime shared:27 - configfs configfs rw - 42 35 0:34 / /var/lib/nfs/rpc_pipefs rw,relatime shared:28 - rpc_pipefs sunrpc rw - 43 15 0:35 / /proc/fs/nfsd rw,relatime shared:29 - nfsd sunrpc rw - 45 35 8:17 / /boot rw,relatime shared:30 - ext4 /dev/sdb1 rw,seclabel,data=ordered - 46 35 253:4 / /home rw,relatime shared:31 - ext4 /dev/mapper/ssd-home rw,seclabel,data=ordered - 47 35 253:5 / /var/lib/libvirt/images rw,noatime,nodiratime shared:32 - ext4 /dev/mapper/ssd-virt rw,seclabel,discard,data=ordered - 48 35 253:12 / /mnt/old rw,relatime shared:33 - ext4 /dev/mapper/HelpDeskRHEL6-FedoraRoot rw,seclabel,data=ordered - 121 22 0:36 / /run/user/1000/gvfs rw,nosuid,nodev,relatime shared:104 - fuse.gvfsd-fuse gvfsd-fuse rw,user_id=1000,group_id=1000 - 124 16 0:37 / /sys/fs/fuse/connections rw,relatime shared:107 - fusectl fusectl rw - 165 38 253:3 / /tmp/mnt rw,relatime shared:147 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered - 167 35 253:15 / /var/lib/docker/devicemapper/mnt/aae4076022f0e2b80a2afbf8fc6df450c52080191fcef7fb679a73e6f073e5c2 rw,relatime shared:149 - ext4 /dev/mapper/docker-253:2-425882-aae4076022f0e2b80a2afbf8fc6df450c52080191fcef7fb679a73e6f073e5c2 rw,seclabel,discard,stripe=16,data=ordered - 171 35 253:16 / /var/lib/docker/devicemapper/mnt/c71be651f114db95180e472f7871b74fa597ee70a58ccc35cb87139ddea15373 rw,relatime shared:153 - ext4 /dev/mapper/docker-253:2-425882-c71be651f114db95180e472f7871b74fa597ee70a58ccc35cb87139ddea15373 rw,seclabel,discard,stripe=16,data=ordered - 175 35 253:17 / /var/lib/docker/devicemapper/mnt/1bac6ab72862d2d5626560df6197cf12036b82e258c53d981fa29adce6f06c3c rw,relatime shared:157 - ext4 /dev/mapper/docker-253:2-425882-1bac6ab72862d2d5626560df6197cf12036b82e258c53d981fa29adce6f06c3c rw,seclabel,discard,stripe=16,data=ordered - 179 35 253:18 / /var/lib/docker/devicemapper/mnt/d710a357d77158e80d5b2c55710ae07c94e76d34d21ee7bae65ce5418f739b09 rw,relatime shared:161 - ext4 /dev/mapper/docker-253:2-425882-d710a357d77158e80d5b2c55710ae07c94e76d34d21ee7bae65ce5418f739b09 rw,seclabel,discard,stripe=16,data=ordered - 183 35 253:19 / /var/lib/docker/devicemapper/mnt/6479f52366114d5f518db6837254baab48fab39f2ac38d5099250e9a6ceae6c7 rw,relatime shared:165 - ext4 /dev/mapper/docker-253:2-425882-6479f52366114d5f518db6837254baab48fab39f2ac38d5099250e9a6ceae6c7 rw,seclabel,discard,stripe=16,data=ordered - 187 35 253:20 / /var/lib/docker/devicemapper/mnt/8d9df91c4cca5aef49eeb2725292aab324646f723a7feab56be34c2ad08268e1 rw,relatime shared:169 - ext4 /dev/mapper/docker-253:2-425882-8d9df91c4cca5aef49eeb2725292aab324646f723a7feab56be34c2ad08268e1 rw,seclabel,discard,stripe=16,data=ordered - 191 35 253:21 / /var/lib/docker/devicemapper/mnt/c8240b768603d32e920d365dc9d1dc2a6af46cd23e7ae819947f969e1b4ec661 rw,relatime shared:173 - ext4 /dev/mapper/docker-253:2-425882-c8240b768603d32e920d365dc9d1dc2a6af46cd23e7ae819947f969e1b4ec661 rw,seclabel,discard,stripe=16,data=ordered - 195 35 253:22 / /var/lib/docker/devicemapper/mnt/2eb3a01278380bbf3ed12d86ac629eaa70a4351301ee307a5cabe7b5f3b1615f rw,relatime shared:177 - ext4 /dev/mapper/docker-253:2-425882-2eb3a01278380bbf3ed12d86ac629eaa70a4351301ee307a5cabe7b5f3b1615f rw,seclabel,discard,stripe=16,data=ordered - 199 35 253:23 / /var/lib/docker/devicemapper/mnt/37a17fb7c9d9b80821235d5f2662879bd3483915f245f9b49cdaa0e38779b70b rw,relatime shared:181 - ext4 /dev/mapper/docker-253:2-425882-37a17fb7c9d9b80821235d5f2662879bd3483915f245f9b49cdaa0e38779b70b rw,seclabel,discard,stripe=16,data=ordered - 203 35 253:24 / /var/lib/docker/devicemapper/mnt/aea459ae930bf1de913e2f29428fd80ee678a1e962d4080019d9f9774331ee2b rw,relatime shared:185 - ext4 /dev/mapper/docker-253:2-425882-aea459ae930bf1de913e2f29428fd80ee678a1e962d4080019d9f9774331ee2b rw,seclabel,discard,stripe=16,data=ordered - 207 35 253:25 / /var/lib/docker/devicemapper/mnt/928ead0bc06c454bd9f269e8585aeae0a6bd697f46dc8754c2a91309bc810882 rw,relatime shared:189 - ext4 /dev/mapper/docker-253:2-425882-928ead0bc06c454bd9f269e8585aeae0a6bd697f46dc8754c2a91309bc810882 rw,seclabel,discard,stripe=16,data=ordered - 211 35 253:26 / /var/lib/docker/devicemapper/mnt/0f284d18481d671644706e7a7244cbcf63d590d634cc882cb8721821929d0420 rw,relatime shared:193 - ext4 /dev/mapper/docker-253:2-425882-0f284d18481d671644706e7a7244cbcf63d590d634cc882cb8721821929d0420 rw,seclabel,discard,stripe=16,data=ordered - 215 35 253:27 / /var/lib/docker/devicemapper/mnt/d9dd16722ab34c38db2733e23f69e8f4803ce59658250dd63e98adff95d04919 rw,relatime shared:197 - ext4 /dev/mapper/docker-253:2-425882-d9dd16722ab34c38db2733e23f69e8f4803ce59658250dd63e98adff95d04919 rw,seclabel,discard,stripe=16,data=ordered - 219 35 253:28 / /var/lib/docker/devicemapper/mnt/bc4500479f18c2c08c21ad5282e5f826a016a386177d9874c2764751c031d634 rw,relatime shared:201 - ext4 /dev/mapper/docker-253:2-425882-bc4500479f18c2c08c21ad5282e5f826a016a386177d9874c2764751c031d634 rw,seclabel,discard,stripe=16,data=ordered - 223 35 253:29 / /var/lib/docker/devicemapper/mnt/7770c8b24eb3d5cc159a065910076938910d307ab2f5d94e1dc3b24c06ee2c8a rw,relatime shared:205 - ext4 /dev/mapper/docker-253:2-425882-7770c8b24eb3d5cc159a065910076938910d307ab2f5d94e1dc3b24c06ee2c8a rw,seclabel,discard,stripe=16,data=ordered - 227 35 253:30 / /var/lib/docker/devicemapper/mnt/c280cd3d0bf0aa36b478b292279671624cceafc1a67eaa920fa1082601297adf rw,relatime shared:209 - ext4 /dev/mapper/docker-253:2-425882-c280cd3d0bf0aa36b478b292279671624cceafc1a67eaa920fa1082601297adf rw,seclabel,discard,stripe=16,data=ordered - 231 35 253:31 / /var/lib/docker/devicemapper/mnt/8b59a7d9340279f09fea67fd6ad89ddef711e9e7050eb647984f8b5ef006335f rw,relatime shared:213 - ext4 /dev/mapper/docker-253:2-425882-8b59a7d9340279f09fea67fd6ad89ddef711e9e7050eb647984f8b5ef006335f rw,seclabel,discard,stripe=16,data=ordered - 235 35 253:32 / /var/lib/docker/devicemapper/mnt/1a28059f29eda821578b1bb27a60cc71f76f846a551abefabce6efd0146dce9f rw,relatime shared:217 - ext4 /dev/mapper/docker-253:2-425882-1a28059f29eda821578b1bb27a60cc71f76f846a551abefabce6efd0146dce9f rw,seclabel,discard,stripe=16,data=ordered - 239 35 253:33 / /var/lib/docker/devicemapper/mnt/e9aa60c60128cad1 rw,relatime shared:221 - ext4 /dev/mapper/docker-253:2-425882-e9aa60c60128cad1 rw,seclabel,discard,stripe=16,data=ordered - 243 35 253:34 / /var/lib/docker/devicemapper/mnt/5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d-init rw,relatime shared:225 - ext4 /dev/mapper/docker-253:2-425882-5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d-init rw,seclabel,discard,stripe=16,data=ordered - 247 35 253:35 / /var/lib/docker/devicemapper/mnt/5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d rw,relatime shared:229 - ext4 /dev/mapper/docker-253:2-425882-5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d rw,seclabel,discard,stripe=16,data=ordered - 31 21 0:23 / /DATA/foo_bla_bla rw,relatime - cifs //foo/BLA\040BLA\040BLA/ rw,sec=ntlm,cache=loose,unc=\\foo\BLA BLA BLA,username=my_login,domain=mydomain.com,uid=12345678,forceuid,gid=12345678,forcegid,addr=10.1.30.10,file_mode=0755,dir_mode=0755,nounix,rsize=61440,wsize=65536,actimeo=1` - - ubuntuMountInfo = `15 20 0:14 / /sys rw,nosuid,nodev,noexec,relatime - sysfs sysfs rw -16 20 0:3 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw -17 20 0:5 / /dev rw,relatime - devtmpfs udev rw,size=1015140k,nr_inodes=253785,mode=755 -18 17 0:11 / /dev/pts rw,nosuid,noexec,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000 -19 20 0:15 / /run rw,nosuid,noexec,relatime - tmpfs tmpfs rw,size=205044k,mode=755 -20 1 253:0 / / rw,relatime - ext4 /dev/disk/by-label/DOROOT rw,errors=remount-ro,data=ordered -21 15 0:16 / /sys/fs/cgroup rw,relatime - tmpfs none rw,size=4k,mode=755 -22 15 0:17 / /sys/fs/fuse/connections rw,relatime - fusectl none rw -23 15 0:6 / /sys/kernel/debug rw,relatime - debugfs none rw -24 15 0:10 / /sys/kernel/security rw,relatime - securityfs none rw -25 19 0:18 / /run/lock rw,nosuid,nodev,noexec,relatime - tmpfs none rw,size=5120k -26 21 0:19 / /sys/fs/cgroup/cpuset rw,relatime - cgroup cgroup rw,cpuset,clone_children -27 19 0:20 / /run/shm rw,nosuid,nodev,relatime - tmpfs none rw -28 21 0:21 / /sys/fs/cgroup/cpu rw,relatime - cgroup cgroup rw,cpu -29 19 0:22 / /run/user rw,nosuid,nodev,noexec,relatime - tmpfs none rw,size=102400k,mode=755 -30 15 0:23 / /sys/fs/pstore rw,relatime - pstore none rw -31 21 0:24 / /sys/fs/cgroup/cpuacct rw,relatime - cgroup cgroup rw,cpuacct -32 21 0:25 / /sys/fs/cgroup/memory rw,relatime - cgroup cgroup rw,memory -33 21 0:26 / /sys/fs/cgroup/devices rw,relatime - cgroup cgroup rw,devices -34 21 0:27 / /sys/fs/cgroup/freezer rw,relatime - cgroup cgroup rw,freezer -35 21 0:28 / /sys/fs/cgroup/blkio rw,relatime - cgroup cgroup rw,blkio -36 21 0:29 / /sys/fs/cgroup/perf_event rw,relatime - cgroup cgroup rw,perf_event -37 21 0:30 / /sys/fs/cgroup/hugetlb rw,relatime - cgroup cgroup rw,hugetlb -38 21 0:31 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime - cgroup systemd rw,name=systemd -39 20 0:32 / /var/lib/docker/aufs/mnt/b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc rw,relatime - aufs none rw,si=caafa54fdc06525 -40 20 0:33 / /var/lib/docker/aufs/mnt/2eed44ac7ce7c75af04f088ed6cb4ce9d164801e91d78c6db65d7ef6d572bba8-init rw,relatime - aufs none rw,si=caafa54f882b525 -41 20 0:34 / /var/lib/docker/aufs/mnt/2eed44ac7ce7c75af04f088ed6cb4ce9d164801e91d78c6db65d7ef6d572bba8 rw,relatime - aufs none rw,si=caafa54f8829525 -42 20 0:35 / /var/lib/docker/aufs/mnt/16f4d7e96dd612903f425bfe856762f291ff2e36a8ecd55a2209b7d7cd81c30b rw,relatime - aufs none rw,si=caafa54f882d525 -43 20 0:36 / /var/lib/docker/aufs/mnt/63ca08b75d7438a9469a5954e003f48ffede73541f6286ce1cb4d7dd4811da7e-init rw,relatime - aufs none rw,si=caafa54f882f525 -44 20 0:37 / /var/lib/docker/aufs/mnt/63ca08b75d7438a9469a5954e003f48ffede73541f6286ce1cb4d7dd4811da7e rw,relatime - aufs none rw,si=caafa54f88ba525 -45 20 0:38 / /var/lib/docker/aufs/mnt/283f35a910233c756409313be71ecd8fcfef0df57108b8d740b61b3e88860452 rw,relatime - aufs none rw,si=caafa54f88b8525 -46 20 0:39 / /var/lib/docker/aufs/mnt/2c6c7253d4090faa3886871fb21bd660609daeb0206588c0602007f7d0f254b1-init rw,relatime - aufs none rw,si=caafa54f88be525 -47 20 0:40 / /var/lib/docker/aufs/mnt/2c6c7253d4090faa3886871fb21bd660609daeb0206588c0602007f7d0f254b1 rw,relatime - aufs none rw,si=caafa54f882c525 -48 20 0:41 / /var/lib/docker/aufs/mnt/de2b538c97d6366cc80e8658547c923ea1d042f85580df379846f36a4df7049d rw,relatime - aufs none rw,si=caafa54f85bb525 -49 20 0:42 / /var/lib/docker/aufs/mnt/94a3d8ed7c27e5b0aa71eba46c736bfb2742afda038e74f2dd6035fb28415b49-init rw,relatime - aufs none rw,si=caafa54fdc00525 -50 20 0:43 / /var/lib/docker/aufs/mnt/94a3d8ed7c27e5b0aa71eba46c736bfb2742afda038e74f2dd6035fb28415b49 rw,relatime - aufs none rw,si=caafa54fbaec525 -51 20 0:44 / /var/lib/docker/aufs/mnt/6ac1cace985c9fc9bea32234de8b36dba49bdd5e29a2972b327ff939d78a6274 rw,relatime - aufs none rw,si=caafa54f8e1a525 -52 20 0:45 / /var/lib/docker/aufs/mnt/dff147033e3a0ef061e1de1ad34256b523d4a8c1fa6bba71a0ab538e8628ff0b-init rw,relatime - aufs none rw,si=caafa54f8e1d525 -53 20 0:46 / /var/lib/docker/aufs/mnt/dff147033e3a0ef061e1de1ad34256b523d4a8c1fa6bba71a0ab538e8628ff0b rw,relatime - aufs none rw,si=caafa54f8e1b525 -54 20 0:47 / /var/lib/docker/aufs/mnt/cabb117d997f0f93519185aea58389a9762770b7496ed0b74a3e4a083fa45902 rw,relatime - aufs none rw,si=caafa54f810a525 -55 20 0:48 / /var/lib/docker/aufs/mnt/e1c8a94ffaa9d532bbbdc6ef771ce8a6c2c06757806ecaf8b68e9108fec65f33-init rw,relatime - aufs none rw,si=caafa54f8529525 -56 20 0:49 / /var/lib/docker/aufs/mnt/e1c8a94ffaa9d532bbbdc6ef771ce8a6c2c06757806ecaf8b68e9108fec65f33 rw,relatime - aufs none rw,si=caafa54f852f525 -57 20 0:50 / /var/lib/docker/aufs/mnt/16a1526fa445b84ce84f89506d219e87fa488a814063baf045d88b02f21166b3 rw,relatime - aufs none rw,si=caafa54f9e1d525 -58 20 0:51 / /var/lib/docker/aufs/mnt/57b9c92e1e368fa7dbe5079f7462e917777829caae732828b003c355fe49da9f-init rw,relatime - aufs none rw,si=caafa54f854d525 -59 20 0:52 / /var/lib/docker/aufs/mnt/57b9c92e1e368fa7dbe5079f7462e917777829caae732828b003c355fe49da9f rw,relatime - aufs none rw,si=caafa54f854e525 -60 20 0:53 / /var/lib/docker/aufs/mnt/e370c3e286bea027917baa0e4d251262681a472a87056e880dfd0513516dffd9 rw,relatime - aufs none rw,si=caafa54f840a525 -61 20 0:54 / /var/lib/docker/aufs/mnt/6b00d3b4f32b41997ec07412b5e18204f82fbe643e7122251cdeb3582abd424e-init rw,relatime - aufs none rw,si=caafa54f8408525 -62 20 0:55 / /var/lib/docker/aufs/mnt/6b00d3b4f32b41997ec07412b5e18204f82fbe643e7122251cdeb3582abd424e rw,relatime - aufs none rw,si=caafa54f8409525 -63 20 0:56 / /var/lib/docker/aufs/mnt/abd0b5ea5d355a67f911475e271924a5388ee60c27185fcd60d095afc4a09dc7 rw,relatime - aufs none rw,si=caafa54f9eb1525 -64 20 0:57 / /var/lib/docker/aufs/mnt/336222effc3f7b89867bb39ff7792ae5412c35c749f127c29159d046b6feedd2-init rw,relatime - aufs none rw,si=caafa54f85bf525 -65 20 0:58 / /var/lib/docker/aufs/mnt/336222effc3f7b89867bb39ff7792ae5412c35c749f127c29159d046b6feedd2 rw,relatime - aufs none rw,si=caafa54f85b8525 -66 20 0:59 / /var/lib/docker/aufs/mnt/912e1bf28b80a09644503924a8a1a4fb8ed10b808ca847bda27a369919aa52fa rw,relatime - aufs none rw,si=caafa54fbaea525 -67 20 0:60 / /var/lib/docker/aufs/mnt/386f722875013b4a875118367abc783fc6617a3cb7cf08b2b4dcf550b4b9c576-init rw,relatime - aufs none rw,si=caafa54f8472525 -68 20 0:61 / /var/lib/docker/aufs/mnt/386f722875013b4a875118367abc783fc6617a3cb7cf08b2b4dcf550b4b9c576 rw,relatime - aufs none rw,si=caafa54f8474525 -69 20 0:62 / /var/lib/docker/aufs/mnt/5aaebb79ef3097dfca377889aeb61a0c9d5e3795117d2b08d0751473c671dfb2 rw,relatime - aufs none rw,si=caafa54f8c5e525 -70 20 0:63 / /var/lib/docker/aufs/mnt/5ba3e493279d01277d583600b81c7c079e691b73c3a2bdea8e4b12a35a418be2-init rw,relatime - aufs none rw,si=caafa54f8c3b525 -71 20 0:64 / /var/lib/docker/aufs/mnt/5ba3e493279d01277d583600b81c7c079e691b73c3a2bdea8e4b12a35a418be2 rw,relatime - aufs none rw,si=caafa54f8c3d525 -72 20 0:65 / /var/lib/docker/aufs/mnt/2777f0763da4de93f8bebbe1595cc77f739806a158657b033eca06f827b6028a rw,relatime - aufs none rw,si=caafa54f8c3e525 -73 20 0:66 / /var/lib/docker/aufs/mnt/5d7445562acf73c6f0ae34c3dd0921d7457de1ba92a587d9e06a44fa209eeb3e-init rw,relatime - aufs none rw,si=caafa54f8c39525 -74 20 0:67 / /var/lib/docker/aufs/mnt/5d7445562acf73c6f0ae34c3dd0921d7457de1ba92a587d9e06a44fa209eeb3e rw,relatime - aufs none rw,si=caafa54f854f525 -75 20 0:68 / /var/lib/docker/aufs/mnt/06400b526ec18b66639c96efc41a84f4ae0b117cb28dafd56be420651b4084a0 rw,relatime - aufs none rw,si=caafa54f840b525 -76 20 0:69 / /var/lib/docker/aufs/mnt/e051d45ec42d8e3e1cc57bb39871a40de486dc123522e9c067fbf2ca6a357785-init rw,relatime - aufs none rw,si=caafa54fdddf525 -77 20 0:70 / /var/lib/docker/aufs/mnt/e051d45ec42d8e3e1cc57bb39871a40de486dc123522e9c067fbf2ca6a357785 rw,relatime - aufs none rw,si=caafa54f854b525 -78 20 0:71 / /var/lib/docker/aufs/mnt/1ff414fa93fd61ec81b0ab7b365a841ff6545accae03cceac702833aaeaf718f rw,relatime - aufs none rw,si=caafa54f8d85525 -79 20 0:72 / /var/lib/docker/aufs/mnt/c661b2f871dd5360e46a2aebf8f970f6d39a2ff64e06979aa0361227c88128b8-init rw,relatime - aufs none rw,si=caafa54f8da3525 -80 20 0:73 / /var/lib/docker/aufs/mnt/c661b2f871dd5360e46a2aebf8f970f6d39a2ff64e06979aa0361227c88128b8 rw,relatime - aufs none rw,si=caafa54f8da2525 -81 20 0:74 / /var/lib/docker/aufs/mnt/b68b1d4fe4d30016c552398e78b379a39f651661d8e1fa5f2460c24a5e723420 rw,relatime - aufs none rw,si=caafa54f8d81525 -82 20 0:75 / /var/lib/docker/aufs/mnt/c5c5979c936cd0153a4c626fa9d69ce4fce7d924cc74fa68b025d2f585031739-init rw,relatime - aufs none rw,si=caafa54f8da1525 -83 20 0:76 / /var/lib/docker/aufs/mnt/c5c5979c936cd0153a4c626fa9d69ce4fce7d924cc74fa68b025d2f585031739 rw,relatime - aufs none rw,si=caafa54f8da0525 -84 20 0:77 / /var/lib/docker/aufs/mnt/53e10b0329afc0e0d3322d31efaed4064139dc7027fe6ae445cffd7104bcc94f rw,relatime - aufs none rw,si=caafa54f8c35525 -85 20 0:78 / /var/lib/docker/aufs/mnt/3bfafd09ff2603e2165efacc2215c1f51afabba6c42d04a68cc2df0e8cc31494-init rw,relatime - aufs none rw,si=caafa54f8db8525 -86 20 0:79 / /var/lib/docker/aufs/mnt/3bfafd09ff2603e2165efacc2215c1f51afabba6c42d04a68cc2df0e8cc31494 rw,relatime - aufs none rw,si=caafa54f8dba525 -87 20 0:80 / /var/lib/docker/aufs/mnt/90fdd2c03eeaf65311f88f4200e18aef6d2772482712d9aea01cd793c64781b5 rw,relatime - aufs none rw,si=caafa54f8315525 -88 20 0:81 / /var/lib/docker/aufs/mnt/7bdf2591c06c154ceb23f5e74b1d03b18fbf6fe96e35fbf539b82d446922442f-init rw,relatime - aufs none rw,si=caafa54f8fc6525 -89 20 0:82 / /var/lib/docker/aufs/mnt/7bdf2591c06c154ceb23f5e74b1d03b18fbf6fe96e35fbf539b82d446922442f rw,relatime - aufs none rw,si=caafa54f8468525 -90 20 0:83 / /var/lib/docker/aufs/mnt/8cf9a993f50f3305abad3da268c0fc44ff78a1e7bba595ef9de963497496c3f9 rw,relatime - aufs none rw,si=caafa54f8c59525 -91 20 0:84 / /var/lib/docker/aufs/mnt/ecc896fd74b21840a8d35e8316b92a08b1b9c83d722a12acff847e9f0ff17173-init rw,relatime - aufs none rw,si=caafa54f846a525 -92 20 0:85 / /var/lib/docker/aufs/mnt/ecc896fd74b21840a8d35e8316b92a08b1b9c83d722a12acff847e9f0ff17173 rw,relatime - aufs none rw,si=caafa54f846b525 -93 20 0:86 / /var/lib/docker/aufs/mnt/d8c8288ec920439a48b5796bab5883ee47a019240da65e8d8f33400c31bac5df rw,relatime - aufs none rw,si=caafa54f8dbf525 -94 20 0:87 / /var/lib/docker/aufs/mnt/ecba66710bcd03199b9398e46c005cd6b68d0266ec81dc8b722a29cc417997c6-init rw,relatime - aufs none rw,si=caafa54f810f525 -95 20 0:88 / /var/lib/docker/aufs/mnt/ecba66710bcd03199b9398e46c005cd6b68d0266ec81dc8b722a29cc417997c6 rw,relatime - aufs none rw,si=caafa54fbae9525 -96 20 0:89 / /var/lib/docker/aufs/mnt/befc1c67600df449dddbe796c0d06da7caff1d2bbff64cde1f0ba82d224996b5 rw,relatime - aufs none rw,si=caafa54f8dab525 -97 20 0:90 / /var/lib/docker/aufs/mnt/c9f470e73d2742629cdc4084a1b2c1a8302914f2aa0d0ec4542371df9a050562-init rw,relatime - aufs none rw,si=caafa54fdc02525 -98 20 0:91 / /var/lib/docker/aufs/mnt/c9f470e73d2742629cdc4084a1b2c1a8302914f2aa0d0ec4542371df9a050562 rw,relatime - aufs none rw,si=caafa54f9eb0525 -99 20 0:92 / /var/lib/docker/aufs/mnt/2a31f10029f04ff9d4381167a9b739609853d7220d55a56cb654779a700ee246 rw,relatime - aufs none rw,si=caafa54f8c37525 -100 20 0:93 / /var/lib/docker/aufs/mnt/8c4261b8e3e4b21ebba60389bd64b6261217e7e6b9fd09e201d5a7f6760f6927-init rw,relatime - aufs none rw,si=caafa54fd173525 -101 20 0:94 / /var/lib/docker/aufs/mnt/8c4261b8e3e4b21ebba60389bd64b6261217e7e6b9fd09e201d5a7f6760f6927 rw,relatime - aufs none rw,si=caafa54f8108525 -102 20 0:95 / /var/lib/docker/aufs/mnt/eaa0f57403a3dc685268f91df3fbcd7a8423cee50e1a9ee5c3e1688d9d676bb4 rw,relatime - aufs none rw,si=caafa54f852d525 -103 20 0:96 / /var/lib/docker/aufs/mnt/9cfe69a2cbffd9bfc7f396d4754f6fe5cc457ef417b277797be3762dfe955a6b-init rw,relatime - aufs none rw,si=caafa54f8d80525 -104 20 0:97 / /var/lib/docker/aufs/mnt/9cfe69a2cbffd9bfc7f396d4754f6fe5cc457ef417b277797be3762dfe955a6b rw,relatime - aufs none rw,si=caafa54f8fc3525 -105 20 0:98 / /var/lib/docker/aufs/mnt/d1b322ae17613c6adee84e709641a9244ac56675244a89a64dc0075075fcbb83 rw,relatime - aufs none rw,si=caafa54f8c58525 -106 20 0:99 / /var/lib/docker/aufs/mnt/d46c2a8e9da7e91ab34fd9c192851c246a4e770a46720bda09e55c7554b9dbbd-init rw,relatime - aufs none rw,si=caafa54f8c63525 -107 20 0:100 / /var/lib/docker/aufs/mnt/d46c2a8e9da7e91ab34fd9c192851c246a4e770a46720bda09e55c7554b9dbbd rw,relatime - aufs none rw,si=caafa54f8c67525 -108 20 0:101 / /var/lib/docker/aufs/mnt/bc9d2a264158f83a617a069bf17cbbf2a2ba453db7d3951d9dc63cc1558b1c2b rw,relatime - aufs none rw,si=caafa54f8dbe525 -109 20 0:102 / /var/lib/docker/aufs/mnt/9e6abb8d72bbeb4d5cf24b96018528015ba830ce42b4859965bd482cbd034e99-init rw,relatime - aufs none rw,si=caafa54f9e0d525 -110 20 0:103 / /var/lib/docker/aufs/mnt/9e6abb8d72bbeb4d5cf24b96018528015ba830ce42b4859965bd482cbd034e99 rw,relatime - aufs none rw,si=caafa54f9e1b525 -111 20 0:104 / /var/lib/docker/aufs/mnt/d4dca7b02569c732e740071e1c654d4ad282de5c41edb619af1f0aafa618be26 rw,relatime - aufs none rw,si=caafa54f8dae525 -112 20 0:105 / /var/lib/docker/aufs/mnt/fea63da40fa1c5ffbad430dde0bc64a8fc2edab09a051fff55b673c40a08f6b7-init rw,relatime - aufs none rw,si=caafa54f8c5c525 -113 20 0:106 / /var/lib/docker/aufs/mnt/fea63da40fa1c5ffbad430dde0bc64a8fc2edab09a051fff55b673c40a08f6b7 rw,relatime - aufs none rw,si=caafa54fd172525 -114 20 0:107 / /var/lib/docker/aufs/mnt/e60c57499c0b198a6734f77f660cdbbd950a5b78aa23f470ca4f0cfcc376abef rw,relatime - aufs none rw,si=caafa54909c4525 -115 20 0:108 / /var/lib/docker/aufs/mnt/099c78e7ccd9c8717471bb1bbfff838c0a9913321ba2f214fbeaf92c678e5b35-init rw,relatime - aufs none rw,si=caafa54909c3525 -116 20 0:109 / /var/lib/docker/aufs/mnt/099c78e7ccd9c8717471bb1bbfff838c0a9913321ba2f214fbeaf92c678e5b35 rw,relatime - aufs none rw,si=caafa54909c7525 -117 20 0:110 / /var/lib/docker/aufs/mnt/2997be666d58b9e71469759bcb8bd9608dad0e533a1a7570a896919ba3388825 rw,relatime - aufs none rw,si=caafa54f8557525 -118 20 0:111 / /var/lib/docker/aufs/mnt/730694eff438ef20569df38dfb38a920969d7ff2170cc9aa7cb32a7ed8147a93-init rw,relatime - aufs none rw,si=caafa54c6e88525 -119 20 0:112 / /var/lib/docker/aufs/mnt/730694eff438ef20569df38dfb38a920969d7ff2170cc9aa7cb32a7ed8147a93 rw,relatime - aufs none rw,si=caafa54c6e8e525 -120 20 0:113 / /var/lib/docker/aufs/mnt/a672a1e2f2f051f6e19ed1dfbe80860a2d774174c49f7c476695f5dd1d5b2f67 rw,relatime - aufs none rw,si=caafa54c6e15525 -121 20 0:114 / /var/lib/docker/aufs/mnt/aba3570e17859f76cf29d282d0d150659c6bd80780fdc52a465ba05245c2a420-init rw,relatime - aufs none rw,si=caafa54f8dad525 -122 20 0:115 / /var/lib/docker/aufs/mnt/aba3570e17859f76cf29d282d0d150659c6bd80780fdc52a465ba05245c2a420 rw,relatime - aufs none rw,si=caafa54f8d84525 -123 20 0:116 / /var/lib/docker/aufs/mnt/2abc86007aca46fb4a817a033e2a05ccacae40b78ea4b03f8ea616b9ada40e2e rw,relatime - aufs none rw,si=caafa54c6e8b525 -124 20 0:117 / /var/lib/docker/aufs/mnt/36352f27f7878e648367a135bd1ec3ed497adcb8ac13577ee892a0bd921d2374-init rw,relatime - aufs none rw,si=caafa54c6e8d525 -125 20 0:118 / /var/lib/docker/aufs/mnt/36352f27f7878e648367a135bd1ec3ed497adcb8ac13577ee892a0bd921d2374 rw,relatime - aufs none rw,si=caafa54f8c34525 -126 20 0:119 / /var/lib/docker/aufs/mnt/2f95ca1a629cea8363b829faa727dd52896d5561f2c96ddee4f697ea2fc872c2 rw,relatime - aufs none rw,si=caafa54c6e8a525 -127 20 0:120 / /var/lib/docker/aufs/mnt/f108c8291654f179ef143a3e07de2b5a34adbc0b28194a0ab17742b6db9a7fb2-init rw,relatime - aufs none rw,si=caafa54f8e19525 -128 20 0:121 / /var/lib/docker/aufs/mnt/f108c8291654f179ef143a3e07de2b5a34adbc0b28194a0ab17742b6db9a7fb2 rw,relatime - aufs none rw,si=caafa54fa8c6525 -129 20 0:122 / /var/lib/docker/aufs/mnt/c1d04dfdf8cccb3676d5a91e84e9b0781ce40623d127d038bcfbe4c761b27401 rw,relatime - aufs none rw,si=caafa54f8c30525 -130 20 0:123 / /var/lib/docker/aufs/mnt/3f4898ffd0e1239aeebf1d1412590cdb7254207fa3883663e2c40cf772e5f05a-init rw,relatime - aufs none rw,si=caafa54c6e1a525 -131 20 0:124 / /var/lib/docker/aufs/mnt/3f4898ffd0e1239aeebf1d1412590cdb7254207fa3883663e2c40cf772e5f05a rw,relatime - aufs none rw,si=caafa54c6e1c525 -132 20 0:125 / /var/lib/docker/aufs/mnt/5ae3b6fccb1539fc02d420e86f3e9637bef5b711fed2ca31a2f426c8f5deddbf rw,relatime - aufs none rw,si=caafa54c4fea525 -133 20 0:126 / /var/lib/docker/aufs/mnt/310bfaf80d57020f2e73b06aeffb0b9b0ca2f54895f88bf5e4d1529ccac58fe0-init rw,relatime - aufs none rw,si=caafa54c6e1e525 -134 20 0:127 / /var/lib/docker/aufs/mnt/310bfaf80d57020f2e73b06aeffb0b9b0ca2f54895f88bf5e4d1529ccac58fe0 rw,relatime - aufs none rw,si=caafa54fa8c0525 -135 20 0:128 / /var/lib/docker/aufs/mnt/f382bd5aaccaf2d04a59089ac7cb12ec87efd769fd0c14d623358fbfd2a3f896 rw,relatime - aufs none rw,si=caafa54c4fec525 -136 20 0:129 / /var/lib/docker/aufs/mnt/50d45e9bb2d779bc6362824085564c7578c231af5ae3b3da116acf7e17d00735-init rw,relatime - aufs none rw,si=caafa54c4fef525 -137 20 0:130 / /var/lib/docker/aufs/mnt/50d45e9bb2d779bc6362824085564c7578c231af5ae3b3da116acf7e17d00735 rw,relatime - aufs none rw,si=caafa54c4feb525 -138 20 0:131 / /var/lib/docker/aufs/mnt/a9c5ee0854dc083b6bf62b7eb1e5291aefbb10702289a446471ce73aba0d5d7d rw,relatime - aufs none rw,si=caafa54909c6525 -139 20 0:134 / /var/lib/docker/aufs/mnt/03a613e7bd5078819d1fd92df4e671c0127559a5e0b5a885cc8d5616875162f0-init rw,relatime - aufs none rw,si=caafa54804fe525 -140 20 0:135 / /var/lib/docker/aufs/mnt/03a613e7bd5078819d1fd92df4e671c0127559a5e0b5a885cc8d5616875162f0 rw,relatime - aufs none rw,si=caafa54804fa525 -141 20 0:136 / /var/lib/docker/aufs/mnt/7ec3277e5c04c907051caf9c9c35889f5fcd6463e5485971b25404566830bb70 rw,relatime - aufs none rw,si=caafa54804f9525 -142 20 0:139 / /var/lib/docker/aufs/mnt/26b5b5d71d79a5b2bfcf8bc4b2280ee829f261eb886745dd90997ed410f7e8b8-init rw,relatime - aufs none rw,si=caafa54c6ef6525 -143 20 0:140 / /var/lib/docker/aufs/mnt/26b5b5d71d79a5b2bfcf8bc4b2280ee829f261eb886745dd90997ed410f7e8b8 rw,relatime - aufs none rw,si=caafa54c6ef5525 -144 20 0:356 / /var/lib/docker/aufs/mnt/e6ecde9e2c18cd3c75f424c67b6d89685cfee0fc67abf2cb6bdc0867eb998026 rw,relatime - aufs none rw,si=caafa548068e525` - - gentooMountinfo = `15 1 8:6 / / rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -16 15 0:3 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw -17 15 0:14 / /run rw,nosuid,nodev,relatime - tmpfs tmpfs rw,size=3292172k,mode=755 -18 15 0:5 / /dev rw,nosuid,relatime - devtmpfs udev rw,size=10240k,nr_inodes=4106451,mode=755 -19 18 0:12 / /dev/mqueue rw,nosuid,nodev,noexec,relatime - mqueue mqueue rw -20 18 0:10 / /dev/pts rw,nosuid,noexec,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000 -21 18 0:15 / /dev/shm rw,nosuid,nodev,noexec,relatime - tmpfs shm rw -22 15 0:16 / /sys rw,nosuid,nodev,noexec,relatime - sysfs sysfs rw -23 22 0:7 / /sys/kernel/debug rw,nosuid,nodev,noexec,relatime - debugfs debugfs rw -24 22 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs cgroup_root rw,size=10240k,mode=755 -25 24 0:18 / /sys/fs/cgroup/openrc rw,nosuid,nodev,noexec,relatime - cgroup openrc rw,release_agent=/lib64/rc/sh/cgroup-release-agent.sh,name=openrc -26 24 0:19 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime - cgroup cpuset rw,cpuset,clone_children -27 24 0:20 / /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime - cgroup cpu rw,cpu,clone_children -28 24 0:21 / /sys/fs/cgroup/cpuacct rw,nosuid,nodev,noexec,relatime - cgroup cpuacct rw,cpuacct,clone_children -29 24 0:22 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup memory rw,memory,clone_children -30 24 0:23 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime - cgroup devices rw,devices,clone_children -31 24 0:24 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime - cgroup freezer rw,freezer,clone_children -32 24 0:25 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime - cgroup blkio rw,blkio,clone_children -33 15 8:1 / /boot rw,noatime,nodiratime - vfat /dev/sda1 rw,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro -34 15 8:18 / /mnt/xfs rw,noatime,nodiratime - xfs /dev/sdb2 rw,attr2,inode64,noquota -35 15 0:26 / /tmp rw,relatime - tmpfs tmpfs rw -36 16 0:27 / /proc/sys/fs/binfmt_misc rw,nosuid,nodev,noexec,relatime - binfmt_misc binfmt_misc rw -42 15 0:33 / /var/lib/nfs/rpc_pipefs rw,relatime - rpc_pipefs rpc_pipefs rw -43 16 0:34 / /proc/fs/nfsd rw,nosuid,nodev,noexec,relatime - nfsd nfsd rw -44 15 0:35 / /home/tianon/.gvfs rw,nosuid,nodev,relatime - fuse.gvfs-fuse-daemon gvfs-fuse-daemon rw,user_id=1000,group_id=1000 -68 15 0:3336 / /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd rw,relatime - aufs none rw,si=9b4a7640128db39c -85 68 8:6 /var/lib/docker/init/dockerinit-0.7.2-dev//deleted /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/.dockerinit rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -86 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/config.env /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/.dockerenv rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -87 68 8:6 /etc/resolv.conf /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/resolv.conf rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -88 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/hostname /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/hostname rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -89 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/hosts /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/hosts rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -38 15 0:3384 / /var/lib/docker/aufs/mnt/0292005a9292401bb5197657f2b682d97d8edcb3b72b5e390d2a680139985b55 rw,relatime - aufs none rw,si=9b4a7642b584939c -39 15 0:3385 / /var/lib/docker/aufs/mnt/59db98c889de5f71b70cfb82c40cbe47b64332f0f56042a2987a9e5df6e5e3aa rw,relatime - aufs none rw,si=9b4a7642b584e39c -40 15 0:3386 / /var/lib/docker/aufs/mnt/0545f0f2b6548eb9601d08f35a08f5a0a385407d36027a28f58e06e9f61e0278 rw,relatime - aufs none rw,si=9b4a7642b584b39c -41 15 0:3387 / /var/lib/docker/aufs/mnt/d882cfa16d1aa8fe0331a36e79be3d80b151e49f24fc39a39c3fed1735d5feb5 rw,relatime - aufs none rw,si=9b4a76453040039c -45 15 0:3388 / /var/lib/docker/aufs/mnt/055ca3befcb1626e74f5344b3398724ff05c0de0e20021683d04305c9e70a3f6 rw,relatime - aufs none rw,si=9b4a76453040739c -46 15 0:3389 / /var/lib/docker/aufs/mnt/b899e4567a351745d4285e7f1c18fdece75d877deb3041981cd290be348b7aa6 rw,relatime - aufs none rw,si=9b4a7647def4039c -47 15 0:3390 / /var/lib/docker/aufs/mnt/067ca040292c58954c5129f953219accfae0d40faca26b4d05e76ca76a998f16 rw,relatime - aufs none rw,si=9b4a7647def4239c -48 15 0:3391 / /var/lib/docker/aufs/mnt/8c995e7cb6e5082742daeea720e340b021d288d25d92e0412c03d200df308a11 rw,relatime - aufs none rw,si=9b4a764479c1639c -49 15 0:3392 / /var/lib/docker/aufs/mnt/07cc54dfae5b45300efdacdd53cc72c01b9044956a86ce7bff42d087e426096d rw,relatime - aufs none rw,si=9b4a764479c1739c -50 15 0:3393 / /var/lib/docker/aufs/mnt/0a9c95cf4c589c05b06baa79150b0cc1d8e7102759fe3ce4afaabb8247ca4f85 rw,relatime - aufs none rw,si=9b4a7644059c839c -51 15 0:3394 / /var/lib/docker/aufs/mnt/468fa98cececcf4e226e8370f18f4f848d63faf287fb8321a07f73086441a3a0 rw,relatime - aufs none rw,si=9b4a7644059ca39c -52 15 0:3395 / /var/lib/docker/aufs/mnt/0b826192231c5ce066fffb5beff4397337b5fc19a377aa7c6282c7c0ce7f111f rw,relatime - aufs none rw,si=9b4a764479c1339c -53 15 0:3396 / /var/lib/docker/aufs/mnt/93b8ba1b772fbe79709b909c43ea4b2c30d712e53548f467db1ffdc7a384f196 rw,relatime - aufs none rw,si=9b4a7640798a739c -54 15 0:3397 / /var/lib/docker/aufs/mnt/0c0d0acfb506859b12ef18cdfef9ebed0b43a611482403564224bde9149d373c rw,relatime - aufs none rw,si=9b4a7640798a039c -55 15 0:3398 / /var/lib/docker/aufs/mnt/33648c39ab6c7c74af0243d6d6a81b052e9e25ad1e04b19892eb2dde013e358b rw,relatime - aufs none rw,si=9b4a7644b439b39c -56 15 0:3399 / /var/lib/docker/aufs/mnt/0c12bea97a1c958a3c739fb148536c1c89351d48e885ecda8f0499b5cc44407e rw,relatime - aufs none rw,si=9b4a7640798a239c -57 15 0:3400 / /var/lib/docker/aufs/mnt/ed443988ce125f172d7512e84a4de2627405990fd767a16adefa8ce700c19ce8 rw,relatime - aufs none rw,si=9b4a7644c8ed339c -59 15 0:3402 / /var/lib/docker/aufs/mnt/f61612c324ff3c924d3f7a82fb00a0f8d8f73c248c41897061949e9f5ab7e3b1 rw,relatime - aufs none rw,si=9b4a76442810c39c -60 15 0:3403 / /var/lib/docker/aufs/mnt/0f1ee55c6c4e25027b80de8e64b8b6fb542b3b41aa0caab9261da75752e22bfd rw,relatime - aufs none rw,si=9b4a76442810e39c -61 15 0:3404 / /var/lib/docker/aufs/mnt/956f6cc4af5785cb3ee6963dcbca668219437d9b28f513290b1453ac64a34f97 rw,relatime - aufs none rw,si=9b4a7644303ec39c -62 15 0:3405 / /var/lib/docker/aufs/mnt/1099769158c4b4773e2569e38024e8717e400f87a002c41d8cf47cb81b051ba6 rw,relatime - aufs none rw,si=9b4a7644303ee39c -63 15 0:3406 / /var/lib/docker/aufs/mnt/11890ceb98d4442595b676085cd7b21550ab85c5df841e0fba997ff54e3d522d rw,relatime - aufs none rw,si=9b4a7644303ed39c -64 15 0:3407 / /var/lib/docker/aufs/mnt/acdb90dc378e8ed2420b43a6d291f1c789a081cd1904018780cc038fcd7aae53 rw,relatime - aufs none rw,si=9b4a76434be2139c -65 15 0:3408 / /var/lib/docker/aufs/mnt/120e716f19d4714fbe63cc1ed246204f2c1106eefebc6537ba2587d7e7711959 rw,relatime - aufs none rw,si=9b4a76434be2339c -66 15 0:3409 / /var/lib/docker/aufs/mnt/b197b7fffb61d89e0ba1c40de9a9fc0d912e778b3c1bd828cf981ff37c1963bc rw,relatime - aufs none rw,si=9b4a76434be2039c -70 15 0:3412 / /var/lib/docker/aufs/mnt/1434b69d2e1bb18a9f0b96b9cdac30132b2688f5d1379f68a39a5e120c2f93eb rw,relatime - aufs none rw,si=9b4a76434be2639c -71 15 0:3413 / /var/lib/docker/aufs/mnt/16006e83caf33ab5eb0cd6afc92ea2ee8edeff897496b0bb3ec3a75b767374b3 rw,relatime - aufs none rw,si=9b4a7644d790439c -72 15 0:3414 / /var/lib/docker/aufs/mnt/55bfa5f44e94d27f91f79ba901b118b15098449165c87abf1b53ffff147ff164 rw,relatime - aufs none rw,si=9b4a7644d790239c -73 15 0:3415 / /var/lib/docker/aufs/mnt/1912b97a07ab21ccd98a2a27bc779bf3cf364a3138afa3c3e6f7f169a3c3eab5 rw,relatime - aufs none rw,si=9b4a76441822739c -76 15 0:3418 / /var/lib/docker/aufs/mnt/1a7c3292e8879bd91ffd9282e954f643b1db5683093574c248ff14a9609f2f56 rw,relatime - aufs none rw,si=9b4a76438cb7239c -77 15 0:3419 / /var/lib/docker/aufs/mnt/bb1faaf0d076ddba82c2318305a85f490dafa4e8a8640a8db8ed657c439120cc rw,relatime - aufs none rw,si=9b4a76438cb7339c -78 15 0:3420 / /var/lib/docker/aufs/mnt/1ab869f21d2241a73ac840c7f988490313f909ac642eba71d092204fec66dd7c rw,relatime - aufs none rw,si=9b4a76438cb7639c -79 15 0:3421 / /var/lib/docker/aufs/mnt/fd7245b2cfe3890fa5f5b452260e4edf9e7fb7746532ed9d83f7a0d7dbaa610e rw,relatime - aufs none rw,si=9b4a7644bdc0139c -80 15 0:3422 / /var/lib/docker/aufs/mnt/1e5686c5301f26b9b3cd24e322c608913465cc6c5d0dcd7c5e498d1314747d61 rw,relatime - aufs none rw,si=9b4a7644bdc0639c -81 15 0:3423 / /var/lib/docker/aufs/mnt/52edf6ee6e40bfec1e9301a4d4a92ab83d144e2ae4ce5099e99df6138cb844bf rw,relatime - aufs none rw,si=9b4a7644bdc0239c -82 15 0:3424 / /var/lib/docker/aufs/mnt/1ea10fb7085d28cda4904657dff0454e52598d28e1d77e4f2965bbc3666e808f rw,relatime - aufs none rw,si=9b4a76438cb7139c -83 15 0:3425 / /var/lib/docker/aufs/mnt/9c03e98c3593946dbd4087f8d83f9ca262f4a2efdc952ce60690838b9ba6c526 rw,relatime - aufs none rw,si=9b4a76443020639c -84 15 0:3426 / /var/lib/docker/aufs/mnt/220a2344d67437602c6d2cee9a98c46be13f82c2a8063919dd2fad52bf2fb7dd rw,relatime - aufs none rw,si=9b4a76434bff339c -94 15 0:3427 / /var/lib/docker/aufs/mnt/3b32876c5b200312c50baa476ff342248e88c8ea96e6a1032cd53a88738a1cf2 rw,relatime - aufs none rw,si=9b4a76434bff139c -95 15 0:3428 / /var/lib/docker/aufs/mnt/23ee2b8b0d4ae8db6f6d1e168e2c6f79f8a18f953b09f65e0d22cc1e67a3a6fa rw,relatime - aufs none rw,si=9b4a7646c305c39c -96 15 0:3429 / /var/lib/docker/aufs/mnt/e86e6daa70b61b57945fa178222615f3c3d6bcef12c9f28e9f8623d44dc2d429 rw,relatime - aufs none rw,si=9b4a7646c305f39c -97 15 0:3430 / /var/lib/docker/aufs/mnt/2413d07623e80860bb2e9e306fbdee699afd07525785c025c591231e864aa162 rw,relatime - aufs none rw,si=9b4a76434bff039c -98 15 0:3431 / /var/lib/docker/aufs/mnt/adfd622eb22340fc80b429e5564b125668e260bf9068096c46dd59f1386a4b7d rw,relatime - aufs none rw,si=9b4a7646a7a1039c -102 15 0:3435 / /var/lib/docker/aufs/mnt/27cd92e7a91d02e2d6b44d16679a00fb6d169b19b88822891084e7fd1a84882d rw,relatime - aufs none rw,si=9b4a7646f25ec39c -103 15 0:3436 / /var/lib/docker/aufs/mnt/27dfdaf94cfbf45055c748293c37dd68d9140240bff4c646cb09216015914a88 rw,relatime - aufs none rw,si=9b4a7646732f939c -104 15 0:3437 / /var/lib/docker/aufs/mnt/5ed7524aff68dfbf0fc601cbaeac01bab14391850a973dabf3653282a627920f rw,relatime - aufs none rw,si=9b4a7646732f839c -105 15 0:3438 / /var/lib/docker/aufs/mnt/2a0d4767e536beb5785b60e071e3ac8e5e812613ab143a9627bee77d0c9ab062 rw,relatime - aufs none rw,si=9b4a7646732fe39c -106 15 0:3439 / /var/lib/docker/aufs/mnt/dea3fc045d9f4ae51ba952450b948a822cf85c39411489ca5224f6d9a8d02bad rw,relatime - aufs none rw,si=9b4a764012ad839c -107 15 0:3440 / /var/lib/docker/aufs/mnt/2d140a787160798da60cb67c21b1210054ad4dafecdcf832f015995b9aa99cfd rw,relatime - aufs none rw,si=9b4a764012add39c -108 15 0:3441 / /var/lib/docker/aufs/mnt/cb190b2a8e984475914430fbad2382e0d20b9b659f8ef83ae8d170cc672e519c rw,relatime - aufs none rw,si=9b4a76454d9c239c -109 15 0:3442 / /var/lib/docker/aufs/mnt/2f4a012d5a7ffd90256a6e9aa479054b3dddbc3c6a343f26dafbf3196890223b rw,relatime - aufs none rw,si=9b4a76454d9c439c -110 15 0:3443 / /var/lib/docker/aufs/mnt/63cc77904b80c4ffbf49cb974c5d8733dc52ad7640d3ae87554b325d7312d87f rw,relatime - aufs none rw,si=9b4a76454d9c339c -111 15 0:3444 / /var/lib/docker/aufs/mnt/30333e872c451482ea2d235ff2192e875bd234006b238ae2bdde3b91a86d7522 rw,relatime - aufs none rw,si=9b4a76422cebf39c -112 15 0:3445 / /var/lib/docker/aufs/mnt/6c54fc1125da3925cae65b5c9a98f3be55b0a2c2666082e5094a4ba71beb5bff rw,relatime - aufs none rw,si=9b4a7646dd5a439c -113 15 0:3446 / /var/lib/docker/aufs/mnt/3087d48cb01cda9d0a83a9ca301e6ea40e8593d18c4921be4794c91a420ab9a3 rw,relatime - aufs none rw,si=9b4a7646dd5a739c -114 15 0:3447 / /var/lib/docker/aufs/mnt/cc2607462a8f55b179a749b144c3fdbb50678e1a4f3065ea04e283e9b1f1d8e2 rw,relatime - aufs none rw,si=9b4a7646dd5a239c -117 15 0:3450 / /var/lib/docker/aufs/mnt/310c5e8392b29e8658a22e08d96d63936633b7e2c38e8d220047928b00a03d24 rw,relatime - aufs none rw,si=9b4a7647932d739c -118 15 0:3451 / /var/lib/docker/aufs/mnt/38a1f0029406ba9c3b6058f2f406d8a1d23c855046cf355c91d87d446fcc1460 rw,relatime - aufs none rw,si=9b4a76445abc939c -119 15 0:3452 / /var/lib/docker/aufs/mnt/42e109ab7914ae997a11ccd860fd18e4d488c50c044c3240423ce15774b8b62e rw,relatime - aufs none rw,si=9b4a76445abca39c -120 15 0:3453 / /var/lib/docker/aufs/mnt/365d832af0402d052b389c1e9c0d353b48487533d20cd4351df8e24ec4e4f9d8 rw,relatime - aufs none rw,si=9b4a7644066aa39c -121 15 0:3454 / /var/lib/docker/aufs/mnt/d3fa8a24d695b6cda9b64f96188f701963d28bef0473343f8b212df1a2cf1d2b rw,relatime - aufs none rw,si=9b4a7644066af39c -122 15 0:3455 / /var/lib/docker/aufs/mnt/37d4f491919abc49a15d0c7a7cc8383f087573525d7d288accd14f0b4af9eae0 rw,relatime - aufs none rw,si=9b4a7644066ad39c -123 15 0:3456 / /var/lib/docker/aufs/mnt/93902707fe12cbdd0068ce73f2baad4b3a299189b1b19cb5f8a2025e106ae3f5 rw,relatime - aufs none rw,si=9b4a76444445f39c -126 15 0:3459 / /var/lib/docker/aufs/mnt/3b49291670a625b9bbb329ffba99bf7fa7abff80cefef040f8b89e2b3aad4f9f rw,relatime - aufs none rw,si=9b4a7640798a339c -127 15 0:3460 / /var/lib/docker/aufs/mnt/8d9c7b943cc8f854f4d0d4ec19f7c16c13b0cc4f67a41472a072648610cecb59 rw,relatime - aufs none rw,si=9b4a76427383039c -128 15 0:3461 / /var/lib/docker/aufs/mnt/3b6c90036526c376307df71d49c9f5fce334c01b926faa6a78186842de74beac rw,relatime - aufs none rw,si=9b4a7644badd439c -130 15 0:3463 / /var/lib/docker/aufs/mnt/7b24158eeddfb5d31b7e932e406ea4899fd728344335ff8e0765e89ddeb351dd rw,relatime - aufs none rw,si=9b4a7644badd539c -131 15 0:3464 / /var/lib/docker/aufs/mnt/3ead6dd5773765c74850cf6c769f21fe65c29d622ffa712664f9f5b80364ce27 rw,relatime - aufs none rw,si=9b4a7642f469939c -132 15 0:3465 / /var/lib/docker/aufs/mnt/3f825573b29547744a37b65597a9d6d15a8350be4429b7038d126a4c9a8e178f rw,relatime - aufs none rw,si=9b4a7642f469c39c -133 15 0:3466 / /var/lib/docker/aufs/mnt/f67aaaeb3681e5dcb99a41f847087370bd1c206680cb8c7b6a9819fd6c97a331 rw,relatime - aufs none rw,si=9b4a7647cc25939c -134 15 0:3467 / /var/lib/docker/aufs/mnt/41afe6cfb3c1fc2280b869db07699da88552786e28793f0bc048a265c01bd942 rw,relatime - aufs none rw,si=9b4a7647cc25c39c -135 15 0:3468 / /var/lib/docker/aufs/mnt/b8092ea59da34a40b120e8718c3ae9fa8436996edc4fc50e4b99c72dfd81e1af rw,relatime - aufs none rw,si=9b4a76445abc439c -136 15 0:3469 / /var/lib/docker/aufs/mnt/42c69d2cc179e2684458bb8596a9da6dad182c08eae9b74d5f0e615b399f75a5 rw,relatime - aufs none rw,si=9b4a76455ddbe39c -137 15 0:3470 / /var/lib/docker/aufs/mnt/ea0871954acd2d62a211ac60e05969622044d4c74597870c4f818fbb0c56b09b rw,relatime - aufs none rw,si=9b4a76455ddbf39c -138 15 0:3471 / /var/lib/docker/aufs/mnt/4307906b275ab3fc971786b3841ae3217ac85b6756ddeb7ad4ba09cd044c2597 rw,relatime - aufs none rw,si=9b4a76455ddb839c -139 15 0:3472 / /var/lib/docker/aufs/mnt/4390b872928c53500a5035634f3421622ed6299dc1472b631fc45de9f56dc180 rw,relatime - aufs none rw,si=9b4a76402f2fd39c -140 15 0:3473 / /var/lib/docker/aufs/mnt/6bb41e78863b85e4aa7da89455314855c8c3bda64e52a583bab15dc1fa2e80c2 rw,relatime - aufs none rw,si=9b4a76402f2fa39c -141 15 0:3474 / /var/lib/docker/aufs/mnt/4444f583c2a79c66608f4673a32c9c812154f027045fbd558c2d69920c53f835 rw,relatime - aufs none rw,si=9b4a764479dbd39c -142 15 0:3475 / /var/lib/docker/aufs/mnt/6f11883af4a05ea362e0c54df89058da4859f977efd07b6f539e1f55c1d2a668 rw,relatime - aufs none rw,si=9b4a76402f30b39c -143 15 0:3476 / /var/lib/docker/aufs/mnt/453490dd32e7c2e9ef906f995d8fb3c2753923d1a5e0ba3fd3296e2e4dc238e7 rw,relatime - aufs none rw,si=9b4a76402f30c39c -144 15 0:3477 / /var/lib/docker/aufs/mnt/45e5945735ee102b5e891c91650c57ec4b52bb53017d68f02d50ea8a6e230610 rw,relatime - aufs none rw,si=9b4a76423260739c -147 15 0:3480 / /var/lib/docker/aufs/mnt/4727a64a5553a1125f315b96bed10d3073d6988225a292cce732617c925b56ab rw,relatime - aufs none rw,si=9b4a76443030339c -150 15 0:3483 / /var/lib/docker/aufs/mnt/4e348b5187b9a567059306afc72d42e0ec5c893b0d4abd547526d5f9b6fb4590 rw,relatime - aufs none rw,si=9b4a7644f5d8c39c -151 15 0:3484 / /var/lib/docker/aufs/mnt/4efc616bfbc3f906718b052da22e4335f8e9f91ee9b15866ed3a8029645189ef rw,relatime - aufs none rw,si=9b4a7644f5d8939c -152 15 0:3485 / /var/lib/docker/aufs/mnt/83e730ae9754d5adb853b64735472d98dfa17136b8812ac9cfcd1eba7f4e7d2d rw,relatime - aufs none rw,si=9b4a76469aa7139c -153 15 0:3486 / /var/lib/docker/aufs/mnt/4fc5ba8a5b333be2b7eefacccb626772eeec0ae8a6975112b56c9fb36c0d342f rw,relatime - aufs none rw,si=9b4a7640128dc39c -154 15 0:3487 / /var/lib/docker/aufs/mnt/50200d5edff5dfe8d1ef3c78b0bbd709793ac6e936aa16d74ff66f7ea577b6f9 rw,relatime - aufs none rw,si=9b4a7640128da39c -155 15 0:3488 / /var/lib/docker/aufs/mnt/51e5e51604361448f0b9777f38329f414bc5ba9cf238f26d465ff479bd574b61 rw,relatime - aufs none rw,si=9b4a76444f68939c -156 15 0:3489 / /var/lib/docker/aufs/mnt/52a142149aa98bba83df8766bbb1c629a97b9799944ead90dd206c4bdf0b8385 rw,relatime - aufs none rw,si=9b4a76444f68b39c -157 15 0:3490 / /var/lib/docker/aufs/mnt/52dd21a94a00f58a1ed489312fcfffb91578089c76c5650364476f1d5de031bc rw,relatime - aufs none rw,si=9b4a76444f68f39c -158 15 0:3491 / /var/lib/docker/aufs/mnt/ee562415ddaad353ed22c88d0ca768a0c74bfba6333b6e25c46849ee22d990da rw,relatime - aufs none rw,si=9b4a7640128d839c -159 15 0:3492 / /var/lib/docker/aufs/mnt/db47a9e87173f7554f550c8a01891de79cf12acdd32e01f95c1a527a08bdfb2c rw,relatime - aufs none rw,si=9b4a764405a1d39c -160 15 0:3493 / /var/lib/docker/aufs/mnt/55e827bf6d44d930ec0b827c98356eb8b68c3301e2d60d1429aa72e05b4c17df rw,relatime - aufs none rw,si=9b4a764405a1a39c -162 15 0:3495 / /var/lib/docker/aufs/mnt/578dc4e0a87fc37ec081ca098430499a59639c09f6f12a8f48de29828a091aa6 rw,relatime - aufs none rw,si=9b4a76406d7d439c -163 15 0:3496 / /var/lib/docker/aufs/mnt/728cc1cb04fa4bc6f7bf7a90980beda6d8fc0beb71630874c0747b994efb0798 rw,relatime - aufs none rw,si=9b4a76444f20e39c -164 15 0:3497 / /var/lib/docker/aufs/mnt/5850cc4bd9b55aea46c7ad598f1785117607974084ea643580f58ce3222e683a rw,relatime - aufs none rw,si=9b4a7644a824239c -165 15 0:3498 / /var/lib/docker/aufs/mnt/89443b3f766d5a37bc8b84e29da8b84e6a3ea8486d3cf154e2aae1816516e4a8 rw,relatime - aufs none rw,si=9b4a7644a824139c -166 15 0:3499 / /var/lib/docker/aufs/mnt/f5ae8fd5a41a337907d16515bc3162525154b59c32314c695ecd092c3b47943d rw,relatime - aufs none rw,si=9b4a7644a824439c -167 15 0:3500 / /var/lib/docker/aufs/mnt/5a430854f2a03a9e5f7cbc9f3fb46a8ebca526a5b3f435236d8295e5998798f5 rw,relatime - aufs none rw,si=9b4a7647fc82439c -168 15 0:3501 / /var/lib/docker/aufs/mnt/eda16901ae4cead35070c39845cbf1e10bd6b8cb0ffa7879ae2d8a186e460f91 rw,relatime - aufs none rw,si=9b4a76441e0df39c -169 15 0:3502 / /var/lib/docker/aufs/mnt/5a593721430c2a51b119ff86a7e06ea2b37e3b4131f8f1344d402b61b0c8d868 rw,relatime - aufs none rw,si=9b4a764248bad39c -170 15 0:3503 / /var/lib/docker/aufs/mnt/d662ad0a30fbfa902e0962108685b9330597e1ee2abb16dc9462eb5a67fdd23f rw,relatime - aufs none rw,si=9b4a764248bae39c -171 15 0:3504 / /var/lib/docker/aufs/mnt/5bc9de5c79812843fb36eee96bef1ddba812407861f572e33242f4ee10da2c15 rw,relatime - aufs none rw,si=9b4a764248ba839c -172 15 0:3505 / /var/lib/docker/aufs/mnt/5e763de8e9b0f7d58d2e12a341e029ab4efb3b99788b175090d8209e971156c1 rw,relatime - aufs none rw,si=9b4a764248baa39c -173 15 0:3506 / /var/lib/docker/aufs/mnt/b4431dc2739936f1df6387e337f5a0c99cf051900c896bd7fd46a870ce61c873 rw,relatime - aufs none rw,si=9b4a76401263539c -174 15 0:3507 / /var/lib/docker/aufs/mnt/5f37830e5a02561ab8c67ea3113137ba69f67a60e41c05cb0e7a0edaa1925b24 rw,relatime - aufs none rw,si=9b4a76401263639c -184 15 0:3508 / /var/lib/docker/aufs/mnt/62ea10b957e6533538a4633a1e1d678502f50ddcdd354b2ca275c54dd7a7793a rw,relatime - aufs none rw,si=9b4a76401263039c -187 15 0:3509 / /var/lib/docker/aufs/mnt/d56ee9d44195fe390e042fda75ec15af5132adb6d5c69468fa8792f4e54a6953 rw,relatime - aufs none rw,si=9b4a76401263239c -188 15 0:3510 / /var/lib/docker/aufs/mnt/6a300930673174549c2b62f36c933f0332a20735978c007c805a301f897146c5 rw,relatime - aufs none rw,si=9b4a76455d4c539c -189 15 0:3511 / /var/lib/docker/aufs/mnt/64496c45c84d348c24d410015456d101601c30cab4d1998c395591caf7e57a70 rw,relatime - aufs none rw,si=9b4a76455d4c639c -190 15 0:3512 / /var/lib/docker/aufs/mnt/65a6a645883fe97a7422cd5e71ebe0bc17c8e6302a5361edf52e89747387e908 rw,relatime - aufs none rw,si=9b4a76455d4c039c -191 15 0:3513 / /var/lib/docker/aufs/mnt/672be40695f7b6e13b0a3ed9fc996c73727dede3481f58155950fcfad57ed616 rw,relatime - aufs none rw,si=9b4a76455d4c239c -192 15 0:3514 / /var/lib/docker/aufs/mnt/d42438acb2bfb2169e1c0d8e917fc824f7c85d336dadb0b0af36dfe0f001b3ba rw,relatime - aufs none rw,si=9b4a7642bfded39c -193 15 0:3515 / /var/lib/docker/aufs/mnt/b48a54abf26d01cb2ddd908b1ed6034d17397c1341bf0eb2b251a3e5b79be854 rw,relatime - aufs none rw,si=9b4a7642bfdee39c -194 15 0:3516 / /var/lib/docker/aufs/mnt/76f27134491f052bfb87f59092126e53ef875d6851990e59195a9da16a9412f8 rw,relatime - aufs none rw,si=9b4a7642bfde839c -195 15 0:3517 / /var/lib/docker/aufs/mnt/6bd626a5462b4f8a8e1cc7d10351326dca97a59b2758e5ea549a4f6350ce8a90 rw,relatime - aufs none rw,si=9b4a7642bfdea39c -196 15 0:3518 / /var/lib/docker/aufs/mnt/f1fe3549dbd6f5ca615e9139d9b53f0c83a3b825565df37628eacc13e70cbd6d rw,relatime - aufs none rw,si=9b4a7642bfdf539c -197 15 0:3519 / /var/lib/docker/aufs/mnt/6d0458c8426a9e93d58d0625737e6122e725c9408488ed9e3e649a9984e15c34 rw,relatime - aufs none rw,si=9b4a7642bfdf639c -198 15 0:3520 / /var/lib/docker/aufs/mnt/6e4c97db83aa82145c9cf2bafc20d500c0b5389643b689e3ae84188c270a48c5 rw,relatime - aufs none rw,si=9b4a7642bfdf039c -199 15 0:3521 / /var/lib/docker/aufs/mnt/eb94d6498f2c5969eaa9fa11ac2934f1ab90ef88e2d002258dca08e5ba74ea27 rw,relatime - aufs none rw,si=9b4a7642bfdf239c -200 15 0:3522 / /var/lib/docker/aufs/mnt/fe3f88f0c511608a2eec5f13a98703aa16e55dbf930309723d8a37101f539fe1 rw,relatime - aufs none rw,si=9b4a7642bfc3539c -201 15 0:3523 / /var/lib/docker/aufs/mnt/6f40c229fb9cad85fabf4b64a2640a5403ec03fe5ac1a57d0609fb8b606b9c83 rw,relatime - aufs none rw,si=9b4a7642bfc3639c -202 15 0:3524 / /var/lib/docker/aufs/mnt/7513e9131f7a8acf58ff15248237feb767c78732ca46e159f4d791e6ef031dbc rw,relatime - aufs none rw,si=9b4a7642bfc3039c -203 15 0:3525 / /var/lib/docker/aufs/mnt/79f48b00aa713cdf809c6bb7c7cb911b66e9a8076c81d6c9d2504139984ea2da rw,relatime - aufs none rw,si=9b4a7642bfc3239c -204 15 0:3526 / /var/lib/docker/aufs/mnt/c3680418350d11358f0a96c676bc5aa74fa00a7c89e629ef5909d3557b060300 rw,relatime - aufs none rw,si=9b4a7642f47cd39c -205 15 0:3527 / /var/lib/docker/aufs/mnt/7a1744dd350d7fcc0cccb6f1757ca4cbe5453f203a5888b0f1014d96ad5a5ef9 rw,relatime - aufs none rw,si=9b4a7642f47ce39c -206 15 0:3528 / /var/lib/docker/aufs/mnt/7fa99662db046be9f03c33c35251afda9ccdc0085636bbba1d90592cec3ff68d rw,relatime - aufs none rw,si=9b4a7642f47c839c -207 15 0:3529 / /var/lib/docker/aufs/mnt/f815021ef20da9c9b056bd1d52d8aaf6e2c0c19f11122fc793eb2b04eb995e35 rw,relatime - aufs none rw,si=9b4a7642f47ca39c -208 15 0:3530 / /var/lib/docker/aufs/mnt/801086ae3110192d601dfcebdba2db92e86ce6b6a9dba6678ea04488e4513669 rw,relatime - aufs none rw,si=9b4a7642dc6dd39c -209 15 0:3531 / /var/lib/docker/aufs/mnt/822ba7db69f21daddda87c01cfbfbf73013fc03a879daf96d16cdde6f9b1fbd6 rw,relatime - aufs none rw,si=9b4a7642dc6de39c -210 15 0:3532 / /var/lib/docker/aufs/mnt/834227c1a950fef8cae3827489129d0dd220541e60c6b731caaa765bf2e6a199 rw,relatime - aufs none rw,si=9b4a7642dc6d839c -211 15 0:3533 / /var/lib/docker/aufs/mnt/83dccbc385299bd1c7cf19326e791b33a544eea7b4cdfb6db70ea94eed4389fb rw,relatime - aufs none rw,si=9b4a7642dc6da39c -212 15 0:3534 / /var/lib/docker/aufs/mnt/f1b8e6f0e7c8928b5dcdab944db89306ebcae3e0b32f9ff40d2daa8329f21600 rw,relatime - aufs none rw,si=9b4a7645a126039c -213 15 0:3535 / /var/lib/docker/aufs/mnt/970efb262c7a020c2404cbcc5b3259efba0d110a786079faeef05bc2952abf3a rw,relatime - aufs none rw,si=9b4a7644c8ed139c -214 15 0:3536 / /var/lib/docker/aufs/mnt/84b6d73af7450f3117a77e15a5ca1255871fea6182cd8e8a7be6bc744be18c2c rw,relatime - aufs none rw,si=9b4a76406559139c -215 15 0:3537 / /var/lib/docker/aufs/mnt/88be2716e026bc681b5e63fe7942068773efbd0b6e901ca7ba441412006a96b6 rw,relatime - aufs none rw,si=9b4a76406559339c -216 15 0:3538 / /var/lib/docker/aufs/mnt/c81939aa166ce50cd8bca5cfbbcc420a78e0318dd5cd7c755209b9166a00a752 rw,relatime - aufs none rw,si=9b4a76406559239c -217 15 0:3539 / /var/lib/docker/aufs/mnt/e0f241645d64b7dc5ff6a8414087cca226be08fb54ce987d1d1f6350c57083aa rw,relatime - aufs none rw,si=9b4a7647cfc0f39c -218 15 0:3540 / /var/lib/docker/aufs/mnt/e10e2bf75234ed51d8a6a4bb39e465404fecbe318e54400d3879cdb2b0679c78 rw,relatime - aufs none rw,si=9b4a7647cfc0939c -219 15 0:3541 / /var/lib/docker/aufs/mnt/8f71d74c8cfc3228b82564aa9f09b2e576cff0083ddfb6aa5cb350346063f080 rw,relatime - aufs none rw,si=9b4a7647cfc0a39c -220 15 0:3542 / /var/lib/docker/aufs/mnt/9159f1eba2aef7f5205cc18d015cda7f5933cd29bba3b1b8aed5ccb5824c69ee rw,relatime - aufs none rw,si=9b4a76468cedd39c -221 15 0:3543 / /var/lib/docker/aufs/mnt/932cad71e652e048e500d9fbb5b8ea4fc9a269d42a3134ce527ceef42a2be56b rw,relatime - aufs none rw,si=9b4a76468cede39c -222 15 0:3544 / /var/lib/docker/aufs/mnt/bf1e1b5f529e8943cc0144ee86dbaaa37885c1ddffcef29537e0078ee7dd316a rw,relatime - aufs none rw,si=9b4a76468ced839c -223 15 0:3545 / /var/lib/docker/aufs/mnt/949d93ecf3322e09f858ce81d5f4b434068ec44ff84c375de03104f7b45ee955 rw,relatime - aufs none rw,si=9b4a76468ceda39c -224 15 0:3546 / /var/lib/docker/aufs/mnt/d65c6087f92dc2a3841b5251d2fe9ca07d4c6e5b021597692479740816e4e2a1 rw,relatime - aufs none rw,si=9b4a7645a126239c -225 15 0:3547 / /var/lib/docker/aufs/mnt/98a0153119d0651c193d053d254f6e16a68345a141baa80c87ae487e9d33f290 rw,relatime - aufs none rw,si=9b4a7640787cf39c -226 15 0:3548 / /var/lib/docker/aufs/mnt/99daf7fe5847c017392f6e59aa9706b3dfdd9e6d1ba11dae0f7fffde0a60b5e5 rw,relatime - aufs none rw,si=9b4a7640787c839c -227 15 0:3549 / /var/lib/docker/aufs/mnt/9ad1f2fe8a5599d4e10c5a6effa7f03d932d4e92ee13149031a372087a359079 rw,relatime - aufs none rw,si=9b4a7640787ca39c -228 15 0:3550 / /var/lib/docker/aufs/mnt/c26d64494da782ddac26f8370d86ac93e7c1666d88a7b99110fc86b35ea6a85d rw,relatime - aufs none rw,si=9b4a7642fc6b539c -229 15 0:3551 / /var/lib/docker/aufs/mnt/a49e4a8275133c230ec640997f35f172312eb0ea5bd2bbe10abf34aae98f30eb rw,relatime - aufs none rw,si=9b4a7642fc6b639c -230 15 0:3552 / /var/lib/docker/aufs/mnt/b5e2740c867ed843025f49d84e8d769de9e8e6039b3c8cb0735b5bf358994bc7 rw,relatime - aufs none rw,si=9b4a7642fc6b039c -231 15 0:3553 / /var/lib/docker/aufs/mnt/a826fdcf3a7039b30570054579b65763db605a314275d7aef31b872c13311b4b rw,relatime - aufs none rw,si=9b4a7642fc6b239c -232 15 0:3554 / /var/lib/docker/aufs/mnt/addf3025babf5e43b5a3f4a0da7ad863dda3c01fb8365c58fd8d28bb61dc11bc rw,relatime - aufs none rw,si=9b4a76407871d39c -233 15 0:3555 / /var/lib/docker/aufs/mnt/c5b6c6813ab3e5ebdc6d22cb2a3d3106a62095f2c298be52b07a3b0fa20ff690 rw,relatime - aufs none rw,si=9b4a76407871e39c -234 15 0:3556 / /var/lib/docker/aufs/mnt/af0609eaaf64e2392060cb46f5a9f3d681a219bb4c651d4f015bf573fbe6c4cf rw,relatime - aufs none rw,si=9b4a76407871839c -235 15 0:3557 / /var/lib/docker/aufs/mnt/e7f20e3c37ecad39cd90a97cd3549466d0d106ce4f0a930b8495442634fa4a1f rw,relatime - aufs none rw,si=9b4a76407871a39c -237 15 0:3559 / /var/lib/docker/aufs/mnt/b57a53d440ffd0c1295804fa68cdde35d2fed5409484627e71b9c37e4249fd5c rw,relatime - aufs none rw,si=9b4a76444445a39c -238 15 0:3560 / /var/lib/docker/aufs/mnt/b5e7d7b8f35e47efbba3d80c5d722f5e7bd43e54c824e54b4a4b351714d36d42 rw,relatime - aufs none rw,si=9b4a7647932d439c -239 15 0:3561 / /var/lib/docker/aufs/mnt/f1b136def157e9465640658f277f3347de593c6ae76412a2e79f7002f091cae2 rw,relatime - aufs none rw,si=9b4a76445abcd39c -240 15 0:3562 / /var/lib/docker/aufs/mnt/b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc rw,relatime - aufs none rw,si=9b4a7644403b339c -241 15 0:3563 / /var/lib/docker/aufs/mnt/b89b140cdbc95063761864e0a23346207fa27ee4c5c63a1ae85c9069a9d9cf1d rw,relatime - aufs none rw,si=9b4a7644aa19739c -242 15 0:3564 / /var/lib/docker/aufs/mnt/bc6a69ed51c07f5228f6b4f161c892e6a949c0e7e86a9c3432049d4c0e5cd298 rw,relatime - aufs none rw,si=9b4a7644aa19139c -243 15 0:3565 / /var/lib/docker/aufs/mnt/be4e2ba3f136933e239f7cf3d136f484fb9004f1fbdfee24a62a2c7b0ab30670 rw,relatime - aufs none rw,si=9b4a7644aa19339c -244 15 0:3566 / /var/lib/docker/aufs/mnt/e04ca1a4a5171e30d20f0c92f90a50b8b6f8600af5459c4b4fb25e42e864dfe1 rw,relatime - aufs none rw,si=9b4a7647932d139c -245 15 0:3567 / /var/lib/docker/aufs/mnt/be61576b31db893129aaffcd3dcb5ce35e49c4b71b30c392a78609a45c7323d8 rw,relatime - aufs none rw,si=9b4a7642d85f739c -246 15 0:3568 / /var/lib/docker/aufs/mnt/dda42c191e56becf672327658ab84fcb563322db3764b91c2fefe4aaef04c624 rw,relatime - aufs none rw,si=9b4a7642d85f139c -247 15 0:3569 / /var/lib/docker/aufs/mnt/c0a7995053330f3d88969247a2e72b07e2dd692133f5668a4a35ea3905561072 rw,relatime - aufs none rw,si=9b4a7642d85f339c -249 15 0:3571 / /var/lib/docker/aufs/mnt/c3594b2e5f08c59ff5ed338a1ba1eceeeb1f7fc5d180068338110c00b1eb8502 rw,relatime - aufs none rw,si=9b4a7642738c739c -250 15 0:3572 / /var/lib/docker/aufs/mnt/c58dce03a0ab0a7588393880379dc3bce9f96ec08ed3f99cf1555260ff0031e8 rw,relatime - aufs none rw,si=9b4a7642738c139c -251 15 0:3573 / /var/lib/docker/aufs/mnt/c73e9f1d109c9d14cb36e1c7489df85649be3911116d76c2fd3648ec8fd94e23 rw,relatime - aufs none rw,si=9b4a7642738c339c -252 15 0:3574 / /var/lib/docker/aufs/mnt/c9eef28c344877cd68aa09e543c0710ab2b305a0ff96dbb859bfa7808c3e8d01 rw,relatime - aufs none rw,si=9b4a7642d85f439c -253 15 0:3575 / /var/lib/docker/aufs/mnt/feb67148f548d70cb7484f2aaad2a86051cd6867a561741a2f13b552457d666e rw,relatime - aufs none rw,si=9b4a76468c55739c -254 15 0:3576 / /var/lib/docker/aufs/mnt/cdf1f96c36d35a96041a896bf398ec0f7dc3b0fb0643612a0f4b6ff96e04e1bb rw,relatime - aufs none rw,si=9b4a76468c55139c -255 15 0:3577 / /var/lib/docker/aufs/mnt/ec6e505872353268451ac4bc034c1df00f3bae4a3ea2261c6e48f7bd5417c1b3 rw,relatime - aufs none rw,si=9b4a76468c55339c -256 15 0:3578 / /var/lib/docker/aufs/mnt/d6dc8aca64efd90e0bc10274001882d0efb310d42ccbf5712b99b169053b8b1a rw,relatime - aufs none rw,si=9b4a7642738c439c -257 15 0:3579 / /var/lib/docker/aufs/mnt/d712594e2ff6eaeb895bfd150d694bd1305fb927e7a186b2dab7df2ea95f8f81 rw,relatime - aufs none rw,si=9b4a76401268f39c -259 15 0:3581 / /var/lib/docker/aufs/mnt/dbfa1174cd78cde2d7410eae442af0b416c4a0e6f87ed4ff1e9f169a0029abc0 rw,relatime - aufs none rw,si=9b4a76401268b39c -260 15 0:3582 / /var/lib/docker/aufs/mnt/e883f5a82316d7856fbe93ee8c0af5a920b7079619dd95c4ffd88bbd309d28dd rw,relatime - aufs none rw,si=9b4a76468c55439c -261 15 0:3583 / /var/lib/docker/aufs/mnt/fdec3eff581c4fc2b09f87befa2fa021f3f2d373bea636a87f1fb5b367d6347a rw,relatime - aufs none rw,si=9b4a7644aa1af39c -262 15 0:3584 / /var/lib/docker/aufs/mnt/ef764e26712184653067ecf7afea18a80854c41331ca0f0ef03e1bacf90a6ffc rw,relatime - aufs none rw,si=9b4a7644aa1a939c -263 15 0:3585 / /var/lib/docker/aufs/mnt/f3176b40c41fce8ce6942936359a2001a6f1b5c1bb40ee224186db0789ec2f76 rw,relatime - aufs none rw,si=9b4a7644aa1ab39c -264 15 0:3586 / /var/lib/docker/aufs/mnt/f5daf06785d3565c6dd18ea7d953d9a8b9606107781e63270fe0514508736e6a rw,relatime - aufs none rw,si=9b4a76401268c39c -58 15 0:3587 / /var/lib/docker/aufs/mnt/cde8c40f6524b7361af4f5ad05bb857dc9ee247c20852ba666195c0739e3a2b8-init rw,relatime - aufs none rw,si=9b4a76444445839c -67 15 0:3588 / /var/lib/docker/aufs/mnt/cde8c40f6524b7361af4f5ad05bb857dc9ee247c20852ba666195c0739e3a2b8 rw,relatime - aufs none rw,si=9b4a7644badd339c -265 15 0:3610 / /var/lib/docker/aufs/mnt/e812472cd2c8c4748d1ef71fac4e77e50d661b9349abe66ce3e23511ed44f414 rw,relatime - aufs none rw,si=9b4a76427937d39c -270 15 0:3615 / /var/lib/docker/aufs/mnt/997636e7c5c9d0d1376a217e295c14c205350b62bc12052804fb5f90abe6f183 rw,relatime - aufs none rw,si=9b4a76406540739c -273 15 0:3618 / /var/lib/docker/aufs/mnt/d5794d080417b6e52e69227c3873e0e4c1ff0d5a845ebe3860ec2f89a47a2a1e rw,relatime - aufs none rw,si=9b4a76454814039c -278 15 0:3623 / /var/lib/docker/aufs/mnt/586bdd48baced671bb19bc4d294ec325f26c55545ae267db426424f157d59c48 rw,relatime - aufs none rw,si=9b4a7644b439f39c -281 15 0:3626 / /var/lib/docker/aufs/mnt/69739d022f89f8586908bbd5edbbdd95ea5256356f177f9ffcc6ef9c0ea752d2 rw,relatime - aufs none rw,si=9b4a7644a0f1b39c -286 15 0:3631 / /var/lib/docker/aufs/mnt/ff28c27d5f894363993622de26d5dd352dba072f219e4691d6498c19bbbc15a9 rw,relatime - aufs none rw,si=9b4a7642265b339c -289 15 0:3634 / /var/lib/docker/aufs/mnt/aa128fe0e64fdede333aa48fd9de39530c91a9244a0f0649a3c411c61e372daa rw,relatime - aufs none rw,si=9b4a764012ada39c -99 15 8:33 / /media/REMOVE\040ME rw,nosuid,nodev,relatime - fuseblk /dev/sdc1 rw,user_id=0,group_id=0,allow_other,blksize=4096` -) - -func TestParseFedoraMountinfo(t *testing.T) { - r := bytes.NewBuffer([]byte(fedoraMountinfo)) - _, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } -} - -func TestParseUbuntuMountinfo(t *testing.T) { - r := bytes.NewBuffer([]byte(ubuntuMountInfo)) - _, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } -} - -func TestParseGentooMountinfo(t *testing.T) { - r := bytes.NewBuffer([]byte(gentooMountinfo)) - _, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } -} - -func TestParseFedoraMountinfoFields(t *testing.T) { - r := bytes.NewBuffer([]byte(fedoraMountinfo)) - infos, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } - expectedLength := 58 - if len(infos) != expectedLength { - t.Fatalf("Expected %d entries, got %d", expectedLength, len(infos)) - } - mi := Info{ - ID: 15, - Parent: 35, - Major: 0, - Minor: 3, - Root: "/", - Mountpoint: "/proc", - Opts: "rw,nosuid,nodev,noexec,relatime", - Optional: "shared:5", - Fstype: "proc", - Source: "proc", - VfsOpts: "rw", - } - - if *infos[0] != mi { - t.Fatalf("expected %#v, got %#v", mi, infos[0]) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go deleted file mode 100644 index 4a8d22f02..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go +++ /dev/null @@ -1,331 +0,0 @@ -// +build linux - -package mount - -import ( - "os" - "path" - "syscall" - "testing" -) - -// nothing is propagated in or out -func TestSubtreePrivate(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - outside1Dir = path.Join(tmp, "outside1") - outside2Dir = path.Join(tmp, "outside2") - - outside1Path = path.Join(outside1Dir, "file.txt") - outside2Path = path.Join(outside2Dir, "file.txt") - outside1CheckPath = path.Join(targetDir, "a", "file.txt") - outside2CheckPath = path.Join(sourceDir, "b", "file.txt") - ) - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(targetDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside1Dir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside2Dir, 0777); err != nil { - t.Fatal(err) - } - - if err := createFile(outside1Path); err != nil { - t.Fatal(err) - } - if err := createFile(outside2Path); err != nil { - t.Fatal(err) - } - - // mount the shared directory to a target - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // next, make the target private - if err := MakePrivate(targetDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // mount in an outside path to a mounted path inside the _source_ - if err := Mount(outside1Dir, path.Join(sourceDir, "a"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(sourceDir, "a")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_not_ show in the _target_ - if _, err := os.Stat(outside1CheckPath); err != nil && !os.IsNotExist(err) { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not be visible, but is", outside1CheckPath) - } - - // next mount outside2Dir into the _target_ - if err := Mount(outside2Dir, path.Join(targetDir, "b"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(targetDir, "b")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_not_ show in the _source_ - if _, err := os.Stat(outside2CheckPath); err != nil && !os.IsNotExist(err) { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not be visible, but is", outside2CheckPath) - } -} - -// Testing that when a target is a shared mount, -// then child mounts propagate to the source -func TestSubtreeShared(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - outsideDir = path.Join(tmp, "outside") - - outsidePath = path.Join(outsideDir, "file.txt") - sourceCheckPath = path.Join(sourceDir, "a", "file.txt") - ) - - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(targetDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outsideDir, 0777); err != nil { - t.Fatal(err) - } - - if err := createFile(outsidePath); err != nil { - t.Fatal(err) - } - - // mount the source as shared - if err := MakeShared(sourceDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(sourceDir); err != nil { - t.Fatal(err) - } - }() - - // mount the shared directory to a target - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // mount in an outside path to a mounted path inside the target - if err := Mount(outsideDir, path.Join(targetDir, "a"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(targetDir, "a")); err != nil { - t.Fatal(err) - } - }() - - // NOW, check that the file from the outside directory is avaible in the source directory - if _, err := os.Stat(sourceCheckPath); err != nil { - t.Fatal(err) - } -} - -// testing that mounts to a shared source show up in the slave target, -// and that mounts into a slave target do _not_ show up in the shared source -func TestSubtreeSharedSlave(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - outside1Dir = path.Join(tmp, "outside1") - outside2Dir = path.Join(tmp, "outside2") - - outside1Path = path.Join(outside1Dir, "file.txt") - outside2Path = path.Join(outside2Dir, "file.txt") - outside1CheckPath = path.Join(targetDir, "a", "file.txt") - outside2CheckPath = path.Join(sourceDir, "b", "file.txt") - ) - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(targetDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside1Dir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside2Dir, 0777); err != nil { - t.Fatal(err) - } - - if err := createFile(outside1Path); err != nil { - t.Fatal(err) - } - if err := createFile(outside2Path); err != nil { - t.Fatal(err) - } - - // mount the source as shared - if err := MakeShared(sourceDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(sourceDir); err != nil { - t.Fatal(err) - } - }() - - // mount the shared directory to a target - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // next, make the target slave - if err := MakeSlave(targetDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // mount in an outside path to a mounted path inside the _source_ - if err := Mount(outside1Dir, path.Join(sourceDir, "a"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(sourceDir, "a")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_ show in the _target_ - if _, err := os.Stat(outside1CheckPath); err != nil { - t.Fatal(err) - } - - // next mount outside2Dir into the _target_ - if err := Mount(outside2Dir, path.Join(targetDir, "b"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(targetDir, "b")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_not_ show in the _source_ - if _, err := os.Stat(outside2CheckPath); err != nil && !os.IsNotExist(err) { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not be visible, but is", outside2CheckPath) - } -} - -func TestSubtreeUnbindable(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - ) - if err := os.MkdirAll(sourceDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(targetDir, 0777); err != nil { - t.Fatal(err) - } - - // next, make the source unbindable - if err := MakeUnbindable(sourceDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(sourceDir); err != nil { - t.Fatal(err) - } - }() - - // then attempt to mount it to target. It should fail - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil && err != syscall.EINVAL { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not have been bindable", sourceDir) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() -} - -func createFile(path string) error { - f, err := os.Create(path) - if err != nil { - return err - } - f.WriteString("hello world!") - return f.Close() -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse.go deleted file mode 100644 index df5486d51..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse.go +++ /dev/null @@ -1,116 +0,0 @@ -package filters - -import ( - "encoding/json" - "errors" - "regexp" - "strings" -) - -type Args map[string][]string - -// Parse the argument to the filter flag. Like -// -// `docker ps -f 'created=today' -f 'image.name=ubuntu*'` -// -// If prev map is provided, then it is appended to, and returned. By default a new -// map is created. -func ParseFlag(arg string, prev Args) (Args, error) { - var filters Args = prev - if prev == nil { - filters = Args{} - } - if len(arg) == 0 { - return filters, nil - } - - if !strings.Contains(arg, "=") { - return filters, ErrorBadFormat - } - - f := strings.SplitN(arg, "=", 2) - name := strings.ToLower(strings.TrimSpace(f[0])) - value := strings.TrimSpace(f[1]) - filters[name] = append(filters[name], value) - - return filters, nil -} - -var ErrorBadFormat = errors.New("bad format of filter (expected name=value)") - -// packs the Args into an string for easy transport from client to server -func ToParam(a Args) (string, error) { - // this way we don't URL encode {}, just empty space - if len(a) == 0 { - return "", nil - } - - buf, err := json.Marshal(a) - if err != nil { - return "", err - } - return string(buf), nil -} - -// unpacks the filter Args -func FromParam(p string) (Args, error) { - args := Args{} - if len(p) == 0 { - return args, nil - } - if err := json.NewDecoder(strings.NewReader(p)).Decode(&args); err != nil { - return nil, err - } - return args, nil -} - -func (filters Args) MatchKVList(field string, sources map[string]string) bool { - fieldValues := filters[field] - - //do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - - if sources == nil || len(sources) == 0 { - return false - } - -outer: - for _, name2match := range fieldValues { - testKV := strings.SplitN(name2match, "=", 2) - - for k, v := range sources { - if len(testKV) == 1 { - if k == testKV[0] { - continue outer - } - } else if k == testKV[0] && v == testKV[1] { - continue outer - } - } - - return false - } - - return true -} - -func (filters Args) Match(field, source string) bool { - fieldValues := filters[field] - - //do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - for _, name2match := range fieldValues { - match, err := regexp.MatchString(name2match, source) - if err != nil { - continue - } - if match { - return true - } - } - return false -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse_test.go deleted file mode 100644 index a141c33ce..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse_test.go +++ /dev/null @@ -1,218 +0,0 @@ -package filters - -import ( - "sort" - "testing" -) - -func TestParseArgs(t *testing.T) { - // equivalent of `docker ps -f 'created=today' -f 'image.name=ubuntu*' -f 'image.name=*untu'` - flagArgs := []string{ - "created=today", - "image.name=ubuntu*", - "image.name=*untu", - } - var ( - args = Args{} - err error - ) - for i := range flagArgs { - args, err = ParseFlag(flagArgs[i], args) - if err != nil { - t.Errorf("failed to parse %s: %s", flagArgs[i], err) - } - } - if len(args["created"]) != 1 { - t.Errorf("failed to set this arg") - } - if len(args["image.name"]) != 2 { - t.Errorf("the args should have collapsed") - } -} - -func TestParseArgsEdgeCase(t *testing.T) { - var filters Args - args, err := ParseFlag("", filters) - if err != nil { - t.Fatal(err) - } - if args == nil || len(args) != 0 { - t.Fatalf("Expected an empty Args (map), got %v", args) - } - if args, err = ParseFlag("anything", args); err == nil || err != ErrorBadFormat { - t.Fatalf("Expected ErrorBadFormat, got %v", err) - } -} - -func TestToParam(t *testing.T) { - a := Args{ - "created": []string{"today"}, - "image.name": []string{"ubuntu*", "*untu"}, - } - - _, err := ToParam(a) - if err != nil { - t.Errorf("failed to marshal the filters: %s", err) - } -} - -func TestFromParam(t *testing.T) { - invalids := []string{ - "anything", - "['a','list']", - "{'key': 'value'}", - `{"key": "value"}`, - } - valids := map[string]Args{ - `{"key": ["value"]}`: { - "key": {"value"}, - }, - `{"key": ["value1", "value2"]}`: { - "key": {"value1", "value2"}, - }, - `{"key1": ["value1"], "key2": ["value2"]}`: { - "key1": {"value1"}, - "key2": {"value2"}, - }, - } - for _, invalid := range invalids { - if _, err := FromParam(invalid); err == nil { - t.Fatalf("Expected an error with %v, got nothing", invalid) - } - } - for json, expectedArgs := range valids { - args, err := FromParam(json) - if err != nil { - t.Fatal(err) - } - if len(args) != len(expectedArgs) { - t.Fatalf("Expected %v, go %v", expectedArgs, args) - } - for key, expectedValues := range expectedArgs { - values := args[key] - sort.Strings(values) - sort.Strings(expectedValues) - if len(values) != len(expectedValues) { - t.Fatalf("Expected %v, go %v", expectedArgs, args) - } - for index, expectedValue := range expectedValues { - if values[index] != expectedValue { - t.Fatalf("Expected %v, go %v", expectedArgs, args) - } - } - } - } -} - -func TestEmpty(t *testing.T) { - a := Args{} - v, err := ToParam(a) - if err != nil { - t.Errorf("failed to marshal the filters: %s", err) - } - v1, err := FromParam(v) - if err != nil { - t.Errorf("%s", err) - } - if len(a) != len(v1) { - t.Errorf("these should both be empty sets") - } -} - -func TestArgsMatchKVList(t *testing.T) { - // empty sources - args := Args{ - "created": []string{"today"}, - } - if args.MatchKVList("created", map[string]string{}) { - t.Fatalf("Expected false for (%v,created), got true", args) - } - // Not empty sources - sources := map[string]string{ - "key1": "value1", - "key2": "value2", - "key3": "value3", - } - matches := map[*Args]string{ - &Args{}: "field", - &Args{ - "created": []string{"today"}, - "labels": []string{"key1"}, - }: "labels", - &Args{ - "created": []string{"today"}, - "labels": []string{"key1=value1"}, - }: "labels", - } - differs := map[*Args]string{ - &Args{ - "created": []string{"today"}, - }: "created", - &Args{ - "created": []string{"today"}, - "labels": []string{"key4"}, - }: "labels", - &Args{ - "created": []string{"today"}, - "labels": []string{"key1=value3"}, - }: "labels", - } - for args, field := range matches { - if args.MatchKVList(field, sources) != true { - t.Fatalf("Expected true for %v on %v, got false", sources, args) - } - } - for args, field := range differs { - if args.MatchKVList(field, sources) != false { - t.Fatalf("Expected false for %v on %v, got true", sources, args) - } - } -} - -func TestArgsMatch(t *testing.T) { - source := "today" - matches := map[*Args]string{ - &Args{}: "field", - &Args{ - "created": []string{"today"}, - "labels": []string{"key1"}, - }: "today", - &Args{ - "created": []string{"to*"}, - }: "created", - &Args{ - "created": []string{"to(.*)"}, - }: "created", - &Args{ - "created": []string{"tod"}, - }: "created", - &Args{ - "created": []string{"anything", "to*"}, - }: "created", - } - differs := map[*Args]string{ - &Args{ - "created": []string{"tomorrow"}, - }: "created", - &Args{ - "created": []string{"to(day"}, - }: "created", - &Args{ - "created": []string{"tom(.*)"}, - }: "created", - &Args{ - "created": []string{"today1"}, - "labels": []string{"today"}, - }: "created", - } - for args, field := range matches { - if args.Match(field, source) != true { - t.Fatalf("Expected true for %v on %v, got false", source, args) - } - } - for args, field := range differs { - if args.Match(field, source) != false { - t.Fatalf("Expected false for %v on %v, got true", source, args) - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel.go deleted file mode 100644 index 5f7930684..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel.go +++ /dev/null @@ -1,95 +0,0 @@ -// +build !windows - -package kernel - -import ( - "bytes" - "errors" - "fmt" -) - -type KernelVersionInfo struct { - Kernel int - Major int - Minor int - Flavor string -} - -func (k *KernelVersionInfo) String() string { - return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor) -} - -// Compare two KernelVersionInfo struct. -// Returns -1 if a < b, 0 if a == b, 1 it a > b -func CompareKernelVersion(a, b *KernelVersionInfo) int { - if a.Kernel < b.Kernel { - return -1 - } else if a.Kernel > b.Kernel { - return 1 - } - - if a.Major < b.Major { - return -1 - } else if a.Major > b.Major { - return 1 - } - - if a.Minor < b.Minor { - return -1 - } else if a.Minor > b.Minor { - return 1 - } - - return 0 -} - -func GetKernelVersion() (*KernelVersionInfo, error) { - var ( - err error - ) - - uts, err := uname() - if err != nil { - return nil, err - } - - release := make([]byte, len(uts.Release)) - - i := 0 - for _, c := range uts.Release { - release[i] = byte(c) - i++ - } - - // Remove the \x00 from the release for Atoi to parse correctly - release = release[:bytes.IndexByte(release, 0)] - - return ParseRelease(string(release)) -} - -func ParseRelease(release string) (*KernelVersionInfo, error) { - var ( - kernel, major, minor, parsed int - flavor, partial string - ) - - // Ignore error from Sscanf to allow an empty flavor. Instead, just - // make sure we got all the version numbers. - parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial) - if parsed < 2 { - return nil, errors.New("Can't parse kernel version " + release) - } - - // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64 - parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor) - if parsed < 1 { - flavor = partial - } - - return &KernelVersionInfo{ - Kernel: kernel, - Major: major, - Minor: minor, - Flavor: flavor, - }, nil -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go deleted file mode 100644 index 7f40939cc..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package kernel - -import ( - "fmt" - "testing" -) - -func assertParseRelease(t *testing.T, release string, b *KernelVersionInfo, result int) { - var ( - a *KernelVersionInfo - ) - a, _ = ParseRelease(release) - - if r := CompareKernelVersion(a, b); r != result { - t.Fatalf("Unexpected kernel version comparison result for (%v,%v). Found %d, expected %d", release, b, r, result) - } - if a.Flavor != b.Flavor { - t.Fatalf("Unexpected parsed kernel flavor. Found %s, expected %s", a.Flavor, b.Flavor) - } -} - -func TestParseRelease(t *testing.T) { - assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0) - assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0) - assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0) - assertParseRelease(t, "3.8.0-19-generic", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "-19-generic"}, 0) - assertParseRelease(t, "3.12.8tag", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 8, Flavor: "tag"}, 0) - assertParseRelease(t, "3.12-1-amd64", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 0, Flavor: "-1-amd64"}, 0) - assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 4, Major: 8, Minor: 0}, -1) - // Errors - invalids := []string{ - "3", - "a", - "a.a", - "a.a.a-a", - } - for _, invalid := range invalids { - expectedMessage := fmt.Sprintf("Can't parse kernel version %v", invalid) - if _, err := ParseRelease(invalid); err == nil || err.Error() != expectedMessage { - - } - } -} - -func assertKernelVersion(t *testing.T, a, b *KernelVersionInfo, result int) { - if r := CompareKernelVersion(a, b); r != result { - t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result) - } -} - -func TestCompareKernelVersion(t *testing.T) { - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - 0) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - -1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0}, - 1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - 0) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 5}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - 1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 0, Minor: 20}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - -1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 7, Minor: 20}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - -1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20}, - &KernelVersionInfo{Kernel: 3, Major: 7, Minor: 0}, - 1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - 1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20}, - -1) -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_windows.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_windows.go deleted file mode 100644 index 399d63e5f..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_windows.go +++ /dev/null @@ -1,65 +0,0 @@ -package kernel - -import ( - "fmt" - "syscall" - "unsafe" -) - -type KernelVersionInfo struct { - kvi string - major int - minor int - build int -} - -func (k *KernelVersionInfo) String() string { - return fmt.Sprintf("%d.%d %d (%s)", k.major, k.minor, k.build, k.kvi) -} - -func GetKernelVersion() (*KernelVersionInfo, error) { - - var ( - h syscall.Handle - dwVersion uint32 - err error - ) - - KVI := &KernelVersionInfo{"Unknown", 0, 0, 0} - - if err = syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, - syscall.StringToUTF16Ptr(`SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\`), - 0, - syscall.KEY_READ, - &h); err != nil { - return KVI, err - } - defer syscall.RegCloseKey(h) - - var buf [1 << 10]uint16 - var typ uint32 - n := uint32(len(buf) * 2) // api expects array of bytes, not uint16 - - if err = syscall.RegQueryValueEx(h, - syscall.StringToUTF16Ptr("BuildLabEx"), - nil, - &typ, - (*byte)(unsafe.Pointer(&buf[0])), - &n); err != nil { - return KVI, err - } - - KVI.kvi = syscall.UTF16ToString(buf[:]) - - // Important - docker.exe MUST be manifested for this API to return - // the correct information. - if dwVersion, err = syscall.GetVersion(); err != nil { - return KVI, err - } - - KVI.major = int(dwVersion & 0xFF) - KVI.minor = int((dwVersion & 0XFF00) >> 8) - KVI.build = int((dwVersion & 0xFFFF0000) >> 16) - - return KVI, nil -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/uname_linux.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/uname_linux.go deleted file mode 100644 index 8ca814c1f..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/uname_linux.go +++ /dev/null @@ -1,16 +0,0 @@ -package kernel - -import ( - "syscall" -) - -type Utsname syscall.Utsname - -func uname() (*syscall.Utsname, error) { - uts := &syscall.Utsname{} - - if err := syscall.Uname(uts); err != nil { - return nil, err - } - return uts, nil -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/uname_unsupported.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/uname_unsupported.go deleted file mode 100644 index 00c542258..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/uname_unsupported.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !linux - -package kernel - -import ( - "errors" -) - -type Utsname struct { - Release [65]byte -} - -func uname() (*Utsname, error) { - return nil, errors.New("Kernel version detection is available only on linux") -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_linux.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_linux.go deleted file mode 100644 index af185f9f6..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_linux.go +++ /dev/null @@ -1,40 +0,0 @@ -package operatingsystem - -import ( - "bytes" - "errors" - "io/ioutil" -) - -var ( - // file to use to detect if the daemon is running in a container - proc1Cgroup = "/proc/1/cgroup" - - // file to check to determine Operating System - etcOsRelease = "/etc/os-release" -) - -func GetOperatingSystem() (string, error) { - b, err := ioutil.ReadFile(etcOsRelease) - if err != nil { - return "", err - } - if i := bytes.Index(b, []byte("PRETTY_NAME")); i >= 0 { - b = b[i+13:] - return string(b[:bytes.IndexByte(b, '"')]), nil - } - return "", errors.New("PRETTY_NAME not found") -} - -func IsContainerized() (bool, error) { - b, err := ioutil.ReadFile(proc1Cgroup) - if err != nil { - return false, err - } - for _, line := range bytes.Split(b, []byte{'\n'}) { - if len(line) > 0 && !bytes.HasSuffix(line, []byte{'/'}) { - return true, nil - } - } - return false, nil -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go deleted file mode 100644 index b7d54cbb1..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package operatingsystem - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" -) - -func TestGetOperatingSystem(t *testing.T) { - var ( - backup = etcOsRelease - ubuntuTrusty = []byte(`NAME="Ubuntu" -VERSION="14.04, Trusty Tahr" -ID=ubuntu -ID_LIKE=debian -PRETTY_NAME="Ubuntu 14.04 LTS" -VERSION_ID="14.04" -HOME_URL="http://www.ubuntu.com/" -SUPPORT_URL="http://help.ubuntu.com/" -BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"`) - gentoo = []byte(`NAME=Gentoo -ID=gentoo -PRETTY_NAME="Gentoo/Linux" -ANSI_COLOR="1;32" -HOME_URL="http://www.gentoo.org/" -SUPPORT_URL="http://www.gentoo.org/main/en/support.xml" -BUG_REPORT_URL="https://bugs.gentoo.org/" -`) - noPrettyName = []byte(`NAME="Ubuntu" -VERSION="14.04, Trusty Tahr" -ID=ubuntu -ID_LIKE=debian -VERSION_ID="14.04" -HOME_URL="http://www.ubuntu.com/" -SUPPORT_URL="http://help.ubuntu.com/" -BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"`) - ) - - dir := os.TempDir() - etcOsRelease = filepath.Join(dir, "etcOsRelease") - - defer func() { - os.Remove(etcOsRelease) - etcOsRelease = backup - }() - - for expect, osRelease := range map[string][]byte{ - "Ubuntu 14.04 LTS": ubuntuTrusty, - "Gentoo/Linux": gentoo, - "": noPrettyName, - } { - if err := ioutil.WriteFile(etcOsRelease, osRelease, 0600); err != nil { - t.Fatalf("failed to write to %s: %v", etcOsRelease, err) - } - s, err := GetOperatingSystem() - if s != expect { - if expect == "" { - t.Fatalf("Expected error 'PRETTY_NAME not found', but got %v", err) - } else { - t.Fatalf("Expected '%s', but got '%s'. Err=%v", expect, s, err) - } - } - } -} - -func TestIsContainerized(t *testing.T) { - var ( - backup = proc1Cgroup - nonContainerizedProc1Cgroup = []byte(`14:name=systemd:/ -13:hugetlb:/ -12:net_prio:/ -11:perf_event:/ -10:bfqio:/ -9:blkio:/ -8:net_cls:/ -7:freezer:/ -6:devices:/ -5:memory:/ -4:cpuacct:/ -3:cpu:/ -2:cpuset:/ -`) - containerizedProc1Cgroup = []byte(`9:perf_event:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -8:blkio:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -7:net_cls:/ -6:freezer:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -5:devices:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -4:memory:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -3:cpuacct:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -2:cpu:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -1:cpuset:/`) - ) - - dir := os.TempDir() - proc1Cgroup = filepath.Join(dir, "proc1Cgroup") - - defer func() { - os.Remove(proc1Cgroup) - proc1Cgroup = backup - }() - - if err := ioutil.WriteFile(proc1Cgroup, nonContainerizedProc1Cgroup, 0600); err != nil { - t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) - } - inContainer, err := IsContainerized() - if err != nil { - t.Fatal(err) - } - if inContainer { - t.Fatal("Wrongly assuming containerized") - } - - if err := ioutil.WriteFile(proc1Cgroup, containerizedProc1Cgroup, 0600); err != nil { - t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) - } - inContainer, err = IsContainerized() - if err != nil { - t.Fatal(err) - } - if !inContainer { - t.Fatal("Wrongly assuming non-containerized") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_windows.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_windows.go deleted file mode 100644 index c843c6f84..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_windows.go +++ /dev/null @@ -1,47 +0,0 @@ -package operatingsystem - -import ( - "syscall" - "unsafe" -) - -// See https://code.google.com/p/go/source/browse/src/pkg/mime/type_windows.go?r=d14520ac25bf6940785aabb71f5be453a286f58c -// for a similar sample - -func GetOperatingSystem() (string, error) { - - var h syscall.Handle - - // Default return value - ret := "Unknown Operating System" - - if err := syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, - syscall.StringToUTF16Ptr(`SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\`), - 0, - syscall.KEY_READ, - &h); err != nil { - return ret, err - } - defer syscall.RegCloseKey(h) - - var buf [1 << 10]uint16 - var typ uint32 - n := uint32(len(buf) * 2) // api expects array of bytes, not uint16 - - if err := syscall.RegQueryValueEx(h, - syscall.StringToUTF16Ptr("ProductName"), - nil, - &typ, - (*byte)(unsafe.Pointer(&buf[0])), - &n); err != nil { - return ret, err - } - ret = syscall.UTF16ToString(buf[:]) - - return ret, nil -} - -// No-op on Windows -func IsContainerized() (bool, error) { - return false, nil -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/parsers_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/parsers_test.go deleted file mode 100644 index a64e6b946..000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/parsers_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package parsers - -import ( - "strings" - "testing" -) - -func TestParseHost(t *testing.T) { - var ( - defaultHttpHost = "127.0.0.1" - defaultUnix = "/var/run/docker.sock" - ) - invalids := map[string]string{ - "0.0.0.0": "Invalid bind address format: 0.0.0.0", - "tcp://": "Invalid proto, expected tcp: ", - "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", - "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", - "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1", - "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375", - } - valids := map[string]string{ - "0.0.0.1:5555": "tcp://0.0.0.1:5555", - "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", - ":6666": "tcp://127.0.0.1:6666", - ":6666/path": "tcp://127.0.0.1:6666/path", - "tcp://:7777": "tcp://127.0.0.1:7777", - "tcp://:7777/path": "tcp://127.0.0.1:7777/path", - "": "unix:///var/run/docker.sock", - "unix:///run/docker.sock": "unix:///run/docker.sock", - "unix://": "unix:///var/run/docker.sock", - "fd://": "fd://", - "fd://something": "fd://something", - } - for invalidAddr, expectedError := range invalids { - if addr, err := ParseHost(defaultHttpHost, defaultUnix, invalidAddr); err == nil || err.Error() != expectedError { - t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr) - } - } - for validAddr, expectedAddr := range valids { - if addr, err := ParseHost(defaultHttpHost, defaultUnix, validAddr); err != nil || addr != expectedAddr { - t.Errorf("%v -> expected %v, got %v", validAddr, expectedAddr, addr) - } - } -} - -func TestParseInvalidUnixAddrInvalid(t *testing.T) { - if _, err := ParseUnixAddr("unix://tcp://127.0.0.1", "unix:///var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" { - t.Fatalf("Expected an error, got %v", err) - } -} - -func TestParseRepositoryTag(t *testing.T) { - if repo, tag := ParseRepositoryTag("root"); repo != "root" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("root:tag"); repo != "root" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("root@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "root" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "root", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } - if repo, tag := ParseRepositoryTag("user/repo"); repo != "user/repo" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("user/repo:tag"); repo != "user/repo" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("user/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "user/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "user/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } - if repo, tag := ParseRepositoryTag("url:5000/repo"); repo != "url:5000/repo" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("url:5000/repo:tag"); repo != "url:5000/repo" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("url:5000/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "url:5000/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "url:5000/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } -} - -func TestParsePortMapping(t *testing.T) { - if _, err := PartParser("ip:public:private", "192.168.1.1:80"); err == nil { - t.Fatalf("Expected an error, got %v", err) - } - data, err := PartParser("ip:public:private", "192.168.1.1:80:8080") - if err != nil { - t.Fatal(err) - } - - if len(data) != 3 { - t.FailNow() - } - if data["ip"] != "192.168.1.1" { - t.Fail() - } - if data["public"] != "80" { - t.Fail() - } - if data["private"] != "8080" { - t.Fail() - } -} - -func TestParseKeyValueOpt(t *testing.T) { - invalids := map[string]string{ - "": "Unable to parse key/value option: ", - "key": "Unable to parse key/value option: key", - } - for invalid, expectedError := range invalids { - if _, _, err := ParseKeyValueOpt(invalid); err == nil || err.Error() != expectedError { - t.Fatalf("Expected error %v for %v, got %v", expectedError, invalid, err) - } - } - valids := map[string][]string{ - "key=value": {"key", "value"}, - " key = value ": {"key", "value"}, - "key=value1=value2": {"key", "value1=value2"}, - " key = value1 = value2 ": {"key", "value1 = value2"}, - } - for valid, expectedKeyValue := range valids { - key, value, err := ParseKeyValueOpt(valid) - if err != nil { - t.Fatal(err) - } - if key != expectedKeyValue[0] || value != expectedKeyValue[1] { - t.Fatalf("Expected {%v: %v} got {%v: %v}", expectedKeyValue[0], expectedKeyValue[1], key, value) - } - } -} - -func TestParsePortRange(t *testing.T) { - if start, end, err := ParsePortRange("8000-8080"); err != nil || start != 8000 || end != 8080 { - t.Fatalf("Error: %s or Expecting {start,end} values {8000,8080} but found {%d,%d}.", err, start, end) - } -} - -func TestParsePortRangeEmpty(t *testing.T) { - if _, _, err := ParsePortRange(""); err == nil || err.Error() != "Empty string specified for ports." { - t.Fatalf("Expected error 'Empty string specified for ports.', got %v", err) - } -} - -func TestParsePortRangeWithNoRange(t *testing.T) { - start, end, err := ParsePortRange("8080") - if err != nil { - t.Fatal(err) - } - if start != 8080 || end != 8080 { - t.Fatalf("Expected start and end to be the same and equal to 8080, but were %v and %v", start, end) - } -} - -func TestParsePortRangeIncorrectRange(t *testing.T) { - if _, _, err := ParsePortRange("9000-8080"); err == nil || !strings.Contains(err.Error(), "Invalid range specified for the Port") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParsePortRangeIncorrectEndRange(t *testing.T) { - if _, _, err := ParsePortRange("8000-a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } - - if _, _, err := ParsePortRange("8000-30a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParsePortRangeIncorrectStartRange(t *testing.T) { - if _, _, err := ParsePortRange("a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } - - if _, _, err := ParsePortRange("30a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParseLink(t *testing.T) { - name, alias, err := ParseLink("name:alias") - if err != nil { - t.Fatalf("Expected not to error out on a valid name:alias format but got: %v", err) - } - if name != "name" { - t.Fatalf("Link name should have been name, got %s instead", name) - } - if alias != "alias" { - t.Fatalf("Link alias should have been alias, got %s instead", alias) - } - // short format definition - name, alias, err = ParseLink("name") - if err != nil { - t.Fatalf("Expected not to error out on a valid name only format but got: %v", err) - } - if name != "name" { - t.Fatalf("Link name should have been name, got %s instead", name) - } - if alias != "name" { - t.Fatalf("Link alias should have been name, got %s instead", alias) - } - // empty string link definition is not allowed - if _, _, err := ParseLink(""); err == nil || !strings.Contains(err.Error(), "empty string specified for links") { - t.Fatalf("Expected error 'empty string specified for links' but got: %v", err) - } - // more than two colons are not allowed - if _, _, err := ParseLink("link:alias:wrong"); err == nil || !strings.Contains(err.Error(), "bad format for links: link:alias:wrong") { - t.Fatalf("Expected error 'bad format for links: link:alias:wrong' but got: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/go-units/duration_test.go b/Godeps/_workspace/src/github.com/docker/go-units/duration_test.go deleted file mode 100644 index 63baa515b..000000000 --- a/Godeps/_workspace/src/github.com/docker/go-units/duration_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package units - -import ( - "fmt" - "testing" - "time" -) - -func ExampleHumanDuration() { - fmt.Println(HumanDuration(450 * time.Millisecond)) - fmt.Println(HumanDuration(47 * time.Second)) - fmt.Println(HumanDuration(1 * time.Minute)) - fmt.Println(HumanDuration(3 * time.Minute)) - fmt.Println(HumanDuration(35 * time.Minute)) - fmt.Println(HumanDuration(35*time.Minute + 40*time.Second)) - fmt.Println(HumanDuration(1 * time.Hour)) - fmt.Println(HumanDuration(1*time.Hour + 45*time.Minute)) - fmt.Println(HumanDuration(3 * time.Hour)) - fmt.Println(HumanDuration(3*time.Hour + 59*time.Minute)) - fmt.Println(HumanDuration(3*time.Hour + 60*time.Minute)) - fmt.Println(HumanDuration(24 * time.Hour)) - fmt.Println(HumanDuration(24*time.Hour + 12*time.Hour)) - fmt.Println(HumanDuration(2 * 24 * time.Hour)) - fmt.Println(HumanDuration(7 * 24 * time.Hour)) - fmt.Println(HumanDuration(13*24*time.Hour + 5*time.Hour)) - fmt.Println(HumanDuration(2 * 7 * 24 * time.Hour)) - fmt.Println(HumanDuration(2*7*24*time.Hour + 4*24*time.Hour)) - fmt.Println(HumanDuration(3 * 7 * 24 * time.Hour)) - fmt.Println(HumanDuration(4 * 7 * 24 * time.Hour)) - fmt.Println(HumanDuration(4*7*24*time.Hour + 3*24*time.Hour)) - fmt.Println(HumanDuration(1 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(1*30*24*time.Hour + 2*7*24*time.Hour)) - fmt.Println(HumanDuration(2 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(3*30*24*time.Hour + 1*7*24*time.Hour)) - fmt.Println(HumanDuration(5*30*24*time.Hour + 2*7*24*time.Hour)) - fmt.Println(HumanDuration(13 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(23 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(24 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(24*30*24*time.Hour + 2*7*24*time.Hour)) - fmt.Println(HumanDuration(3*365*24*time.Hour + 2*30*24*time.Hour)) -} - -func TestHumanDuration(t *testing.T) { - // Useful duration abstractions - day := 24 * time.Hour - week := 7 * day - month := 30 * day - year := 365 * day - - assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond)) - assertEquals(t, "47 seconds", HumanDuration(47*time.Second)) - assertEquals(t, "About a minute", HumanDuration(1*time.Minute)) - assertEquals(t, "3 minutes", HumanDuration(3*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute)) - assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute)) - assertEquals(t, "24 hours", HumanDuration(24*time.Hour)) - assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour)) - assertEquals(t, "2 days", HumanDuration(2*day)) - assertEquals(t, "7 days", HumanDuration(7*day)) - assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour)) - assertEquals(t, "2 weeks", HumanDuration(2*week)) - assertEquals(t, "2 weeks", HumanDuration(2*week+4*day)) - assertEquals(t, "3 weeks", HumanDuration(3*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week+3*day)) - assertEquals(t, "4 weeks", HumanDuration(1*month)) - assertEquals(t, "6 weeks", HumanDuration(1*month+2*week)) - assertEquals(t, "8 weeks", HumanDuration(2*month)) - assertEquals(t, "3 months", HumanDuration(3*month+1*week)) - assertEquals(t, "5 months", HumanDuration(5*month+2*week)) - assertEquals(t, "13 months", HumanDuration(13*month)) - assertEquals(t, "23 months", HumanDuration(23*month)) - assertEquals(t, "24 months", HumanDuration(24*month)) - assertEquals(t, "2 years", HumanDuration(24*month+2*week)) - assertEquals(t, "3 years", HumanDuration(3*year+2*month)) -} diff --git a/Godeps/_workspace/src/github.com/docker/go-units/size_test.go b/Godeps/_workspace/src/github.com/docker/go-units/size_test.go deleted file mode 100644 index a968f5c0d..000000000 --- a/Godeps/_workspace/src/github.com/docker/go-units/size_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package units - -import ( - "fmt" - "reflect" - "runtime" - "strings" - "testing" -) - -func ExampleBytesSize() { - fmt.Println(BytesSize(1024)) - fmt.Println(BytesSize(1024 * 1024)) - fmt.Println(BytesSize(1048576)) - fmt.Println(BytesSize(2 * MiB)) - fmt.Println(BytesSize(3.42 * GiB)) - fmt.Println(BytesSize(5.372 * TiB)) - fmt.Println(BytesSize(2.22 * PiB)) -} - -func ExampleHumanSize() { - fmt.Println(HumanSize(1000)) - fmt.Println(HumanSize(1024)) - fmt.Println(HumanSize(1000000)) - fmt.Println(HumanSize(1048576)) - fmt.Println(HumanSize(2 * MB)) - fmt.Println(HumanSize(float64(3.42 * GB))) - fmt.Println(HumanSize(float64(5.372 * TB))) - fmt.Println(HumanSize(float64(2.22 * PB))) -} - -func ExampleFromHumanSize() { - fmt.Println(FromHumanSize("32")) - fmt.Println(FromHumanSize("32b")) - fmt.Println(FromHumanSize("32B")) - fmt.Println(FromHumanSize("32k")) - fmt.Println(FromHumanSize("32K")) - fmt.Println(FromHumanSize("32kb")) - fmt.Println(FromHumanSize("32Kb")) - fmt.Println(FromHumanSize("32Mb")) - fmt.Println(FromHumanSize("32Gb")) - fmt.Println(FromHumanSize("32Tb")) - fmt.Println(FromHumanSize("32Pb")) -} - -func ExampleRAMInBytes() { - fmt.Println(RAMInBytes("32")) - fmt.Println(RAMInBytes("32b")) - fmt.Println(RAMInBytes("32B")) - fmt.Println(RAMInBytes("32k")) - fmt.Println(RAMInBytes("32K")) - fmt.Println(RAMInBytes("32kb")) - fmt.Println(RAMInBytes("32Kb")) - fmt.Println(RAMInBytes("32Mb")) - fmt.Println(RAMInBytes("32Gb")) - fmt.Println(RAMInBytes("32Tb")) - fmt.Println(RAMInBytes("32Pb")) - fmt.Println(RAMInBytes("32PB")) - fmt.Println(RAMInBytes("32P")) -} - -func TestBytesSize(t *testing.T) { - assertEquals(t, "1 KiB", BytesSize(1024)) - assertEquals(t, "1 MiB", BytesSize(1024*1024)) - assertEquals(t, "1 MiB", BytesSize(1048576)) - assertEquals(t, "2 MiB", BytesSize(2*MiB)) - assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) - assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) - assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) -} - -func TestHumanSize(t *testing.T) { - assertEquals(t, "1 kB", HumanSize(1000)) - assertEquals(t, "1.024 kB", HumanSize(1024)) - assertEquals(t, "1 MB", HumanSize(1000000)) - assertEquals(t, "1.049 MB", HumanSize(1048576)) - assertEquals(t, "2 MB", HumanSize(2*MB)) - assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB))) - assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB))) - assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB))) -} - -func TestFromHumanSize(t *testing.T) { - assertSuccessEquals(t, 32, FromHumanSize, "32") - assertSuccessEquals(t, 32, FromHumanSize, "32b") - assertSuccessEquals(t, 32, FromHumanSize, "32B") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32k") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32K") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb") - assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb") - assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb") - assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb") - assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb") - - assertError(t, FromHumanSize, "") - assertError(t, FromHumanSize, "hello") - assertError(t, FromHumanSize, "-32") - assertError(t, FromHumanSize, "32.3") - assertError(t, FromHumanSize, " 32 ") - assertError(t, FromHumanSize, "32.3Kb") - assertError(t, FromHumanSize, "32 mb") - assertError(t, FromHumanSize, "32m b") - assertError(t, FromHumanSize, "32bm") -} - -func TestRAMInBytes(t *testing.T) { - assertSuccessEquals(t, 32, RAMInBytes, "32") - assertSuccessEquals(t, 32, RAMInBytes, "32b") - assertSuccessEquals(t, 32, RAMInBytes, "32B") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") - assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") - assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") - assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P") - - assertError(t, RAMInBytes, "") - assertError(t, RAMInBytes, "hello") - assertError(t, RAMInBytes, "-32") - assertError(t, RAMInBytes, "32.3") - assertError(t, RAMInBytes, " 32 ") - assertError(t, RAMInBytes, "32.3Kb") - assertError(t, RAMInBytes, "32 mb") - assertError(t, RAMInBytes, "32m b") - assertError(t, RAMInBytes, "32bm") -} - -func assertEquals(t *testing.T, expected, actual interface{}) { - if expected != actual { - t.Errorf("Expected '%v' but got '%v'", expected, actual) - } -} - -// func that maps to the parse function signatures as testing abstraction -type parseFn func(string) (int64, error) - -// Define 'String()' for pretty-print -func (fn parseFn) String() string { - fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() - return fnName[strings.LastIndex(fnName, ".")+1:] -} - -func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) { - res, err := fn(arg) - if err != nil || res != expected { - t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err) - } -} - -func assertError(t *testing.T, fn parseFn, arg string) { - res, err := fn(arg) - if err == nil && res != -1 { - t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/go-units/ulimit_test.go b/Godeps/_workspace/src/github.com/docker/go-units/ulimit_test.go deleted file mode 100644 index 3e7f10fc2..000000000 --- a/Godeps/_workspace/src/github.com/docker/go-units/ulimit_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package units - -import ( - "fmt" - "strconv" - "testing" -) - -func ExampleParseUlimit() { - fmt.Println(ParseUlimit("nofile=512:1024")) - fmt.Println(ParseUlimit("nofile=1024")) - fmt.Println(ParseUlimit("cpu=2:4")) - fmt.Println(ParseUlimit("cpu=6")) -} - -func TestParseUlimitValid(t *testing.T) { - u1 := &Ulimit{"nofile", 1024, 512} - if u2, _ := ParseUlimit("nofile=512:1024"); *u1 != *u2 { - t.Fatalf("expected %q, but got %q", u1, u2) - } -} - -func TestParseUlimitInvalidLimitType(t *testing.T) { - if _, err := ParseUlimit("notarealtype=1024:1024"); err == nil { - t.Fatalf("expected error on invalid ulimit type") - } -} - -func TestParseUlimitBadFormat(t *testing.T) { - if _, err := ParseUlimit("nofile:1024:1024"); err == nil { - t.Fatal("expected error on bad syntax") - } - - if _, err := ParseUlimit("nofile"); err == nil { - t.Fatal("expected error on bad syntax") - } - - if _, err := ParseUlimit("nofile="); err == nil { - t.Fatal("expected error on bad syntax") - } - if _, err := ParseUlimit("nofile=:"); err == nil { - t.Fatal("expected error on bad syntax") - } - if _, err := ParseUlimit("nofile=:1024"); err == nil { - t.Fatal("expected error on bad syntax") - } -} - -func TestParseUlimitHardLessThanSoft(t *testing.T) { - if _, err := ParseUlimit("nofile=1024:1"); err == nil { - t.Fatal("expected error on hard limit less than soft limit") - } -} - -func TestParseUlimitInvalidValueType(t *testing.T) { - if _, err := ParseUlimit("nofile=asdf"); err == nil { - t.Fatal("expected error on bad value type, but got no error") - } else if _, ok := err.(*strconv.NumError); !ok { - t.Fatalf("expected error on bad value type, but got `%s`", err) - } - - if _, err := ParseUlimit("nofile=1024:asdf"); err == nil { - t.Fatal("expected error on bad value type, but got no error") - } else if _, ok := err.(*strconv.NumError); !ok { - t.Fatalf("expected error on bad value type, but got `%s`", err) - } -} - -func TestUlimitStringOutput(t *testing.T) { - u := &Ulimit{"nofile", 1024, 512} - if s := u.String(); s != "nofile=512:1024" { - t.Fatal("expected String to return nofile=512:1024, but got", s) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_curly_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_curly_test.go deleted file mode 100644 index db6a1a752..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_curly_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package restful - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" -) - -func setupCurly(container *Container) []string { - wsCount := 26 - rtCount := 26 - urisCurly := []string{} - - container.Router(CurlyRouter{}) - for i := 0; i < wsCount; i++ { - root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) - ws := new(WebService).Path(root) - for j := 0; j < rtCount; j++ { - sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) - ws.Route(ws.GET(sub).Consumes("application/xml").Produces("application/xml").To(echoCurly)) - } - container.Add(ws) - for _, each := range ws.Routes() { - urisCurly = append(urisCurly, "http://bench.com"+each.Path) - } - } - return urisCurly -} - -func echoCurly(req *Request, resp *Response) {} - -func BenchmarkManyCurly(b *testing.B) { - container := NewContainer() - urisCurly := setupCurly(container) - b.ResetTimer() - for t := 0; t < b.N; t++ { - for r := 0; r < 1000; r++ { - for _, each := range urisCurly { - sendNoReturnTo(each, container, t) - } - } - } -} - -func sendNoReturnTo(address string, container *Container, t int) { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "application/xml") - httpWriter := httptest.NewRecorder() - container.dispatch(httpWriter, httpRequest) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_test.go deleted file mode 100644 index 3e77c2d29..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package restful - -import ( - "fmt" - "io" - "testing" -) - -var uris = []string{} - -func setup(container *Container) { - wsCount := 26 - rtCount := 26 - - for i := 0; i < wsCount; i++ { - root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) - ws := new(WebService).Path(root) - for j := 0; j < rtCount; j++ { - sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) - ws.Route(ws.GET(sub).To(echo)) - } - container.Add(ws) - for _, each := range ws.Routes() { - uris = append(uris, "http://bench.com"+each.Path) - } - } -} - -func echo(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "echo") -} - -func BenchmarkMany(b *testing.B) { - container := NewContainer() - setup(container) - b.ResetTimer() - for t := 0; t < b.N; t++ { - for _, each := range uris { - // println(each) - sendItTo(each, container) - } - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/compress_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/compress_test.go deleted file mode 100644 index 84a93c3fc..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/compress_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package restful - -import ( - "bytes" - "compress/gzip" - "compress/zlib" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestGzip ...restful -func TestGzip(t *testing.T) { - EnableContentEncoding = true - httpRequest, _ := http.NewRequest("GET", "/test", nil) - httpRequest.Header.Set("Accept-Encoding", "gzip,deflate") - httpWriter := httptest.NewRecorder() - wanted, encoding := wantsCompressedResponse(httpRequest) - if !wanted { - t.Fatal("should accept gzip") - } - if encoding != "gzip" { - t.Fatal("expected gzip") - } - c, err := NewCompressingResponseWriter(httpWriter, encoding) - if err != nil { - t.Fatal(err.Error()) - } - c.Write([]byte("Hello World")) - c.Close() - if httpWriter.Header().Get("Content-Encoding") != "gzip" { - t.Fatal("Missing gzip header") - } - reader, err := gzip.NewReader(httpWriter.Body) - if err != nil { - t.Fatal(err.Error()) - } - data, err := ioutil.ReadAll(reader) - if err != nil { - t.Fatal(err.Error()) - } - if got, want := string(data), "Hello World"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestDeflate(t *testing.T) { - EnableContentEncoding = true - httpRequest, _ := http.NewRequest("GET", "/test", nil) - httpRequest.Header.Set("Accept-Encoding", "deflate,gzip") - httpWriter := httptest.NewRecorder() - wanted, encoding := wantsCompressedResponse(httpRequest) - if !wanted { - t.Fatal("should accept deflate") - } - if encoding != "deflate" { - t.Fatal("expected deflate") - } - c, err := NewCompressingResponseWriter(httpWriter, encoding) - if err != nil { - t.Fatal(err.Error()) - } - c.Write([]byte("Hello World")) - c.Close() - if httpWriter.Header().Get("Content-Encoding") != "deflate" { - t.Fatal("Missing deflate header") - } - reader, err := zlib.NewReader(httpWriter.Body) - if err != nil { - t.Fatal(err.Error()) - } - data, err := ioutil.ReadAll(reader) - if err != nil { - t.Fatal(err.Error()) - } - if got, want := string(data), "Hello World"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestGzipDecompressRequestBody(t *testing.T) { - b := new(bytes.Buffer) - w := newGzipWriter() - w.Reset(b) - io.WriteString(w, `{"msg":"hi"}`) - w.Flush() - w.Close() - - req := new(Request) - httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) - httpRequest.Header.Set("Content-Type", "application/json") - httpRequest.Header.Set("Content-Encoding", "gzip") - req.Request = httpRequest - - doCacheReadEntityBytes = false - doc := make(map[string]interface{}) - req.ReadEntity(&doc) - - if got, want := doc["msg"], "hi"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestZlibDecompressRequestBody(t *testing.T) { - b := new(bytes.Buffer) - w := newZlibWriter() - w.Reset(b) - io.WriteString(w, `{"msg":"hi"}`) - w.Flush() - w.Close() - - req := new(Request) - httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) - httpRequest.Header.Set("Content-Type", "application/json") - httpRequest.Header.Set("Content-Encoding", "deflate") - req.Request = httpRequest - - doCacheReadEntityBytes = false - doc := make(map[string]interface{}) - req.ReadEntity(&doc) - - if got, want := doc["msg"], "hi"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/container_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/container_test.go deleted file mode 100644 index dd2552c37..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/container_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestContainer_computeAllowedMethods ...restful -func TestContainer_computeAllowedMethods(t *testing.T) { - wc := NewContainer() - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.GET("{i}").To(dummy)) - ws1.Route(ws1.POST("{i}").To(dummy)) - wc.Add(ws1) - httpRequest, _ := http.NewRequest("GET", "http://api.his.com/users/1", nil) - rreq := Request{Request: httpRequest} - m := wc.computeAllowedMethods(&rreq) - if len(m) != 2 { - t.Errorf("got %d expected 2 methods, %v", len(m), m) - } -} - -func TestContainer_HandleWithFilter(t *testing.T) { - prefilterCalled := false - postfilterCalled := false - httpHandlerCalled := false - - wc := NewContainer() - wc.Filter(func(request *Request, response *Response, chain *FilterChain) { - prefilterCalled = true - chain.ProcessFilter(request, response) - }) - wc.HandleWithFilter("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - httpHandlerCalled = true - w.Write([]byte("ok")) - })) - wc.Filter(func(request *Request, response *Response, chain *FilterChain) { - postfilterCalled = true - chain.ProcessFilter(request, response) - }) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/", nil) - wc.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("unexpected code %d", recorder.Code) - } - if recorder.Body.String() != "ok" { - t.Errorf("unexpected body %s", recorder.Body.String()) - } - if !prefilterCalled { - t.Errorf("filter added before calling HandleWithFilter wasn't called") - } - if !postfilterCalled { - t.Errorf("filter added after calling HandleWithFilter wasn't called") - } - if !httpHandlerCalled { - t.Errorf("handler added by calling HandleWithFilter wasn't called") - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/cors_filter_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/cors_filter_test.go deleted file mode 100644 index 9b4723089..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/cors_filter_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestCORSFilter_Preflight ...restful -// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request -func TestCORSFilter_Preflight(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - ExposeHeaders: []string{"X-Custom-Header"}, - AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - // Preflight - httpRequest, _ := http.NewRequest("OPTIONS", "http://api.alice.com/cors", nil) - httpRequest.Method = "OPTIONS" - httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") - httpRequest.Header.Set(HEADER_AccessControlRequestMethod, "PUT") - httpRequest.Header.Set(HEADER_AccessControlRequestHeaders, "X-Custom-Header, X-Additional-Header") - - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if "http://api.bob.com" != actual { - t.Fatal("expected: http://api.bob.com but got:" + actual) - } - actual = httpWriter.Header().Get(HEADER_AccessControlAllowMethods) - if "PUT" != actual { - t.Fatal("expected: PUT but got:" + actual) - } - actual = httpWriter.Header().Get(HEADER_AccessControlAllowHeaders) - if "X-Custom-Header, X-Additional-Header" != actual { - t.Fatal("expected: X-Custom-Header, X-Additional-Header but got:" + actual) - } - - if !cors.isOriginAllowed("somewhere") { - t.Fatal("origin expected to be allowed") - } - cors.AllowedDomains = []string{"overthere.com"} - if cors.isOriginAllowed("somewhere") { - t.Fatal("origin [somewhere] expected NOT to be allowed") - } - if !cors.isOriginAllowed("overthere.com") { - t.Fatal("origin [overthere] expected to be allowed") - } - -} - -// go test -v -test.run TestCORSFilter_Actual ...restful -// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request -func TestCORSFilter_Actual(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - ExposeHeaders: []string{"X-Custom-Header"}, - AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - // Actual - httpRequest, _ := http.NewRequest("PUT", "http://api.alice.com/cors", nil) - httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") - httpRequest.Header.Set("X-Custom-Header", "value") - - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if "http://api.bob.com" != actual { - t.Fatal("expected: http://api.bob.com but got:" + actual) - } - if httpWriter.Body.String() != "dummy" { - t.Fatal("expected: dummy but got:" + httpWriter.Body.String()) - } -} - -var allowedDomainInput = []struct { - domains []string - origin string - accepted bool -}{ - {[]string{}, "http://anything.com", true}, -} - -// go test -v -test.run TestCORSFilter_AllowedDomains ...restful -func TestCORSFilter_AllowedDomains(t *testing.T) { - for _, each := range allowedDomainInput { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - AllowedDomains: each.domains, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil) - httpRequest.Header.Set(HEADER_Origin, each.origin) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if actual != each.origin && each.accepted { - t.Fatal("expected to be accepted") - } - if actual == each.origin && !each.accepted { - t.Fatal("did not expect to be accepted") - } - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/curly_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/curly_test.go deleted file mode 100644 index 31d66dcbd..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/curly_test.go +++ /dev/null @@ -1,231 +0,0 @@ -package restful - -import ( - "io" - "net/http" - "testing" -) - -var requestPaths = []struct { - // url with path (1) is handled by service with root (2) and remainder has value final (3) - path, root string -}{ - {"/", "/"}, - {"/p", "/p"}, - {"/p/x", "/p/{q}"}, - {"/q/x", "/q"}, - {"/p/x/", "/p/{q}"}, - {"/p/x/y", "/p/{q}"}, - {"/q/x/y", "/q"}, - {"/z/q", "/{p}/q"}, - {"/a/b/c/q", "/"}, -} - -// go test -v -test.run TestCurlyDetectWebService ...restful -func TestCurlyDetectWebService(t *testing.T) { - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws7 := new(WebService).Path("/{p}/q") - var wss = []*WebService{ws1, ws2, ws3, ws4, ws5, ws7} - - for _, each := range wss { - t.Logf("path=%s,toks=%v\n", each.pathExpr.Source, each.pathExpr.tokens) - } - - router := CurlyRouter{} - - ok := true - for i, fixture := range requestPaths { - requestTokens := tokenizePath(fixture.path) - who := router.detectWebService(requestTokens, wss) - if who != nil && who.RootPath() != fixture.root { - t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) - ok = false - } - } - if !ok { - t.Fail() - } -} - -var serviceDetects = []struct { - path string - found bool - root string -}{ - {"/a/b", true, "/{p}/{q}/{r}"}, - {"/p/q", true, "/p/q"}, - {"/q/p", true, "/q"}, - {"/", true, "/"}, - {"/p/q/r", true, "/p/q"}, -} - -// go test -v -test.run Test_detectWebService ...restful -func Test_detectWebService(t *testing.T) { - router := CurlyRouter{} - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws6 := new(WebService).Path("/p/{q}/") - ws7 := new(WebService).Path("/{p}/q") - ws8 := new(WebService).Path("/{p}/{q}/{r}") - var wss = []*WebService{ws8, ws7, ws6, ws5, ws4, ws3, ws2, ws1} - for _, fix := range serviceDetects { - requestPath := fix.path - requestTokens := tokenizePath(requestPath) - for _, ws := range wss { - serviceTokens := ws.pathExpr.tokens - matches, score := router.computeWebserviceScore(requestTokens, serviceTokens) - t.Logf("req=%s,toks:%v,ws=%s,toks:%v,score=%d,matches=%v", requestPath, requestTokens, ws.RootPath(), serviceTokens, score, matches) - } - best := router.detectWebService(requestTokens, wss) - if best != nil { - if fix.found { - t.Logf("best=%s", best.RootPath()) - } else { - t.Fatalf("should have found:%s", fix.root) - } - } - } -} - -var routeMatchers = []struct { - route string - path string - matches bool - paramCount int - staticCount int -}{ - // route, request-path - {"/a", "/a", true, 0, 1}, - {"/a", "/b", false, 0, 0}, - {"/a", "/b", false, 0, 0}, - {"/a/{b}/c/", "/a/2/c", true, 1, 2}, - {"/{a}/{b}/{c}/", "/a/b", false, 0, 0}, - {"/{x:*}", "/", false, 0, 0}, - {"/{x:*}", "/a", true, 1, 0}, - {"/{x:*}", "/a/b", true, 1, 0}, - {"/a/{x:*}", "/a/b", true, 1, 1}, - {"/a/{x:[A-Z][A-Z]}", "/a/ZX", true, 1, 1}, - {"/basepath/{resource:*}", "/basepath/some/other/location/test.xml", true, 1, 1}, -} - -// clear && go test -v -test.run Test_matchesRouteByPathTokens ...restful -func Test_matchesRouteByPathTokens(t *testing.T) { - router := CurlyRouter{} - for i, each := range routeMatchers { - routeToks := tokenizePath(each.route) - reqToks := tokenizePath(each.path) - matches, pCount, sCount := router.matchesRouteByPathTokens(routeToks, reqToks) - if matches != each.matches { - t.Fatalf("[%d] unexpected matches outcome route:%s, path:%s, matches:%v", i, each.route, each.path, matches) - } - if pCount != each.paramCount { - t.Fatalf("[%d] unexpected paramCount got:%d want:%d ", i, pCount, each.paramCount) - } - if sCount != each.staticCount { - t.Fatalf("[%d] unexpected staticCount got:%d want:%d ", i, sCount, each.staticCount) - } - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard1 ...restful -func TestExtractParameters_Wildcard1(t *testing.T) { - params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remainder", t) - if params["var"] != "remainder" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard2 ...restful -func TestExtractParameters_Wildcard2(t *testing.T) { - params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remain/der", t) - if params["var"] != "remain/der" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard3 ...restful -func TestExtractParameters_Wildcard3(t *testing.T) { - params := doExtractParams("/static/{var:*}", 2, "/static/test/sub/hi.html", t) - if params["var"] != "test/sub/hi.html" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestCurly_ISSUE_34 ...restful -func TestCurly_ISSUE_34(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) - ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) - routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// clear && go test -v -test.run TestCurly_ISSUE_34_2 ...restful -func TestCurly_ISSUE_34_2(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) - ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) - routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// clear && go test -v -test.run TestCurly_JsonHtml ...restful -func TestCurly_JsonHtml(t *testing.T) { - ws1 := new(WebService) - ws1.Path("/") - ws1.Route(ws1.GET("/some.html").To(curlyDummy).Consumes("*/*").Produces("text/html")) - req, _ := http.NewRequest("GET", "/some.html", nil) - req.Header.Set("Accept", "application/json") - _, route, err := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - if err == nil { - t.Error("error expected") - } - if route != nil { - t.Error("no route expected") - } -} - -// go test -v -test.run TestCurly_ISSUE_137 ...restful -func TestCurly_ISSUE_137(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(curlyDummy)) - ws1.Path("/") - req, _ := http.NewRequest("GET", "/", nil) - _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - t.Log(route) - if route != nil { - t.Error("no route expected") - } -} - -// go test -v -test.run TestCurly_ISSUE_137_2 ...restful -func TestCurly_ISSUE_137_2(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(curlyDummy)) - ws1.Path("/") - req, _ := http.NewRequest("GET", "/hello/bob", nil) - _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - t.Log(route) - if route != nil { - t.Errorf("no route expected, got %v", route) - } -} - -func curlyDummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "curlyDummy") } diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/doc_examples_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/doc_examples_test.go deleted file mode 100644 index 0af636e55..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/doc_examples_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package restful - -import "net/http" - -func ExampleOPTIONSFilter() { - // Install the OPTIONS filter on the default Container - Filter(OPTIONSFilter()) -} -func ExampleContainer_OPTIONSFilter() { - // Install the OPTIONS filter on a Container - myContainer := new(Container) - myContainer.Filter(myContainer.OPTIONSFilter) -} - -func ExampleContainer() { - // The Default container of go-restful uses the http.DefaultServeMux. - // You can create your own Container using restful.NewContainer() and create a new http.Server for that particular container - - ws := new(WebService) - wsContainer := NewContainer() - wsContainer.Add(ws) - server := &http.Server{Addr: ":8080", Handler: wsContainer} - server.ListenAndServe() -} - -func ExampleCrossOriginResourceSharing() { - // To install this filter on the Default Container use: - cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} - Filter(cors.Filter) -} - -func ExampleServiceError() { - resp := new(Response) - resp.WriteEntity(NewError(http.StatusBadRequest, "Non-integer {id} path parameter")) -} - -func ExampleBoundedCachedCompressors() { - // Register a compressor provider (gzip/deflate read/write) that uses - // a bounded cache with a maximum of 20 writers and 20 readers. - SetCompressorProvider(NewBoundedCachedCompressors(20, 20)) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/entity_accessors_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/entity_accessors_test.go deleted file mode 100644 index 943093ae0..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/entity_accessors_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package restful - -import ( - "bytes" - "fmt" - "io" - "net/http" - "net/http/httptest" - "reflect" - "testing" -) - -type keyvalue struct { - readCalled bool - writeCalled bool -} - -func (kv *keyvalue) Read(req *Request, v interface{}) error { - //t := reflect.TypeOf(v) - //rv := reflect.ValueOf(v) - kv.readCalled = true - return nil -} - -func (kv *keyvalue) Write(resp *Response, status int, v interface{}) error { - t := reflect.TypeOf(v) - rv := reflect.ValueOf(v) - for ix := 0; ix < t.NumField(); ix++ { - sf := t.Field(ix) - io.WriteString(resp, sf.Name) - io.WriteString(resp, "=") - io.WriteString(resp, fmt.Sprintf("%v\n", rv.Field(ix).Interface())) - } - kv.writeCalled = true - return nil -} - -// go test -v -test.run TestKeyValueEncoding ...restful -func TestKeyValueEncoding(t *testing.T) { - type Book struct { - Title string - Author string - PublishedYear int - } - kv := new(keyvalue) - RegisterEntityAccessor("application/kv", kv) - b := Book{"Singing for Dummies", "john doe", 2015} - - // Write - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "application/kv,*/*;q=0.8", []string{"application/kv"}, 0, 0, true, nil} - resp.WriteEntity(b) - t.Log(string(httpWriter.Body.Bytes())) - if !kv.writeCalled { - t.Error("Write never called") - } - - // Read - bodyReader := bytes.NewReader(httpWriter.Body.Bytes()) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/kv; charset=UTF-8") - request := NewRequest(httpRequest) - var bb Book - request.ReadEntity(&bb) - if !kv.readCalled { - t.Error("Read never called") - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/.goconvey b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/.goconvey deleted file mode 100644 index 8485e986e..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/.goconvey +++ /dev/null @@ -1 +0,0 @@ -ignore \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey deleted file mode 100644 index 8485e986e..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey +++ /dev/null @@ -1 +0,0 @@ -ignore \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml deleted file mode 100644 index 362db6b07..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml +++ /dev/null @@ -1,20 +0,0 @@ -# -# Include your application ID here -# -application: -version: 1 -runtime: go -api_version: go1 - -handlers: -# -# Regex for all swagger files to make as static content. -# You should create the folder static/swagger and copy -# swagger-ui into it. -# -- url: /apidocs/(.*?)/(.*\.(js|html|css)) - static_files: static/swagger/\1/\2 - upload: static/swagger/(.*?)/(.*\.(js|html|css)) - -- url: /.* - script: _go_app diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey deleted file mode 100644 index 8485e986e..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey +++ /dev/null @@ -1 +0,0 @@ -ignore \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml deleted file mode 100644 index 1ac9dca28..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml +++ /dev/null @@ -1,18 +0,0 @@ -application: -version: 1 -runtime: go -api_version: go1 - -handlers: -# Regex for all swagger files to make as static content. -# You should create the folder static/swagger and copy -# swagger-ui into it. -# -- url: /apidocs/(.*?)/(.*\.(js|html|css)) - static_files: static/swagger/\1/\2 - upload: static/swagger/(.*?)/(.*\.(js|html|css)) - -# Catch all. -- url: /.* - script: _go_app - login: required diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go deleted file mode 100644 index 9f9c78d1f..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go +++ /dev/null @@ -1,266 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "github.com/emicklei/go-restful/swagger" - "google.golang.com/appengine" - "google.golang.com/appengine/datastore" - "google.golang.com/appengine/user" - "net/http" - "time" -) - -// This example demonstrates a reasonably complete suite of RESTful operations backed -// by DataStore on Google App Engine. - -// Our simple example struct. -type Profile struct { - LastModified time.Time `json:"-" xml:"-"` - Email string `json:"-" xml:"-"` - FirstName string `json:"first_name" xml:"first-name"` - NickName string `json:"nick_name" xml:"nick-name"` - LastName string `json:"last_name" xml:"last-name"` -} - -type ProfileApi struct { - Path string -} - -func gaeUrl() string { - if appengine.IsDevAppServer() { - return "http://localhost:8080" - } else { - // Include your URL on App Engine here. - // I found no way to get AppID without appengine.Context and this always - // based on a http.Request. - return "http://federatedservices.appspot.com" - } -} - -func init() { - u := ProfileApi{Path: "/profiles"} - u.register() - - // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API - // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. - // Open .appspot.com/apidocs and enter - // Place the Swagger UI files into a folder called static/swagger if you wish to use Swagger - // http://.appspot.com/apidocs.json in the api input field. - // For testing, you can use http://localhost:8080/apidocs.json - config := swagger.Config{ - // You control what services are visible - WebServices: restful.RegisteredWebServices(), - WebServicesUrl: gaeUrl(), - ApiPath: "/apidocs.json", - - // Optionally, specifiy where the UI is located - SwaggerPath: "/apidocs/", - - // GAE support static content which is configured in your app.yaml. - // This example expect the swagger-ui in static/swagger so you should place it there :) - SwaggerFilePath: "static/swagger"} - swagger.InstallSwaggerService(config) -} - -func (u ProfileApi) register() { - ws := new(restful.WebService) - - ws. - Path(u.Path). - // You can specify consumes and produces per route as well. - Consumes(restful.MIME_JSON, restful.MIME_XML). - Produces(restful.MIME_JSON, restful.MIME_XML) - - ws.Route(ws.POST("").To(u.insert). - // Swagger documentation. - Doc("insert a new profile"). - Param(ws.BodyParameter("Profile", "representation of a profile").DataType("main.Profile")). - Reads(Profile{})) - - ws.Route(ws.GET("/{profile-id}").To(u.read). - // Swagger documentation. - Doc("read a profile"). - Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string")). - Writes(Profile{})) - - ws.Route(ws.PUT("/{profile-id}").To(u.update). - // Swagger documentation. - Doc("update an existing profile"). - Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string")). - Param(ws.BodyParameter("Profile", "representation of a profile").DataType("main.Profile")). - Reads(Profile{})) - - ws.Route(ws.DELETE("/{profile-id}").To(u.remove). - // Swagger documentation. - Doc("remove a profile"). - Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string"))) - - restful.Add(ws) -} - -// POST http://localhost:8080/profiles -// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"} -// -func (u *ProfileApi) insert(r *restful.Request, w *restful.Response) { - c := appengine.NewContext(r.Request) - - // Marshall the entity from the request into a struct. - p := new(Profile) - err := r.ReadEntity(&p) - if err != nil { - w.WriteError(http.StatusNotAcceptable, err) - return - } - - // Ensure we start with a sensible value for this field. - p.LastModified = time.Now() - - // The profile belongs to this user. - p.Email = user.Current(c).String() - - k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "profiles", nil), p) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - // Let them know the location of the newly created resource. - // TODO: Use a safe Url path append function. - w.AddHeader("Location", u.Path+"/"+k.Encode()) - - // Return the resultant entity. - w.WriteHeader(http.StatusCreated) - w.WriteEntity(p) -} - -// GET http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM -// -func (u ProfileApi) read(r *restful.Request, w *restful.Response) { - c := appengine.NewContext(r.Request) - - // Decode the request parameter to determine the key for the entity. - k, err := datastore.DecodeKey(r.PathParameter("profile-id")) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - // Retrieve the entity from the datastore. - p := Profile{} - if err := datastore.Get(c, k, &p); err != nil { - if err.Error() == "datastore: no such entity" { - http.Error(w, err.Error(), http.StatusNotFound) - } else { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - return - } - - // Check we own the profile before allowing them to view it. - // Optionally, return a 404 instead to help prevent guessing ids. - // TODO: Allow admins access. - if p.Email != user.Current(c).String() { - http.Error(w, "You do not have access to this resource", http.StatusForbidden) - return - } - - w.WriteEntity(p) -} - -// PUT http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM -// {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"} -// -func (u *ProfileApi) update(r *restful.Request, w *restful.Response) { - c := appengine.NewContext(r.Request) - - // Decode the request parameter to determine the key for the entity. - k, err := datastore.DecodeKey(r.PathParameter("profile-id")) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - // Marshall the entity from the request into a struct. - p := new(Profile) - err = r.ReadEntity(&p) - if err != nil { - w.WriteError(http.StatusNotAcceptable, err) - return - } - - // Retrieve the old entity from the datastore. - old := Profile{} - if err := datastore.Get(c, k, &old); err != nil { - if err.Error() == "datastore: no such entity" { - http.Error(w, err.Error(), http.StatusNotFound) - } else { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - return - } - - // Check we own the profile before allowing them to update it. - // Optionally, return a 404 instead to help prevent guessing ids. - // TODO: Allow admins access. - if old.Email != user.Current(c).String() { - http.Error(w, "You do not have access to this resource", http.StatusForbidden) - return - } - - // Since the whole entity is re-written, we need to assign any invariant fields again - // e.g. the owner of the entity. - p.Email = user.Current(c).String() - - // Keep track of the last modification date. - p.LastModified = time.Now() - - // Attempt to overwrite the old entity. - _, err = datastore.Put(c, k, p) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - // Let them know it succeeded. - w.WriteHeader(http.StatusNoContent) -} - -// DELETE http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM -// -func (u *ProfileApi) remove(r *restful.Request, w *restful.Response) { - c := appengine.NewContext(r.Request) - - // Decode the request parameter to determine the key for the entity. - k, err := datastore.DecodeKey(r.PathParameter("profile-id")) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - // Retrieve the old entity from the datastore. - old := Profile{} - if err := datastore.Get(c, k, &old); err != nil { - if err.Error() == "datastore: no such entity" { - http.Error(w, err.Error(), http.StatusNotFound) - } else { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - return - } - - // Check we own the profile before allowing them to delete it. - // Optionally, return a 404 instead to help prevent guessing ids. - // TODO: Allow admins access. - if old.Email != user.Current(c).String() { - http.Error(w, "You do not have access to this resource", http.StatusForbidden) - return - } - - // Delete the entity. - if err := datastore.Delete(c, k); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - - // Success notification. - w.WriteHeader(http.StatusNoContent) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go deleted file mode 100644 index b3261eeb9..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - "github.com/mjibson/appstats" -) - - -func stats(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - c := appstats.NewContext(req.Request) - chain.ProcessFilter(req, resp) - c.Stats.Status = resp.StatusCode() - c.Save() -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go deleted file mode 100644 index 0e8830181..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go +++ /dev/null @@ -1,161 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "github.com/emicklei/go-restful/swagger" - "google.golang.com/appengine" - "google.golang.com/appengine/memcache" - "net/http" -) - -// This example is functionally the same as ../restful-user-service.go -// but it`s supposed to run on Goole App Engine (GAE) -// -// contributed by ivanhawkes - -type User struct { - Id, Name string -} - -type UserService struct { - // normally one would use DAO (data access object) - // but in this example we simple use memcache. -} - -func (u UserService) Register() { - ws := new(restful.WebService) - - ws. - Path("/users"). - Consumes(restful.MIME_XML, restful.MIME_JSON). - Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well - - ws.Route(ws.GET("/{user-id}").To(u.findUser). - // docs - Doc("get a user"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). - Writes(User{})) // on the response - - ws.Route(ws.PATCH("").To(u.updateUser). - // docs - Doc("update a user"). - Reads(User{})) // from the request - - ws.Route(ws.PUT("/{user-id}").To(u.createUser). - // docs - Doc("create a user"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). - Reads(User{})) // from the request - - ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). - // docs - Doc("delete a user"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) - - restful.Add(ws) -} - -// GET http://localhost:8080/users/1 -// -func (u UserService) findUser(request *restful.Request, response *restful.Response) { - c := appengine.NewContext(request.Request) - id := request.PathParameter("user-id") - usr := new(User) - _, err := memcache.Gob.Get(c, id, &usr) - if err != nil || len(usr.Id) == 0 { - response.WriteErrorString(http.StatusNotFound, "User could not be found.") - } else { - response.WriteEntity(usr) - } -} - -// PATCH http://localhost:8080/users -// 1Melissa Raspberry -// -func (u *UserService) updateUser(request *restful.Request, response *restful.Response) { - c := appengine.NewContext(request.Request) - usr := new(User) - err := request.ReadEntity(&usr) - if err == nil { - item := &memcache.Item{ - Key: usr.Id, - Object: &usr, - } - err = memcache.Gob.Set(c, item) - if err != nil { - response.WriteError(http.StatusInternalServerError, err) - return - } - response.WriteEntity(usr) - } else { - response.WriteError(http.StatusInternalServerError, err) - } -} - -// PUT http://localhost:8080/users/1 -// 1Melissa -// -func (u *UserService) createUser(request *restful.Request, response *restful.Response) { - c := appengine.NewContext(request.Request) - usr := User{Id: request.PathParameter("user-id")} - err := request.ReadEntity(&usr) - if err == nil { - item := &memcache.Item{ - Key: usr.Id, - Object: &usr, - } - err = memcache.Gob.Add(c, item) - if err != nil { - response.WriteError(http.StatusInternalServerError, err) - return - } - response.WriteHeader(http.StatusCreated) - response.WriteEntity(usr) - } else { - response.WriteError(http.StatusInternalServerError, err) - } -} - -// DELETE http://localhost:8080/users/1 -// -func (u *UserService) removeUser(request *restful.Request, response *restful.Response) { - c := appengine.NewContext(request.Request) - id := request.PathParameter("user-id") - err := memcache.Delete(c, id) - if err != nil { - response.WriteError(http.StatusInternalServerError, err) - } -} - -func getGaeURL() string { - if appengine.IsDevAppServer() { - return "http://localhost:8080" - } else { - /** - * Include your URL on App Engine here. - * I found no way to get AppID without appengine.Context and this always - * based on a http.Request. - */ - return "http://.appspot.com" - } -} - -func init() { - u := UserService{} - u.Register() - - // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API - // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. - // Open .appspot.com/apidocs and enter http://.appspot.com/apidocs.json in the api input field. - config := swagger.Config{ - WebServices: restful.RegisteredWebServices(), // you control what services are visible - WebServicesUrl: getGaeURL(), - ApiPath: "/apidocs.json", - - // Optionally, specifiy where the UI is located - SwaggerPath: "/apidocs/", - // GAE support static content which is configured in your app.yaml. - // This example expect the swagger-ui in static/swagger so you should place it there :) - SwaggerFilePath: "static/swagger"} - swagger.InstallSwaggerService(config) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/home.html b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/home.html deleted file mode 100644 index e5d49b42c..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/home.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - -

{{.Text}}

- - \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-CORS-filter.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-CORS-filter.go deleted file mode 100644 index 346aa1b37..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-CORS-filter.go +++ /dev/null @@ -1,67 +0,0 @@ -package main - -import ( - "io" - "log" - "net/http" - - "github.com/emicklei/go-restful" -) - -// Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page -// to make XMLHttpRequests to another domain, not the domain the JavaScript originated from. -// -// http://en.wikipedia.org/wiki/Cross-origin_resource_sharing -// http://enable-cors.org/server.html -// -// GET http://localhost:8080/users -// -// GET http://localhost:8080/users/1 -// -// PUT http://localhost:8080/users/1 -// -// DELETE http://localhost:8080/users/1 -// -// OPTIONS http://localhost:8080/users/1 with Header "Origin" set to some domain and - -type UserResource struct{} - -func (u UserResource) RegisterTo(container *restful.Container) { - ws := new(restful.WebService) - ws. - Path("/users"). - Consumes("*/*"). - Produces("*/*") - - ws.Route(ws.GET("/{user-id}").To(u.nop)) - ws.Route(ws.POST("").To(u.nop)) - ws.Route(ws.PUT("/{user-id}").To(u.nop)) - ws.Route(ws.DELETE("/{user-id}").To(u.nop)) - - container.Add(ws) -} - -func (u UserResource) nop(request *restful.Request, response *restful.Response) { - io.WriteString(response.ResponseWriter, "this would be a normal response") -} - -func main() { - wsContainer := restful.NewContainer() - u := UserResource{} - u.RegisterTo(wsContainer) - - // Add container filter to enable CORS - cors := restful.CrossOriginResourceSharing{ - ExposeHeaders: []string{"X-My-Header"}, - AllowedHeaders: []string{"Content-Type", "Accept"}, - CookiesAllowed: false, - Container: wsContainer} - wsContainer.Filter(cors.Filter) - - // Add container filter to respond to OPTIONS - wsContainer.Filter(wsContainer.OPTIONSFilter) - - log.Printf("start listening on localhost:8080") - server := &http.Server{Addr: ":8080", Handler: wsContainer} - log.Fatal(server.ListenAndServe()) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go deleted file mode 100644 index 0cda50d34..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "io" - "log" - "net/http" - "os" - "strings" - "time" -) - -// This example shows how to create a filter that produces log lines -// according to the Common Log Format, also known as the NCSA standard. -// -// kindly contributed by leehambley -// -// GET http://localhost:8080/ping - -var logger *log.Logger = log.New(os.Stdout, "", 0) - -func NCSACommonLogFormatLogger() restful.FilterFunction { - return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - var username = "-" - if req.Request.URL.User != nil { - if name := req.Request.URL.User.Username(); name != "" { - username = name - } - } - chain.ProcessFilter(req, resp) - logger.Printf("%s - %s [%s] \"%s %s %s\" %d %d", - strings.Split(req.Request.RemoteAddr, ":")[0], - username, - time.Now().Format("02/Jan/2006:15:04:05 -0700"), - req.Request.Method, - req.Request.URL.RequestURI(), - req.Request.Proto, - resp.StatusCode(), - resp.ContentLength(), - ) - } -} - -func main() { - ws := new(restful.WebService) - ws.Filter(NCSACommonLogFormatLogger()) - ws.Route(ws.GET("/ping").To(hello)) - restful.Add(ws) - http.ListenAndServe(":8080", nil) -} - -func hello(req *restful.Request, resp *restful.Response) { - io.WriteString(resp, "pong") -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-basic-authentication.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-basic-authentication.go deleted file mode 100644 index 5dd3067e9..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-basic-authentication.go +++ /dev/null @@ -1,35 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "io" - "net/http" -) - -// This example shows how to create a (Route) Filter that performs Basic Authentication on the Http request. -// -// GET http://localhost:8080/secret -// and use admin,admin for the credentials - -func main() { - ws := new(restful.WebService) - ws.Route(ws.GET("/secret").Filter(basicAuthenticate).To(secret)) - restful.Add(ws) - http.ListenAndServe(":8080", nil) -} - -func basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - encoded := req.Request.Header.Get("Authorization") - // usr/pwd = admin/admin - // real code does some decoding - if len(encoded) == 0 || "Basic YWRtaW46YWRtaW4=" != encoded { - resp.AddHeader("WWW-Authenticate", "Basic realm=Protected Area") - resp.WriteErrorString(401, "401: Not Authorized") - return - } - chain.ProcessFilter(req, resp) -} - -func secret(req *restful.Request, resp *restful.Response) { - io.WriteString(resp, "42") -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go deleted file mode 100644 index 9148213cf..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go +++ /dev/null @@ -1,65 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "io" - "log" - "os" - "runtime/pprof" -) - -// ProfilingService is a WebService that can start/stop a CPU profile and write results to a file -// GET /{rootPath}/start will activate CPU profiling -// GET /{rootPath}/stop will stop profiling -// -// NewProfileService("/profiler", "ace.prof").AddWebServiceTo(restful.DefaultContainer) -// -type ProfilingService struct { - rootPath string // the base (root) of the service, e.g. /profiler - cpuprofile string // the output filename to write profile results, e.g. myservice.prof - cpufile *os.File // if not nil, then profiling is active -} - -func NewProfileService(rootPath string, outputFilename string) *ProfilingService { - ps := new(ProfilingService) - ps.rootPath = rootPath - ps.cpuprofile = outputFilename - return ps -} - -// Add this ProfileService to a restful Container -func (p ProfilingService) AddWebServiceTo(container *restful.Container) { - ws := new(restful.WebService) - ws.Path(p.rootPath).Consumes("*/*").Produces(restful.MIME_JSON) - ws.Route(ws.GET("/start").To(p.startProfiler)) - ws.Route(ws.GET("/stop").To(p.stopProfiler)) - container.Add(ws) -} - -func (p *ProfilingService) startProfiler(req *restful.Request, resp *restful.Response) { - if p.cpufile != nil { - io.WriteString(resp.ResponseWriter, "[restful] CPU profiling already running") - return // error? - } - cpufile, err := os.Create(p.cpuprofile) - if err != nil { - log.Fatal(err) - } - // remember for close - p.cpufile = cpufile - pprof.StartCPUProfile(cpufile) - io.WriteString(resp.ResponseWriter, "[restful] CPU profiling started, writing on:"+p.cpuprofile) -} - -func (p *ProfilingService) stopProfiler(req *restful.Request, resp *restful.Response) { - if p.cpufile == nil { - io.WriteString(resp.ResponseWriter, "[restful] CPU profiling not active") - return // error? - } - pprof.StopCPUProfile() - p.cpufile.Close() - p.cpufile = nil - io.WriteString(resp.ResponseWriter, "[restful] CPU profiling stopped, closing:"+p.cpuprofile) -} - -func main() {} // exists for example compilation only diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-curly-router.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-curly-router.go deleted file mode 100644 index 1b95dd02b..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-curly-router.go +++ /dev/null @@ -1,107 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "log" - "net/http" -) - -// This example has the same service definition as restful-user-resource -// but uses a different router (CurlyRouter) that does not use regular expressions -// -// POST http://localhost:8080/users -// 1Melissa Raspberry -// -// GET http://localhost:8080/users/1 -// -// PUT http://localhost:8080/users/1 -// 1Melissa -// -// DELETE http://localhost:8080/users/1 -// - -type User struct { - Id, Name string -} - -type UserResource struct { - // normally one would use DAO (data access object) - users map[string]User -} - -func (u UserResource) Register(container *restful.Container) { - ws := new(restful.WebService) - ws. - Path("/users"). - Consumes(restful.MIME_XML, restful.MIME_JSON). - Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well - - ws.Route(ws.GET("/{user-id}").To(u.findUser)) - ws.Route(ws.POST("").To(u.updateUser)) - ws.Route(ws.PUT("/{user-id}").To(u.createUser)) - ws.Route(ws.DELETE("/{user-id}").To(u.removeUser)) - - container.Add(ws) -} - -// GET http://localhost:8080/users/1 -// -func (u UserResource) findUser(request *restful.Request, response *restful.Response) { - id := request.PathParameter("user-id") - usr := u.users[id] - if len(usr.Id) == 0 { - response.AddHeader("Content-Type", "text/plain") - response.WriteErrorString(http.StatusNotFound, "User could not be found.") - } else { - response.WriteEntity(usr) - } -} - -// POST http://localhost:8080/users -// 1Melissa Raspberry -// -func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { - usr := new(User) - err := request.ReadEntity(&usr) - if err == nil { - u.users[usr.Id] = *usr - response.WriteEntity(usr) - } else { - response.AddHeader("Content-Type", "text/plain") - response.WriteErrorString(http.StatusInternalServerError, err.Error()) - } -} - -// PUT http://localhost:8080/users/1 -// 1Melissa -// -func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { - usr := User{Id: request.PathParameter("user-id")} - err := request.ReadEntity(&usr) - if err == nil { - u.users[usr.Id] = usr - response.WriteHeader(http.StatusCreated) - response.WriteEntity(usr) - } else { - response.AddHeader("Content-Type", "text/plain") - response.WriteErrorString(http.StatusInternalServerError, err.Error()) - } -} - -// DELETE http://localhost:8080/users/1 -// -func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { - id := request.PathParameter("user-id") - delete(u.users, id) -} - -func main() { - wsContainer := restful.NewContainer() - wsContainer.Router(restful.CurlyRouter{}) - u := UserResource{map[string]User{}} - u.Register(wsContainer) - - log.Printf("start listening on localhost:8080") - server := &http.Server{Addr: ":8080", Handler: wsContainer} - log.Fatal(server.ListenAndServe()) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-encoding-filter.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-encoding-filter.go deleted file mode 100644 index 6094c4909..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-encoding-filter.go +++ /dev/null @@ -1,61 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "log" - "net/http" -) - -type User struct { - Id, Name string -} - -type UserList struct { - Users []User -} - -// -// This example shows how to use the CompressingResponseWriter by a Filter -// such that encoding can be enabled per WebService or per Route (instead of per container) -// Using restful.DefaultContainer.EnableContentEncoding(true) will encode all responses served by WebServices in the DefaultContainer. -// -// Set Accept-Encoding to gzip or deflate -// GET http://localhost:8080/users/42 -// and look at the response headers - -func main() { - restful.Add(NewUserService()) - log.Printf("start listening on localhost:8080") - log.Fatal(http.ListenAndServe(":8080", nil)) -} - -func NewUserService() *restful.WebService { - ws := new(restful.WebService) - ws. - Path("/users"). - Consumes(restful.MIME_XML, restful.MIME_JSON). - Produces(restful.MIME_JSON, restful.MIME_XML) - - // install a response encoding filter - ws.Route(ws.GET("/{user-id}").Filter(encodingFilter).To(findUser)) - return ws -} - -// Route Filter (defines FilterFunction) -func encodingFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - log.Printf("[encoding-filter] %s,%s\n", req.Request.Method, req.Request.URL) - // wrap responseWriter into a compressing one - compress, _ := restful.NewCompressingResponseWriter(resp.ResponseWriter, restful.ENCODING_GZIP) - resp.ResponseWriter = compress - defer func() { - compress.Close() - }() - chain.ProcessFilter(req, resp) -} - -// GET http://localhost:8080/users/42 -// -func findUser(request *restful.Request, response *restful.Response) { - log.Printf("findUser") - response.WriteEntity(User{"42", "Gandalf"}) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-filters.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-filters.go deleted file mode 100644 index 47e1146a0..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-filters.go +++ /dev/null @@ -1,114 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "log" - "net/http" - "time" -) - -type User struct { - Id, Name string -} - -type UserList struct { - Users []User -} - -// This example show how to create and use the three different Filters (Container,WebService and Route) -// When applied to the restful.DefaultContainer, we refer to them as a global filter. -// -// GET http://locahost:8080/users/42 -// and see the logging per filter (try repeating this request) - -func main() { - // install a global (=DefaultContainer) filter (processed before any webservice in the DefaultContainer) - restful.Filter(globalLogging) - - restful.Add(NewUserService()) - log.Printf("start listening on localhost:8080") - log.Fatal(http.ListenAndServe(":8080", nil)) -} - -func NewUserService() *restful.WebService { - ws := new(restful.WebService) - ws. - Path("/users"). - Consumes(restful.MIME_XML, restful.MIME_JSON). - Produces(restful.MIME_JSON, restful.MIME_XML) - - // install a webservice filter (processed before any route) - ws.Filter(webserviceLogging).Filter(measureTime) - - // install a counter filter - ws.Route(ws.GET("").Filter(NewCountFilter().routeCounter).To(getAllUsers)) - - // install 2 chained route filters (processed before calling findUser) - ws.Route(ws.GET("/{user-id}").Filter(routeLogging).Filter(NewCountFilter().routeCounter).To(findUser)) - return ws -} - -// Global Filter -func globalLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - log.Printf("[global-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) - chain.ProcessFilter(req, resp) -} - -// WebService Filter -func webserviceLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - log.Printf("[webservice-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) - chain.ProcessFilter(req, resp) -} - -// WebService (post-process) Filter (as a struct that defines a FilterFunction) -func measureTime(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - now := time.Now() - chain.ProcessFilter(req, resp) - log.Printf("[webservice-filter (timer)] %v\n", time.Now().Sub(now)) -} - -// Route Filter (defines FilterFunction) -func routeLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - log.Printf("[route-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) - chain.ProcessFilter(req, resp) -} - -// Route Filter (as a struct that defines a FilterFunction) -// CountFilter implements a FilterFunction for counting requests. -type CountFilter struct { - count int - counter chan int // for go-routine safe count increments -} - -// NewCountFilter creates and initializes a new CountFilter. -func NewCountFilter() *CountFilter { - c := new(CountFilter) - c.counter = make(chan int) - go func() { - for { - c.count += <-c.counter - } - }() - return c -} - -// routeCounter increments the count of the filter (through a channel) -func (c *CountFilter) routeCounter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - c.counter <- 1 - log.Printf("[route-filter (counter)] count:%d", c.count) - chain.ProcessFilter(req, resp) -} - -// GET http://localhost:8080/users -// -func getAllUsers(request *restful.Request, response *restful.Response) { - log.Printf("getAllUsers") - response.WriteEntity(UserList{[]User{User{"42", "Gandalf"}, User{"3.14", "Pi"}}}) -} - -// GET http://localhost:8080/users/42 -// -func findUser(request *restful.Request, response *restful.Response) { - log.Printf("findUser") - response.WriteEntity(User{"42", "Gandalf"}) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-form-handling.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-form-handling.go deleted file mode 100644 index a83db4492..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-form-handling.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import ( - "fmt" - "github.com/emicklei/go-restful" - "github.com/gorilla/schema" - "io" - "net/http" -) - -// This example shows how to handle a POST of a HTML form that uses the standard x-www-form-urlencoded content-type. -// It uses the gorilla web tool kit schema package to decode the form data into a struct. -// -// GET http://localhost:8080/profiles -// - -type Profile struct { - Name string - Age int -} - -var decoder *schema.Decoder - -func main() { - decoder = schema.NewDecoder() - ws := new(restful.WebService) - ws.Route(ws.POST("/profiles").Consumes("application/x-www-form-urlencoded").To(postAdddress)) - ws.Route(ws.GET("/profiles").To(addresssForm)) - restful.Add(ws) - http.ListenAndServe(":8080", nil) -} - -func postAdddress(req *restful.Request, resp *restful.Response) { - err := req.Request.ParseForm() - if err != nil { - resp.WriteErrorString(http.StatusBadRequest, err.Error()) - return - } - p := new(Profile) - err = decoder.Decode(p, req.Request.PostForm) - if err != nil { - resp.WriteErrorString(http.StatusBadRequest, err.Error()) - return - } - io.WriteString(resp.ResponseWriter, fmt.Sprintf("Name=%s, Age=%d", p.Name, p.Age)) -} - -func addresssForm(req *restful.Request, resp *restful.Response) { - io.WriteString(resp.ResponseWriter, - ` - -

Enter Profile

-
- - - - - -
- - `) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-hello-world.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-hello-world.go deleted file mode 100644 index a21c2a69c..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-hello-world.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "io" - "net/http" -) - -// This example shows the minimal code needed to get a restful.WebService working. -// -// GET http://localhost:8080/hello - -func main() { - ws := new(restful.WebService) - ws.Route(ws.GET("/hello").To(hello)) - restful.Add(ws) - http.ListenAndServe(":8080", nil) -} - -func hello(req *restful.Request, resp *restful.Response) { - io.WriteString(resp, "world") -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-html-template.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-html-template.go deleted file mode 100644 index de51c5919..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-html-template.go +++ /dev/null @@ -1,35 +0,0 @@ -package main - -import ( - "log" - "net/http" - "text/template" - - "github.com/emicklei/go-restful" -) - -// This example shows how to serve a HTML page using the standard Go template engine. -// -// GET http://localhost:8080/ - -func main() { - ws := new(restful.WebService) - ws.Route(ws.GET("/").To(home)) - restful.Add(ws) - print("open browser on http://localhost:8080/\n") - http.ListenAndServe(":8080", nil) -} - -type Message struct { - Text string -} - -func home(req *restful.Request, resp *restful.Response) { - p := &Message{"restful-html-template demo"} - // you might want to cache compiled templates - t, err := template.ParseFiles("home.html") - if err != nil { - log.Fatalf("Template gave: %s", err) - } - t.Execute(resp.ResponseWriter, p) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-multi-containers.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-multi-containers.go deleted file mode 100644 index 3f1650b36..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-multi-containers.go +++ /dev/null @@ -1,43 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "io" - "log" - "net/http" -) - -// This example shows how to have a program with 2 WebServices containers -// each having a http server listening on its own port. -// -// The first "hello" is added to the restful.DefaultContainer (and uses DefaultServeMux) -// For the second "hello", a new container and ServeMux is created -// and requires a new http.Server with the container being the Handler. -// This first server is spawn in its own go-routine such that the program proceeds to create the second. -// -// GET http://localhost:8080/hello -// GET http://localhost:8081/hello - -func main() { - ws := new(restful.WebService) - ws.Route(ws.GET("/hello").To(hello)) - restful.Add(ws) - go func() { - http.ListenAndServe(":8080", nil) - }() - - container2 := restful.NewContainer() - ws2 := new(restful.WebService) - ws2.Route(ws2.GET("/hello").To(hello2)) - container2.Add(ws2) - server := &http.Server{Addr: ":8081", Handler: container2} - log.Fatal(server.ListenAndServe()) -} - -func hello(req *restful.Request, resp *restful.Response) { - io.WriteString(resp, "default world") -} - -func hello2(req *restful.Request, resp *restful.Response) { - io.WriteString(resp, "second world") -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-options-filter.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-options-filter.go deleted file mode 100644 index 73dc3cfe5..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-options-filter.go +++ /dev/null @@ -1,51 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "io" - "log" - "net/http" -) - -// This example shows how to use the OPTIONSFilter on a Container -// -// OPTIONS http://localhost:8080/users -// -// OPTIONS http://localhost:8080/users/1 - -type UserResource struct{} - -func (u UserResource) RegisterTo(container *restful.Container) { - ws := new(restful.WebService) - ws. - Path("/users"). - Consumes("*/*"). - Produces("*/*") - - ws.Route(ws.GET("/{user-id}").To(u.nop)) - ws.Route(ws.POST("").To(u.nop)) - ws.Route(ws.PUT("/{user-id}").To(u.nop)) - ws.Route(ws.DELETE("/{user-id}").To(u.nop)) - - container.Add(ws) -} - -func (u UserResource) nop(request *restful.Request, response *restful.Response) { - io.WriteString(response.ResponseWriter, "this would be a normal response") -} - -func main() { - wsContainer := restful.NewContainer() - u := UserResource{} - u.RegisterTo(wsContainer) - - // Add container filter to respond to OPTIONS - wsContainer.Filter(wsContainer.OPTIONSFilter) - - // For use on the default container, you can write - // restful.Filter(restful.OPTIONSFilter()) - - log.Printf("start listening on localhost:8080") - server := &http.Server{Addr: ":8080", Handler: wsContainer} - log.Fatal(server.ListenAndServe()) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-path-tail.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-path-tail.go deleted file mode 100644 index 8488a232c..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-path-tail.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "io" - "net/http" - . "github.com/emicklei/go-restful" -) - -// This example shows how to a Route that matches the "tail" of a path. -// Requires the use of a CurlyRouter and the star "*" path parameter pattern. -// -// GET http://localhost:8080/basepath/some/other/location/test.xml - -func main() { - DefaultContainer.Router(CurlyRouter{}) - ws := new(WebService) - ws.Route(ws.GET("/basepath/{resource:*}").To(staticFromPathParam)) - Add(ws) - - println("[go-restful] serve path tails from http://localhost:8080/basepath") - http.ListenAndServe(":8080", nil) -} - -func staticFromPathParam(req *Request, resp *Response) { - io.WriteString(resp, "Tail="+req.PathParameter("resource")) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go deleted file mode 100644 index 0b55f1493..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go +++ /dev/null @@ -1,98 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "io" - "log" - "net/http" -) - -// This example shows how the different types of filters are called in the request-response flow. -// The call chain is logged on the console when sending an http request. -// -// GET http://localhost:8080/1 -// GET http://localhost:8080/2 - -var indentLevel int - -func container_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - log.Printf("url path:%v\n", req.Request.URL) - trace("container_filter_A: before", 1) - chain.ProcessFilter(req, resp) - trace("container_filter_A: after", -1) -} - -func container_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - trace("container_filter_B: before", 1) - chain.ProcessFilter(req, resp) - trace("container_filter_B: after", -1) -} - -func service_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - trace("service_filter_A: before", 1) - chain.ProcessFilter(req, resp) - trace("service_filter_A: after", -1) -} - -func service_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - trace("service_filter_B: before", 1) - chain.ProcessFilter(req, resp) - trace("service_filter_B: after", -1) -} - -func route_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - trace("route_filter_A: before", 1) - chain.ProcessFilter(req, resp) - trace("route_filter_A: after", -1) -} - -func route_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { - trace("route_filter_B: before", 1) - chain.ProcessFilter(req, resp) - trace("route_filter_B: after", -1) -} - -func trace(what string, delta int) { - indented := what - if delta < 0 { - indentLevel += delta - } - for t := 0; t < indentLevel; t++ { - indented = "." + indented - } - log.Printf("%s", indented) - if delta > 0 { - indentLevel += delta - } -} - -func main() { - restful.Filter(container_filter_A) - restful.Filter(container_filter_B) - - ws1 := new(restful.WebService) - ws1.Path("/1") - ws1.Filter(service_filter_A) - ws1.Filter(service_filter_B) - ws1.Route(ws1.GET("").To(doit1).Filter(route_filter_A).Filter(route_filter_B)) - - ws2 := new(restful.WebService) - ws2.Path("/2") - ws2.Filter(service_filter_A) - ws2.Filter(service_filter_B) - ws2.Route(ws2.GET("").To(doit2).Filter(route_filter_A).Filter(route_filter_B)) - - restful.Add(ws1) - restful.Add(ws2) - - log.Print("go-restful example listing on http://localhost:8080/1 and http://localhost:8080/2") - log.Fatal(http.ListenAndServe(":8080", nil)) -} - -func doit1(req *restful.Request, resp *restful.Response) { - io.WriteString(resp, "nothing to see in 1") -} - -func doit2(req *restful.Request, resp *restful.Response) { - io.WriteString(resp, "nothing to see in 2") -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-resource-functions.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-resource-functions.go deleted file mode 100644 index fb1012a02..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-resource-functions.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "github.com/emicklei/go-restful" - "log" - "net/http" -) - -// This example shows how to use methods as RouteFunctions for WebServices. -// The ProductResource has a Register() method that creates and initializes -// a WebService to expose its methods as REST operations. -// The WebService is added to the restful.DefaultContainer. -// A ProductResource is typically created using some data access object. -// -// GET http://localhost:8080/products/1 -// POST http://localhost:8080/products -// 1The First - -type Product struct { - Id, Title string -} - -type ProductResource struct { - // typically reference a DAO (data-access-object) -} - -func (p ProductResource) getOne(req *restful.Request, resp *restful.Response) { - id := req.PathParameter("id") - log.Println("getting product with id:" + id) - resp.WriteEntity(Product{Id: id, Title: "test"}) -} - -func (p ProductResource) postOne(req *restful.Request, resp *restful.Response) { - updatedProduct := new(Product) - err := req.ReadEntity(updatedProduct) - if err != nil { // bad request - resp.WriteErrorString(http.StatusBadRequest, err.Error()) - return - } - log.Println("updating product with id:" + updatedProduct.Id) -} - -func (p ProductResource) Register() { - ws := new(restful.WebService) - ws.Path("/products") - ws.Consumes(restful.MIME_XML) - ws.Produces(restful.MIME_XML) - - ws.Route(ws.GET("/{id}").To(p.getOne). - Doc("get the product by its id"). - Param(ws.PathParameter("id", "identifier of the product").DataType("string"))) - - ws.Route(ws.POST("").To(p.postOne). - Doc("update or create a product"). - Param(ws.BodyParameter("Product", "a Product (XML)").DataType("main.Product"))) - - restful.Add(ws) -} - -func main() { - ProductResource{}.Register() - http.ListenAndServe(":8080", nil) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-route_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-route_test.go deleted file mode 100644 index 20c366bf9..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-route_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/emicklei/go-restful" -) - -var ( - Result string -) - -func TestRouteExtractParameter(t *testing.T) { - // setup service - ws := new(restful.WebService) - ws.Consumes(restful.MIME_XML) - ws.Route(ws.GET("/test/{param}").To(DummyHandler)) - restful.Add(ws) - - // setup request + writer - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test/THIS", bodyReader) - httpRequest.Header.Set("Content-Type", restful.MIME_XML) - httpWriter := httptest.NewRecorder() - - // run - restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest) - - if Result != "THIS" { - t.Fatalf("Result is actually: %s", Result) - } -} - -func DummyHandler(rq *restful.Request, rp *restful.Response) { - Result = rq.PathParameter("param") -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-routefunction_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-routefunction_test.go deleted file mode 100644 index 957c05550..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-routefunction_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/emicklei/go-restful" -) - -// This example show how to test one particular RouteFunction (getIt) -// It uses the httptest.ResponseRecorder to capture output - -func getIt(req *restful.Request, resp *restful.Response) { - resp.WriteHeader(204) -} - -func TestCallFunction(t *testing.T) { - httpReq, _ := http.NewRequest("GET", "/", nil) - req := restful.NewRequest(httpReq) - - recorder := new(httptest.ResponseRecorder) - resp := restful.NewResponse(recorder) - - getIt(req, resp) - if recorder.Code != 204 { - t.Fatalf("Missing or wrong status code:%d", recorder.Code) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-serve-static.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-serve-static.go deleted file mode 100644 index 8cb7848c1..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-serve-static.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "path" - - "github.com/emicklei/go-restful" -) - -// This example shows how to define methods that serve static files -// It uses the standard http.ServeFile method -// -// GET http://localhost:8080/static/test.xml -// GET http://localhost:8080/static/ -// -// GET http://localhost:8080/static?resource=subdir/test.xml - -var rootdir = "/tmp" - -func main() { - restful.DefaultContainer.Router(restful.CurlyRouter{}) - - ws := new(restful.WebService) - ws.Route(ws.GET("/static/{subpath:*}").To(staticFromPathParam)) - ws.Route(ws.GET("/static").To(staticFromQueryParam)) - restful.Add(ws) - - println("[go-restful] serving files on http://localhost:8080/static from local /tmp") - http.ListenAndServe(":8080", nil) -} - -func staticFromPathParam(req *restful.Request, resp *restful.Response) { - actual := path.Join(rootdir, req.PathParameter("subpath")) - fmt.Printf("serving %s ... (from %s)\n", actual, req.PathParameter("subpath")) - http.ServeFile( - resp.ResponseWriter, - req.Request, - actual) -} - -func staticFromQueryParam(req *restful.Request, resp *restful.Response) { - http.ServeFile( - resp.ResponseWriter, - req.Request, - path.Join(rootdir, req.QueryParameter("resource"))) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-swagger.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-swagger.go deleted file mode 100644 index 7746b5b07..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-swagger.go +++ /dev/null @@ -1,61 +0,0 @@ -package main - -import ( - "log" - "net/http" - - "github.com/emicklei/go-restful" - "github.com/emicklei/go-restful/swagger" -) - -type Book struct { - Title string - Author string -} - -func main() { - ws := new(restful.WebService) - ws.Path("/books") - ws.Consumes(restful.MIME_JSON, restful.MIME_XML) - ws.Produces(restful.MIME_JSON, restful.MIME_XML) - restful.Add(ws) - - ws.Route(ws.GET("/{medium}").To(noop). - Doc("Search all books"). - Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). - Param(ws.QueryParameter("language", "en,nl,de").DataType("string")). - Param(ws.HeaderParameter("If-Modified-Since", "last known timestamp").DataType("datetime")). - Do(returns200, returns500)) - - ws.Route(ws.PUT("/{medium}").To(noop). - Doc("Add a new book"). - Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). - Reads(Book{})) - - // You can install the Swagger Service which provides a nice Web UI on your REST API - // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. - // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. - config := swagger.Config{ - WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible - WebServicesUrl: "http://localhost:8080", - ApiPath: "/apidocs.json", - - // Optionally, specifiy where the UI is located - SwaggerPath: "/apidocs/", - SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"} - swagger.RegisterSwaggerService(config, restful.DefaultContainer) - - log.Printf("start listening on localhost:8080") - server := &http.Server{Addr: ":8080", Handler: restful.DefaultContainer} - log.Fatal(server.ListenAndServe()) -} - -func noop(req *restful.Request, resp *restful.Response) {} - -func returns200(b *restful.RouteBuilder) { - b.Returns(http.StatusOK, "OK", Book{}) -} - -func returns500(b *restful.RouteBuilder) { - b.Returns(http.StatusInternalServerError, "Bummer, something went wrong", nil) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-user-resource.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-user-resource.go deleted file mode 100644 index 6b860dc20..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-user-resource.go +++ /dev/null @@ -1,152 +0,0 @@ -package main - -import ( - "log" - "net/http" - "strconv" - - "github.com/emicklei/go-restful" - "github.com/emicklei/go-restful/swagger" -) - -// This example show a complete (GET,PUT,POST,DELETE) conventional example of -// a REST Resource including documentation to be served by e.g. a Swagger UI -// It is recommended to create a Resource struct (UserResource) that can encapsulate -// an object that provide domain access (a DAO) -// It has a Register method including the complete Route mapping to methods together -// with all the appropriate documentation -// -// POST http://localhost:8080/users -// 1Melissa Raspberry -// -// GET http://localhost:8080/users/1 -// -// PUT http://localhost:8080/users/1 -// 1Melissa -// -// DELETE http://localhost:8080/users/1 -// - -type User struct { - Id, Name string -} - -type UserResource struct { - // normally one would use DAO (data access object) - users map[string]User -} - -func (u UserResource) Register(container *restful.Container) { - ws := new(restful.WebService) - ws. - Path("/users"). - Doc("Manage Users"). - Consumes(restful.MIME_XML, restful.MIME_JSON). - Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well - - ws.Route(ws.GET("/{user-id}").To(u.findUser). - // docs - Doc("get a user"). - Operation("findUser"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). - Writes(User{})) // on the response - - ws.Route(ws.PUT("/{user-id}").To(u.updateUser). - // docs - Doc("update a user"). - Operation("updateUser"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). - ReturnsError(409, "duplicate user-id", nil). - Reads(User{})) // from the request - - ws.Route(ws.POST("").To(u.createUser). - // docs - Doc("create a user"). - Operation("createUser"). - Reads(User{})) // from the request - - ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). - // docs - Doc("delete a user"). - Operation("removeUser"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) - - container.Add(ws) -} - -// GET http://localhost:8080/users/1 -// -func (u UserResource) findUser(request *restful.Request, response *restful.Response) { - id := request.PathParameter("user-id") - usr := u.users[id] - if len(usr.Id) == 0 { - response.AddHeader("Content-Type", "text/plain") - response.WriteErrorString(http.StatusNotFound, "404: User could not be found.") - return - } - response.WriteEntity(usr) -} - -// POST http://localhost:8080/users -// Melissa -// -func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { - usr := new(User) - err := request.ReadEntity(usr) - if err != nil { - response.AddHeader("Content-Type", "text/plain") - response.WriteErrorString(http.StatusInternalServerError, err.Error()) - return - } - usr.Id = strconv.Itoa(len(u.users) + 1) // simple id generation - u.users[usr.Id] = *usr - response.WriteHeaderAndEntity(http.StatusCreated, usr) -} - -// PUT http://localhost:8080/users/1 -// 1Melissa Raspberry -// -func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { - usr := new(User) - err := request.ReadEntity(&usr) - if err != nil { - response.AddHeader("Content-Type", "text/plain") - response.WriteErrorString(http.StatusInternalServerError, err.Error()) - return - } - u.users[usr.Id] = *usr - response.WriteEntity(usr) -} - -// DELETE http://localhost:8080/users/1 -// -func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { - id := request.PathParameter("user-id") - delete(u.users, id) -} - -func main() { - // to see what happens in the package, uncomment the following - //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) - - wsContainer := restful.NewContainer() - u := UserResource{map[string]User{}} - u.Register(wsContainer) - - // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API - // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. - // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. - config := swagger.Config{ - WebServices: wsContainer.RegisteredWebServices(), // you control what services are visible - WebServicesUrl: "http://localhost:8080", - ApiPath: "/apidocs.json", - - // Optionally, specifiy where the UI is located - SwaggerPath: "/apidocs/", - SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"} - swagger.RegisterSwaggerService(config, wsContainer) - - log.Printf("start listening on localhost:8080") - server := &http.Server{Addr: ":8080", Handler: wsContainer} - log.Fatal(server.ListenAndServe()) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-user-service.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-user-service.go deleted file mode 100644 index 77c678ce4..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-user-service.go +++ /dev/null @@ -1,137 +0,0 @@ -package main - -import ( - "log" - "net/http" - - "github.com/emicklei/go-restful" - "github.com/emicklei/go-restful/swagger" -) - -// This example is functionally the same as the example in restful-user-resource.go -// with the only difference that is served using the restful.DefaultContainer - -type User struct { - Id, Name string -} - -type UserService struct { - // normally one would use DAO (data access object) - users map[string]User -} - -func (u UserService) Register() { - ws := new(restful.WebService) - ws. - Path("/users"). - Consumes(restful.MIME_XML, restful.MIME_JSON). - Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well - - ws.Route(ws.GET("/").To(u.findAllUsers). - // docs - Doc("get all users"). - Operation("findAllUsers"). - Returns(200, "OK", []User{})) - - ws.Route(ws.GET("/{user-id}").To(u.findUser). - // docs - Doc("get a user"). - Operation("findUser"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). - Writes(User{})) // on the response - - ws.Route(ws.PUT("/{user-id}").To(u.updateUser). - // docs - Doc("update a user"). - Operation("updateUser"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). - Reads(User{})) // from the request - - ws.Route(ws.PUT("").To(u.createUser). - // docs - Doc("create a user"). - Operation("createUser"). - Reads(User{})) // from the request - - ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). - // docs - Doc("delete a user"). - Operation("removeUser"). - Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) - - restful.Add(ws) -} - -// GET http://localhost:8080/users -// -func (u UserService) findAllUsers(request *restful.Request, response *restful.Response) { - response.WriteEntity(u.users) -} - -// GET http://localhost:8080/users/1 -// -func (u UserService) findUser(request *restful.Request, response *restful.Response) { - id := request.PathParameter("user-id") - usr := u.users[id] - if len(usr.Id) == 0 { - response.WriteErrorString(http.StatusNotFound, "User could not be found.") - } else { - response.WriteEntity(usr) - } -} - -// PUT http://localhost:8080/users/1 -// 1Melissa Raspberry -// -func (u *UserService) updateUser(request *restful.Request, response *restful.Response) { - usr := new(User) - err := request.ReadEntity(&usr) - if err == nil { - u.users[usr.Id] = *usr - response.WriteEntity(usr) - } else { - response.WriteError(http.StatusInternalServerError, err) - } -} - -// PUT http://localhost:8080/users/1 -// 1Melissa -// -func (u *UserService) createUser(request *restful.Request, response *restful.Response) { - usr := User{Id: request.PathParameter("user-id")} - err := request.ReadEntity(&usr) - if err == nil { - u.users[usr.Id] = usr - response.WriteHeaderAndEntity(http.StatusCreated, usr) - } else { - response.WriteError(http.StatusInternalServerError, err) - } -} - -// DELETE http://localhost:8080/users/1 -// -func (u *UserService) removeUser(request *restful.Request, response *restful.Response) { - id := request.PathParameter("user-id") - delete(u.users, id) -} - -func main() { - u := UserService{map[string]User{}} - u.Register() - - // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API - // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. - // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. - config := swagger.Config{ - WebServices: restful.RegisteredWebServices(), // you control what services are visible - WebServicesUrl: "http://localhost:8080", - ApiPath: "/apidocs.json", - - // Optionally, specifiy where the UI is located - SwaggerPath: "/apidocs/", - SwaggerFilePath: "/Users/emicklei/Projects/swagger-ui/dist"} - swagger.InstallSwaggerService(config) - - log.Printf("start listening on localhost:8080") - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/filter_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/filter_test.go deleted file mode 100644 index fadfb570f..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/filter_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package restful - -import ( - "io" - "net/http" - "net/http/httptest" - "testing" -) - -func setupServices(addGlobalFilter bool, addServiceFilter bool, addRouteFilter bool) { - if addGlobalFilter { - Filter(globalFilter) - } - Add(newTestService(addServiceFilter, addRouteFilter)) -} - -func tearDown() { - DefaultContainer.webServices = []*WebService{} - DefaultContainer.isRegisteredOnRoot = true // this allows for setupServices multiple times - DefaultContainer.containerFilters = []FilterFunction{} -} - -func newTestService(addServiceFilter bool, addRouteFilter bool) *WebService { - ws := new(WebService).Path("") - if addServiceFilter { - ws.Filter(serviceFilter) - } - rb := ws.GET("/foo").To(foo) - if addRouteFilter { - rb.Filter(routeFilter) - } - ws.Route(rb) - ws.Route(ws.GET("/bar").To(bar)) - return ws -} - -func foo(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "foo") -} - -func bar(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "bar") -} - -func fail(req *Request, resp *Response) { - http.Error(resp.ResponseWriter, "something failed", http.StatusInternalServerError) -} - -func globalFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "global-") - chain.ProcessFilter(req, resp) -} - -func serviceFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "service-") - chain.ProcessFilter(req, resp) -} - -func routeFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "route-") - chain.ProcessFilter(req, resp) -} - -func TestNoFilter(t *testing.T) { - tearDown() - setupServices(false, false, false) - actual := sendIt("http://example.com/foo") - if "foo" != actual { - t.Fatal("expected: foo but got:" + actual) - } -} - -func TestGlobalFilter(t *testing.T) { - tearDown() - setupServices(true, false, false) - actual := sendIt("http://example.com/foo") - if "global-foo" != actual { - t.Fatal("expected: global-foo but got:" + actual) - } -} - -func TestWebServiceFilter(t *testing.T) { - tearDown() - setupServices(true, true, false) - actual := sendIt("http://example.com/foo") - if "global-service-foo" != actual { - t.Fatal("expected: global-service-foo but got:" + actual) - } -} - -func TestRouteFilter(t *testing.T) { - tearDown() - setupServices(true, true, true) - actual := sendIt("http://example.com/foo") - if "global-service-route-foo" != actual { - t.Fatal("expected: global-service-route-foo but got:" + actual) - } -} - -func TestRouteFilterOnly(t *testing.T) { - tearDown() - setupServices(false, false, true) - actual := sendIt("http://example.com/foo") - if "route-foo" != actual { - t.Fatal("expected: route-foo but got:" + actual) - } -} - -func TestBar(t *testing.T) { - tearDown() - setupServices(false, true, false) - actual := sendIt("http://example.com/bar") - if "service-bar" != actual { - t.Fatal("expected: service-bar but got:" + actual) - } -} - -func TestAllFiltersBar(t *testing.T) { - tearDown() - setupServices(true, true, true) - actual := sendIt("http://example.com/bar") - if "global-service-bar" != actual { - t.Fatal("expected: global-service-bar but got:" + actual) - } -} - -func sendIt(address string) string { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - return httpWriter.Body.String() -} - -func sendItTo(address string, container *Container) string { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - container.dispatch(httpWriter, httpRequest) - return httpWriter.Body.String() -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/jsr311_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/jsr311_test.go deleted file mode 100644 index 3e79a6def..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/jsr311_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package restful - -import ( - "io" - "sort" - "testing" -) - -// -// Step 1 tests -// -var paths = []struct { - // url with path (1) is handled by service with root (2) and last capturing group has value final (3) - path, root, final string -}{ - {"/", "/", "/"}, - {"/p", "/p", ""}, - {"/p/x", "/p/{q}", ""}, - {"/q/x", "/q", "/x"}, - {"/p/x/", "/p/{q}", "/"}, - {"/p/x/y", "/p/{q}", "/y"}, - {"/q/x/y", "/q", "/x/y"}, - {"/z/q", "/{p}/q", ""}, - {"/a/b/c/q", "/", "/a/b/c/q"}, -} - -func TestDetectDispatcher(t *testing.T) { - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws6 := new(WebService).Path("/p/{q}/") - ws7 := new(WebService).Path("/{p}/q") - var dispatchers = []*WebService{ws1, ws2, ws3, ws4, ws5, ws6, ws7} - - wc := NewContainer() - for _, each := range dispatchers { - wc.Add(each) - } - - router := RouterJSR311{} - - ok := true - for i, fixture := range paths { - who, final, err := router.detectDispatcher(fixture.path, dispatchers) - if err != nil { - t.Logf("error in detection:%v", err) - ok = false - } - if who.RootPath() != fixture.root { - t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) - ok = false - } - if final != fixture.final { - t.Logf("[line:%v] Unexpected final, expected:%v, actual:%v", i, fixture.final, final) - ok = false - } - } - if !ok { - t.Fail() - } -} - -// -// Step 2 tests -// - -// go test -v -test.run TestISSUE_179 ...restful -func TestISSUE_179(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/v1/category/{param:*}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/v1/category/sub/sub") - t.Logf("%v", routes) -} - -// go test -v -test.run TestISSUE_30 ...restful -func TestISSUE_30(t *testing.T) { - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.GET("/{id}").To(dummy)) - ws1.Route(ws1.POST("/login").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/login") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/users/login" { - t.Error("first is", routes[0].Path) - t.Logf("routes:%v", routes) - } -} - -// go test -v -test.run TestISSUE_34 ...restful -func TestISSUE_34(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) - ws1.Route(ws1.GET("/network/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - t.Logf("routes:%v", routes) - } -} - -// go test -v -test.run TestISSUE_34_2 ...restful -func TestISSUE_34_2(t *testing.T) { - ws1 := new(WebService).Path("/") - // change the registration order - ws1.Route(ws1.GET("/network/{id}").To(dummy)) - ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// go test -v -test.run TestISSUE_137 ...restful -func TestISSUE_137(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/") - t.Log(routes) - if len(routes) > 0 { - t.Error("no route expected") - } -} - -func TestSelectRoutesSlash(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("").To(dummy)) - ws1.Route(ws1.GET("/").To(dummy)) - ws1.Route(ws1.GET("/u").To(dummy)) - ws1.Route(ws1.POST("/u").To(dummy)) - ws1.Route(ws1.POST("/u/v").To(dummy)) - ws1.Route(ws1.POST("/u/{w}").To(dummy)) - ws1.Route(ws1.POST("/u/{w}/z").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/u") - checkRoutesContains(routes, "/u", t) - checkRoutesContainsNo(routes, "/u/v", t) - checkRoutesContainsNo(routes, "/", t) - checkRoutesContainsNo(routes, "/u/{w}/z", t) -} -func TestSelectRoutesU(t *testing.T) { - ws1 := new(WebService).Path("/u") - ws1.Route(ws1.GET("").To(dummy)) - ws1.Route(ws1.GET("/").To(dummy)) - ws1.Route(ws1.GET("/v").To(dummy)) - ws1.Route(ws1.POST("/{w}").To(dummy)) - ws1.Route(ws1.POST("/{w}/z").To(dummy)) // so full path = /u/{w}/z - routes := RouterJSR311{}.selectRoutes(ws1, "/v") // test against /u/v - checkRoutesContains(routes, "/u/{w}", t) -} - -func TestSelectRoutesUsers1(t *testing.T) { - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.POST("").To(dummy)) - ws1.Route(ws1.POST("/").To(dummy)) - ws1.Route(ws1.PUT("/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/1") - checkRoutesContains(routes, "/users/{id}", t) -} -func checkRoutesContains(routes []Route, path string, t *testing.T) { - if !containsRoutePath(routes, path, t) { - for _, r := range routes { - t.Logf("route %v %v", r.Method, r.Path) - } - t.Fatalf("routes should include [%v]:", path) - } -} -func checkRoutesContainsNo(routes []Route, path string, t *testing.T) { - if containsRoutePath(routes, path, t) { - for _, r := range routes { - t.Logf("route %v %v", r.Method, r.Path) - } - t.Fatalf("routes should not include [%v]:", path) - } -} -func containsRoutePath(routes []Route, path string, t *testing.T) bool { - for _, each := range routes { - if each.Path == path { - return true - } - } - return false -} - -// go test -v -test.run TestSortableRouteCandidates ...restful -func TestSortableRouteCandidates(t *testing.T) { - fixture := &sortableRouteCandidates{} - r1 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 0} - r2 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 1} - r3 := routeCandidate{matchesCount: 0, literalCount: 1, nonDefaultCount: 1} - r4 := routeCandidate{matchesCount: 1, literalCount: 1, nonDefaultCount: 0} - r5 := routeCandidate{matchesCount: 1, literalCount: 0, nonDefaultCount: 0} - fixture.candidates = append(fixture.candidates, r5, r4, r3, r2, r1) - sort.Sort(sort.Reverse(fixture)) - first := fixture.candidates[0] - if first.matchesCount != 1 && first.literalCount != 1 && first.nonDefaultCount != 0 { - t.Fatal("expected r4") - } - last := fixture.candidates[len(fixture.candidates)-1] - if last.matchesCount != 0 && last.literalCount != 0 && last.nonDefaultCount != 0 { - t.Fatal("expected r1") - } -} - -func dummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "dummy") } diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/options_filter_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/options_filter_test.go deleted file mode 100644 index f0fceb834..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/options_filter_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestOptionsFilter ...restful -func TestOptionsFilter(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.GET("/candy/{kind}").To(dummy)) - ws.Route(ws.DELETE("/candy/{kind}").To(dummy)) - ws.Route(ws.POST("/candies").To(dummy)) - Add(ws) - Filter(OPTIONSFilter()) - - httpRequest, _ := http.NewRequest("OPTIONS", "http://here.io/candy/gum", nil) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_Allow) - if "GET,DELETE" != actual { - t.Fatal("expected: GET,DELETE but got:" + actual) - } - - httpRequest, _ = http.NewRequest("OPTIONS", "http://here.io/candies", nil) - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual = httpWriter.Header().Get(HEADER_Allow) - if "POST" != actual { - t.Fatal("expected: POST but got:" + actual) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/path_expression_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/path_expression_test.go deleted file mode 100644 index 334fcef73..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/path_expression_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package restful - -import "testing" - -var tempregexs = []struct { - template, regex string - literalCount, varCount int -}{ - {"", "^(/.*)?$", 0, 0}, - {"/a/{b}/c/", "^/a/([^/]+?)/c(/.*)?$", 2, 1}, - {"/{a}/{b}/{c-d-e}/", "^/([^/]+?)/([^/]+?)/([^/]+?)(/.*)?$", 0, 3}, - {"/{p}/abcde", "^/([^/]+?)/abcde(/.*)?$", 5, 1}, - {"/a/{b:*}", "^/a/(.*)(/.*)?$", 1, 1}, - {"/a/{b:[a-z]+}", "^/a/([a-z]+)(/.*)?$", 1, 1}, -} - -func TestTemplateToRegularExpression(t *testing.T) { - ok := true - for i, fixture := range tempregexs { - actual, lCount, vCount, _ := templateToRegularExpression(fixture.template) - if actual != fixture.regex { - t.Logf("regex mismatch, expected:%v , actual:%v, line:%v\n", fixture.regex, actual, i) // 11 = where the data starts - ok = false - } - if lCount != fixture.literalCount { - t.Logf("literal count mismatch, expected:%v , actual:%v, line:%v\n", fixture.literalCount, lCount, i) - ok = false - } - if vCount != fixture.varCount { - t.Logf("variable count mismatch, expected:%v , actual:%v, line:%v\n", fixture.varCount, vCount, i) - ok = false - } - } - if !ok { - t.Fatal("one or more expression did not match") - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/request_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/request_test.go deleted file mode 100644 index 72f078f92..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/request_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package restful - -import ( - "encoding/json" - "net/http" - "net/url" - "strconv" - "strings" - "testing" -) - -func TestQueryParameter(t *testing.T) { - hreq := http.Request{Method: "GET"} - hreq.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar") - rreq := Request{Request: &hreq} - if rreq.QueryParameter("q") != "foo" { - t.Errorf("q!=foo %#v", rreq) - } -} - -type Anything map[string]interface{} - -type Number struct { - ValueFloat float64 - ValueInt int64 -} - -type Sample struct { - Value string -} - -func TestReadEntityXmlCached(t *testing.T) { - SetCacheReadEntity(true) - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/xml") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } - if request.bodyContent == nil { - t.Fatal("no expected cached bytes found") - } -} - -func TestReadEntityXmlNonCached(t *testing.T) { - SetCacheReadEntity(false) - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/xml") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } - if request.bodyContent != nil { - t.Fatal("unexpected cached bytes found") - } -} - -func TestReadEntityJson(t *testing.T) { - bodyReader := strings.NewReader(`{"Value" : "42"}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } -} - -func TestReadEntityJsonCharset(t *testing.T) { - bodyReader := strings.NewReader(`{"Value" : "42"}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json; charset=UTF-8") - request := NewRequest(httpRequest) - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } -} - -func TestReadEntityJsonNumber(t *testing.T) { - SetCacheReadEntity(true) - bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - any := make(Anything) - request.ReadEntity(&any) - number, ok := any["Value"].(json.Number) - if !ok { - t.Fatal("read failed") - } - vint, err := number.Int64() - if err != nil { - t.Fatal("convert failed") - } - if vint != 4899710515899924123 { - t.Fatal("read failed") - } - vfloat, err := number.Float64() - if err != nil { - t.Fatal("convert failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestReadEntityJsonNumberNonCached(t *testing.T) { - SetCacheReadEntity(false) - bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - any := make(Anything) - request.ReadEntity(&any) - number, ok := any["Value"].(json.Number) - if !ok { - t.Fatal("read failed") - } - vint, err := number.Int64() - if err != nil { - t.Fatal("convert failed") - } - if vint != 4899710515899924123 { - t.Fatal("read failed") - } - vfloat, err := number.Float64() - if err != nil { - t.Fatal("convert failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestReadEntityJsonLong(t *testing.T) { - bodyReader := strings.NewReader(`{"ValueFloat" : 4899710515899924123, "ValueInt": 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - number := new(Number) - request.ReadEntity(&number) - if number.ValueInt != 4899710515899924123 { - t.Fatal("read failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(number.ValueFloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestBodyParameter(t *testing.T) { - bodyReader := strings.NewReader(`value1=42&value2=43`) - httpRequest, _ := http.NewRequest("POST", "/test?value1=44", bodyReader) // POST and PUT body parameters take precedence over URL query string - httpRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") - request := NewRequest(httpRequest) - v1, err := request.BodyParameter("value1") - if err != nil { - t.Error(err) - } - v2, err := request.BodyParameter("value2") - if err != nil { - t.Error(err) - } - if v1 != "42" || v2 != "43" { - t.Fatal("read failed") - } -} - -func TestReadEntityUnkown(t *testing.T) { - bodyReader := strings.NewReader("?") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/rubbish") - request := NewRequest(httpRequest) - sam := new(Sample) - err := request.ReadEntity(sam) - if err == nil { - t.Fatal("read should be in error") - } -} - -func TestSetAttribute(t *testing.T) { - bodyReader := strings.NewReader("?") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - request := NewRequest(httpRequest) - request.SetAttribute("go", "there") - there := request.Attribute("go") - if there != "there" { - t.Fatalf("missing request attribute:%v", there) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/response_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/response_test.go deleted file mode 100644 index c8354f8ae..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/response_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package restful - -import ( - "errors" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestWriteHeader(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteHeader(123) - if resp.StatusCode() != 123 { - t.Errorf("Unexpected status code:%d", resp.StatusCode()) - } -} - -func TestNoWriteHeader(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - if resp.StatusCode() != http.StatusOK { - t.Errorf("Unexpected status code:%d", resp.StatusCode()) - } -} - -type food struct { - Kind string -} - -// go test -v -test.run TestMeasureContentLengthXml ...restful -func TestMeasureContentLengthXml(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteAsXml(food{"apple"}) - if resp.ContentLength() != 76 { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthJson ...restful -func TestMeasureContentLengthJson(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteAsJson(food{"apple"}) - if resp.ContentLength() != 22 { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthJsonNotPretty ...restful -func TestMeasureContentLengthJsonNotPretty(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, false, nil} - resp.WriteAsJson(food{"apple"}) - if resp.ContentLength() != 17 { // 16+1 using the Encoder directly yields another /n - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthWriteErrorString ...restful -func TestMeasureContentLengthWriteErrorString(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteErrorString(404, "Invalid") - if resp.ContentLength() != len("Invalid") { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestStatusIsPassedToResponse ...restful -func TestStatusIsPassedToResponse(t *testing.T) { - for _, each := range []struct { - write, read int - }{ - {write: 204, read: 204}, - {write: 304, read: 304}, - {write: 200, read: 200}, - {write: 400, read: 400}, - } { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteHeader(each.write) - if got, want := httpWriter.Code, each.read; got != want { - t.Errorf("got %v want %v", got, want) - } - } -} - -// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue54 ...restful -func TestStatusCreatedAndContentTypeJson_Issue54(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - resp.WriteHeader(201) - resp.WriteAsJson(food{"Juicy"}) - if httpWriter.HeaderMap.Get("Content-Type") != "application/json" { - t.Errorf("Expected content type json but got:%d", httpWriter.HeaderMap.Get("Content-Type")) - } - if httpWriter.Code != 201 { - t.Errorf("Expected status 201 but got:%d", httpWriter.Code) - } -} - -type errorOnWriteRecorder struct { - *httptest.ResponseRecorder -} - -func (e errorOnWriteRecorder) Write(bytes []byte) (int, error) { - return 0, errors.New("fail") -} - -// go test -v -test.run TestLastWriteErrorCaught ...restful -func TestLastWriteErrorCaught(t *testing.T) { - httpWriter := errorOnWriteRecorder{httptest.NewRecorder()} - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - err := resp.WriteAsJson(food{"Juicy"}) - if err.Error() != "fail" { - t.Errorf("Unexpected error message:%v", err) - } -} - -// go test -v -test.run TestAcceptStarStar_Issue83 ...restful -func TestAcceptStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "application/bogus,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/json" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestAcceptSkipStarStar_Issue83 ...restful -func TestAcceptSkipStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, " application/xml ,*/* ; q=0.8", []string{"application/json", "application/xml"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/xml" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestAcceptXmlBeforeStarStar_Issue83 ...restful -func TestAcceptXmlBeforeStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/json" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestWriteHeaderNoContent_Issue124 ...restful -func TestWriteHeaderNoContent_Issue124(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "text/plain", []string{"text/plain"}, 0, 0, true, nil} - resp.WriteHeader(http.StatusNoContent) - if httpWriter.Code != http.StatusNoContent { - t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) - } -} - -// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue163 ...restful -func TestStatusCreatedAndContentTypeJson_Issue163(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - resp.WriteHeader(http.StatusNotModified) - if httpWriter.Code != http.StatusNotModified { - t.Errorf("Got %d want %d", httpWriter.Code, http.StatusNotModified) - } -} - -func TestWriteHeaderAndEntity_Issue235(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - var pong = struct { - Foo string `json:"foo"` - }{Foo: "123"} - resp.WriteHeaderAndEntity(404, pong) - if httpWriter.Code != http.StatusNotFound { - t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) - } - if got, want := httpWriter.Header().Get("Content-Type"), "application/json"; got != want { - t.Errorf("got %v want %v", got, want) - } - if !strings.HasPrefix(httpWriter.Body.String(), "{") { - t.Errorf("expected pong struct in json:%s", httpWriter.Body.String()) - } -} - -func TestWriteEntityNotAcceptable(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/bogus", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity("done") - if httpWriter.Code != http.StatusNotAcceptable { - t.Errorf("got %d want %d", httpWriter.Code, http.StatusNotAcceptable) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_builder_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/route_builder_test.go deleted file mode 100644 index 56dbe02e4..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_builder_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package restful - -import ( - "testing" -) - -func TestRouteBuilder_PathParameter(t *testing.T) { - p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} - p.AllowMultiple(true) - p.DataType("int") - p.Required(true) - values := map[string]string{"a": "b"} - p.AllowableValues(values) - p.bePath() - - b := new(RouteBuilder) - b.function = dummy - b.Param(p) - r := b.Build() - if !r.ParameterDocs[0].Data().AllowMultiple { - t.Error("AllowMultiple invalid") - } - if r.ParameterDocs[0].Data().DataType != "int" { - t.Error("dataType invalid") - } - if !r.ParameterDocs[0].Data().Required { - t.Error("required invalid") - } - if r.ParameterDocs[0].Data().Kind != PathParameterKind { - t.Error("kind invalid") - } - if r.ParameterDocs[0].Data().AllowableValues["a"] != "b" { - t.Error("allowableValues invalid") - } - if b.ParameterNamed("name") == nil { - t.Error("access to parameter failed") - } -} - -func TestRouteBuilder(t *testing.T) { - json := "application/json" - b := new(RouteBuilder) - b.To(dummy) - b.Path("/routes").Method("HEAD").Consumes(json).Produces(json) - r := b.Build() - if r.Path != "/routes" { - t.Error("path invalid") - } - if r.Produces[0] != json { - t.Error("produces invalid") - } - if r.Consumes[0] != json { - t.Error("consumes invalid") - } - if r.Operation != "dummy" { - t.Error("Operation not set") - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/route_test.go deleted file mode 100644 index 6a104aff8..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package restful - -import ( - "testing" -) - -// accept should match produces -func TestMatchesAcceptPlainTextWhenProducePlainTextAsLast(t *testing.T) { - r := Route{Produces: []string{"application/json", "text/plain"}} - if !r.matchesAccept("text/plain") { - t.Errorf("accept should match text/plain") - } -} - -// accept should match produces -func TestMatchesAcceptStar(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if !r.matchesAccept("*/*") { - t.Errorf("accept should match star") - } -} - -// accept should match produces -func TestMatchesAcceptIE(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if !r.matchesAccept("text/html, application/xhtml+xml, */*") { - t.Errorf("accept should match star") - } -} - -// accept should match produces -func TestMatchesAcceptXml(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if r.matchesAccept("application/json") { - t.Errorf("accept should not match json") - } - if !r.matchesAccept("application/xml") { - t.Errorf("accept should match xml") - } -} - -// accept should match produces -func TestMatchesAcceptAny(t *testing.T) { - r := Route{Produces: []string{"*/*"}} - if !r.matchesAccept("application/json") { - t.Errorf("accept should match json") - } - if !r.matchesAccept("application/xml") { - t.Errorf("accept should match xml") - } -} - -// content type should match consumes -func TestMatchesContentTypeXml(t *testing.T) { - r := Route{Consumes: []string{"application/xml"}} - if r.matchesContentType("application/json") { - t.Errorf("accept should not match json") - } - if !r.matchesContentType("application/xml") { - t.Errorf("accept should match xml") - } -} - -// content type should match consumes -func TestMatchesContentTypeCharsetInformation(t *testing.T) { - r := Route{Consumes: []string{"application/json"}} - if !r.matchesContentType("application/json; charset=UTF-8") { - t.Errorf("matchesContentType should ignore charset information") - } -} - -func TestMatchesPath_OneParam(t *testing.T) { - params := doExtractParams("/from/{source}", 2, "/from/here", t) - if params["source"] != "here" { - t.Errorf("parameter mismatch here") - } -} - -func TestMatchesPath_Slash(t *testing.T) { - params := doExtractParams("/", 0, "/", t) - if len(params) != 0 { - t.Errorf("expected empty parameters") - } -} - -func TestMatchesPath_SlashNonVar(t *testing.T) { - params := doExtractParams("/any", 1, "/any", t) - if len(params) != 0 { - t.Errorf("expected empty parameters") - } -} - -func TestMatchesPath_TwoVars(t *testing.T) { - params := doExtractParams("/from/{source}/to/{destination}", 4, "/from/AMS/to/NY", t) - if params["source"] != "AMS" { - t.Errorf("parameter mismatch AMS") - } -} - -func TestMatchesPath_VarOnFront(t *testing.T) { - params := doExtractParams("{what}/from/{source}/", 3, "who/from/SOS/", t) - if params["source"] != "SOS" { - t.Errorf("parameter mismatch SOS") - } -} - -func TestExtractParameters_EmptyValue(t *testing.T) { - params := doExtractParams("/fixed/{var}", 2, "/fixed/", t) - if params["var"] != "" { - t.Errorf("parameter mismatch var") - } -} - -func TestTokenizePath(t *testing.T) { - if len(tokenizePath("/")) != 0 { - t.Errorf("not empty path tokens") - } -} - -func doExtractParams(routePath string, size int, urlPath string, t *testing.T) map[string]string { - r := Route{Path: routePath} - r.postBuild() - if len(r.pathParts) != size { - t.Fatalf("len not %v %v, but %v", size, r.pathParts, len(r.pathParts)) - } - return r.extractParameters(urlPath) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_builder_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_builder_test.go deleted file mode 100644 index fa3a1a453..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_builder_test.go +++ /dev/null @@ -1,1142 +0,0 @@ -package swagger - -import ( - "net" - "testing" - "time" -) - -type YesNo bool - -func (y YesNo) MarshalJSON() ([]byte, error) { - if y { - return []byte("yes"), nil - } - return []byte("no"), nil -} - -// clear && go test -v -test.run TestRef_Issue190 ...swagger -func TestRef_Issue190(t *testing.T) { - type User struct { - items []string - } - testJsonFromStruct(t, User{}, `{ - "swagger.User": { - "id": "swagger.User", - "required": [ - "items" - ], - "properties": { - "items": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -// clear && go test -v -test.run TestCustomMarshaller_Issue96 ...swagger -func TestCustomMarshaller_Issue96(t *testing.T) { - type Vote struct { - What YesNo - } - testJsonFromStruct(t, Vote{}, `{ - "swagger.Vote": { - "id": "swagger.Vote", - "required": [ - "What" - ], - "properties": { - "What": { - "type": "string" - } - } - } - }`) -} - -// clear && go test -v -test.run TestPrimitiveTypes ...swagger -func TestPrimitiveTypes(t *testing.T) { - type Prims struct { - f float64 - t time.Time - } - testJsonFromStruct(t, Prims{}, `{ - "swagger.Prims": { - "id": "swagger.Prims", - "required": [ - "f", - "t" - ], - "properties": { - "f": { - "type": "number", - "format": "double" - }, - "t": { - "type": "string", - "format": "date-time" - } - } - } - }`) -} - -// clear && go test -v -test.run TestPrimitivePtrTypes ...swagger -func TestPrimitivePtrTypes(t *testing.T) { - type Prims struct { - f *float64 - t *time.Time - b *bool - s *string - i *int - } - testJsonFromStruct(t, Prims{}, `{ - "swagger.Prims": { - "id": "swagger.Prims", - "required": [ - "f", - "t", - "b", - "s", - "i" - ], - "properties": { - "b": { - "type": "boolean" - }, - "f": { - "type": "number", - "format": "double" - }, - "i": { - "type": "integer", - "format": "int32" - }, - "s": { - "type": "string" - }, - "t": { - "type": "string", - "format": "date-time" - } - } - } - }`) -} - -// clear && go test -v -test.run TestS1 ...swagger -func TestS1(t *testing.T) { - type S1 struct { - Id string - } - testJsonFromStruct(t, S1{}, `{ - "swagger.S1": { - "id": "swagger.S1", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "string" - } - } - } - }`) -} - -// clear && go test -v -test.run TestS2 ...swagger -func TestS2(t *testing.T) { - type S2 struct { - Ids []string - } - testJsonFromStruct(t, S2{}, `{ - "swagger.S2": { - "id": "swagger.S2", - "required": [ - "Ids" - ], - "properties": { - "Ids": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -// clear && go test -v -test.run TestS3 ...swagger -func TestS3(t *testing.T) { - type NestedS3 struct { - Id string - } - type S3 struct { - Nested NestedS3 - } - testJsonFromStruct(t, S3{}, `{ - "swagger.NestedS3": { - "id": "swagger.NestedS3", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "string" - } - } - }, - "swagger.S3": { - "id": "swagger.S3", - "required": [ - "Nested" - ], - "properties": { - "Nested": { - "$ref": "swagger.NestedS3" - } - } - } - }`) -} - -type sample struct { - id string `swagger:"required"` // TODO - items []item - rootItem item `json:"root" description:"root desc"` -} - -type item struct { - itemName string `json:"name"` -} - -// clear && go test -v -test.run TestSampleToModelAsJson ...swagger -func TestSampleToModelAsJson(t *testing.T) { - testJsonFromStruct(t, sample{items: []item{}}, `{ - "swagger.item": { - "id": "swagger.item", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - } - } - }, - "swagger.sample": { - "id": "swagger.sample", - "required": [ - "id", - "items", - "root" - ], - "properties": { - "id": { - "type": "string" - }, - "items": { - "type": "array", - "items": { - "$ref": "swagger.item" - } - }, - "root": { - "$ref": "swagger.item", - "description": "root desc" - } - } - } - }`) -} - -func TestJsonTags(t *testing.T) { - type X struct { - A string - B string `json:"-"` - C int `json:",string"` - D int `json:","` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A", - "C", - "D" - ], - "properties": { - "A": { - "type": "string" - }, - "C": { - "type": "string" - }, - "D": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestJsonTagOmitempty(t *testing.T) { - type X struct { - A int `json:",omitempty"` - B int `json:"C,omitempty"` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "properties": { - "A": { - "type": "integer", - "format": "int32" - }, - "C": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestJsonTagName(t *testing.T) { - type X struct { - A string `json:"B"` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "string" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousStruct(t *testing.T) { - type X struct { - A struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "$ref": "swagger.X.A" - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousPtrStruct(t *testing.T) { - type X struct { - A *struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "$ref": "swagger.X.A" - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousArrayStruct(t *testing.T) { - type X struct { - A []struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "array", - "items": { - "$ref": "swagger.X.A" - } - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousPtrArrayStruct(t *testing.T) { - type X struct { - A *[]struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "array", - "items": { - "$ref": "swagger.X.A" - } - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -// go test -v -test.run TestEmbeddedStruct_Issue98 ...swagger -func TestEmbeddedStruct_Issue98(t *testing.T) { - type Y struct { - A int - } - type X struct { - Y - } - testJsonFromStruct(t, X{}, `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type Dataset struct { - Names []string -} - -// clear && go test -v -test.run TestIssue85 ...swagger -func TestIssue85(t *testing.T) { - anon := struct{ Datasets []Dataset }{} - testJsonFromStruct(t, anon, `{ - "struct { Datasets ||swagger.Dataset }": { - "id": "struct { Datasets ||swagger.Dataset }", - "required": [ - "Datasets" - ], - "properties": { - "Datasets": { - "type": "array", - "items": { - "$ref": "swagger.Dataset" - } - } - } - }, - "swagger.Dataset": { - "id": "swagger.Dataset", - "required": [ - "Names" - ], - "properties": { - "Names": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -type File struct { - History []File - HistoryPtrs []*File -} - -// go test -v -test.run TestRecursiveStructure ...swagger -func TestRecursiveStructure(t *testing.T) { - testJsonFromStruct(t, File{}, `{ - "swagger.File": { - "id": "swagger.File", - "required": [ - "History", - "HistoryPtrs" - ], - "properties": { - "History": { - "type": "array", - "items": { - "$ref": "swagger.File" - } - }, - "HistoryPtrs": { - "type": "array", - "items": { - "$ref": "swagger.File" - } - } - } - } - }`) -} - -type A1 struct { - B struct { - Id int - Comment string `json:"comment,omitempty"` - } -} - -// go test -v -test.run TestEmbeddedStructA1 ...swagger -func TestEmbeddedStructA1(t *testing.T) { - testJsonFromStruct(t, A1{}, `{ - "swagger.A1": { - "id": "swagger.A1", - "required": [ - "B" - ], - "properties": { - "B": { - "$ref": "swagger.A1.B" - } - } - }, - "swagger.A1.B": { - "id": "swagger.A1.B", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - }, - "comment": { - "type": "string" - } - } - } - }`) -} - -type A2 struct { - C -} -type C struct { - Id int `json:"B"` - Comment string `json:"comment,omitempty"` - Secure bool `json:"secure"` -} - -// go test -v -test.run TestEmbeddedStructA2 ...swagger -func TestEmbeddedStructA2(t *testing.T) { - testJsonFromStruct(t, A2{}, `{ - "swagger.A2": { - "id": "swagger.A2", - "required": [ - "B", - "secure" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - }, - "comment": { - "type": "string" - }, - "secure": { - "type": "boolean" - } - } - } - }`) -} - -type A3 struct { - B D -} - -type D struct { - Id int -} - -// clear && go test -v -test.run TestStructA3 ...swagger -func TestStructA3(t *testing.T) { - testJsonFromStruct(t, A3{}, `{ - "swagger.A3": { - "id": "swagger.A3", - "required": [ - "B" - ], - "properties": { - "B": { - "$ref": "swagger.D" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type A4 struct { - D "json:,inline" -} - -// clear && go test -v -test.run TestStructA4 ...swagger -func TestEmbeddedStructA4(t *testing.T) { - testJsonFromStruct(t, A4{}, `{ - "swagger.A4": { - "id": "swagger.A4", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type A5 struct { - D `json:"d"` -} - -// clear && go test -v -test.run TestStructA5 ...swagger -func TestEmbeddedStructA5(t *testing.T) { - testJsonFromStruct(t, A5{}, `{ - "swagger.A5": { - "id": "swagger.A5", - "required": [ - "d" - ], - "properties": { - "d": { - "$ref": "swagger.D" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type D2 struct { - id int - D []D -} - -type A6 struct { - D2 "json:,inline" -} - -// clear && go test -v -test.run TestStructA4 ...swagger -func TestEmbeddedStructA6(t *testing.T) { - testJsonFromStruct(t, A6{}, `{ - "swagger.A6": { - "id": "swagger.A6", - "required": [ - "id", - "D" - ], - "properties": { - "D": { - "type": "array", - "items": { - "$ref": "swagger.D" - } - }, - "id": { - "type": "integer", - "format": "int32" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type ObjectId []byte - -type Region struct { - Id ObjectId `bson:"_id" json:"id"` - Name string `bson:"name" json:"name"` - Type string `bson:"type" json:"type"` -} - -// clear && go test -v -test.run TestRegion_Issue113 ...swagger -func TestRegion_Issue113(t *testing.T) { - testJsonFromStruct(t, []Region{}, `{ - "integer": { - "id": "integer", - "properties": {} - }, - "swagger.Region": { - "id": "swagger.Region", - "required": [ - "id", - "name", - "type" - ], - "properties": { - "id": { - "type": "array", - "items": { - "$ref": "integer" - } - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - } - } - }, - "||swagger.Region": { - "id": "||swagger.Region", - "properties": {} - } - }`) -} - -// clear && go test -v -test.run TestIssue158 ...swagger -func TestIssue158(t *testing.T) { - type Address struct { - Country string `json:"country,omitempty"` - } - - type Customer struct { - Name string `json:"name"` - Address Address `json:"address"` - } - expected := `{ - "swagger.Address": { - "id": "swagger.Address", - "properties": { - "country": { - "type": "string" - } - } - }, - "swagger.Customer": { - "id": "swagger.Customer", - "required": [ - "name", - "address" - ], - "properties": { - "address": { - "$ref": "swagger.Address" - }, - "name": { - "type": "string" - } - } - } - }` - testJsonFromStruct(t, Customer{}, expected) -} - -func TestSlices(t *testing.T) { - type Address struct { - Country string `json:"country,omitempty"` - } - expected := `{ - "swagger.Address": { - "id": "swagger.Address", - "properties": { - "country": { - "type": "string" - } - } - }, - "swagger.Customer": { - "id": "swagger.Customer", - "required": [ - "name", - "addresses" - ], - "properties": { - "addresses": { - "type": "array", - "items": { - "$ref": "swagger.Address" - } - }, - "name": { - "type": "string" - } - } - } - }` - // both slices (with pointer value and with type value) should have equal swagger representation - { - type Customer struct { - Name string `json:"name"` - Addresses []Address `json:"addresses"` - } - testJsonFromStruct(t, Customer{}, expected) - } - { - type Customer struct { - Name string `json:"name"` - Addresses []*Address `json:"addresses"` - } - testJsonFromStruct(t, Customer{}, expected) - } - -} - -type Name struct { - Value string -} - -func (n Name) PostBuildModel(m *Model) *Model { - m.Description = "titles must be upcase" - return m -} - -type TOC struct { - Titles []Name -} - -type Discography struct { - Title Name - TOC -} - -// clear && go test -v -test.run TestEmbeddedStructPull204 ...swagger -func TestEmbeddedStructPull204(t *testing.T) { - b := Discography{} - testJsonFromStruct(t, b, ` -{ - "swagger.Discography": { - "id": "swagger.Discography", - "required": [ - "Title", - "Titles" - ], - "properties": { - "Title": { - "$ref": "swagger.Name" - }, - "Titles": { - "type": "array", - "items": { - "$ref": "swagger.Name" - } - } - } - }, - "swagger.Name": { - "id": "swagger.Name", - "required": [ - "Value" - ], - "properties": { - "Value": { - "type": "string" - } - } - } - } -`) -} - -type AddressWithMethod struct { - Country string `json:"country,omitempty"` - PostCode int `json:"postcode,omitempty"` -} - -func (AddressWithMethod) SwaggerDoc() map[string]string { - return map[string]string{ - "": "Address doc", - "country": "Country doc", - "postcode": "PostCode doc", - } -} - -func TestDocInMethodSwaggerDoc(t *testing.T) { - expected := `{ - "swagger.AddressWithMethod": { - "id": "swagger.AddressWithMethod", - "description": "Address doc", - "properties": { - "country": { - "type": "string", - "description": "Country doc" - }, - "postcode": { - "type": "integer", - "format": "int32", - "description": "PostCode doc" - } - } - } - }` - testJsonFromStruct(t, AddressWithMethod{}, expected) -} - -type RefDesc struct { - f1 *int64 `description:"desc"` -} - -func TestPtrDescription(t *testing.T) { - b := RefDesc{} - expected := `{ - "swagger.RefDesc": { - "id": "swagger.RefDesc", - "required": [ - "f1" - ], - "properties": { - "f1": { - "type": "integer", - "format": "int64", - "description": "desc" - } - } - } - }` - testJsonFromStruct(t, b, expected) -} - -type A struct { - B `json:",inline"` - C1 `json:"metadata,omitempty"` -} - -type B struct { - SB string -} - -type C1 struct { - SC string -} - -func (A) SwaggerDoc() map[string]string { - return map[string]string{ - "": "A struct", - "B": "B field", // We should not get anything from this - "metadata": "C1 field", - } -} - -func (B) SwaggerDoc() map[string]string { - return map[string]string{ - "": "B struct", - "SB": "SB field", - } -} - -func (C1) SwaggerDoc() map[string]string { - return map[string]string{ - "": "C1 struct", - "SC": "SC field", - } -} - -func TestNestedStructDescription(t *testing.T) { - expected := ` -{ - "swagger.A": { - "id": "swagger.A", - "description": "A struct", - "required": [ - "SB" - ], - "properties": { - "SB": { - "type": "string", - "description": "SB field" - }, - "metadata": { - "$ref": "swagger.C1", - "description": "C1 field" - } - } - }, - "swagger.C1": { - "id": "swagger.C1", - "description": "C1 struct", - "required": [ - "SC" - ], - "properties": { - "SC": { - "type": "string", - "description": "SC field" - } - } - } - } -` - testJsonFromStruct(t, A{}, expected) -} - -// This tests a primitive with type overrides in the struct tags -type FakeInt int -type E struct { - Id FakeInt `type:"integer"` - IP net.IP `type:"string"` -} - -func TestOverridenTypeTagE1(t *testing.T) { - expected := ` -{ - "swagger.E": { - "id": "swagger.E", - "required": [ - "Id", - "IP" - ], - "properties": { - "Id": { - "type": "integer" - }, - "IP": { - "type": "string" - } - } - } - } -` - testJsonFromStruct(t, E{}, expected) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_list_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_list_test.go deleted file mode 100644 index 9a9ab919b..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" -) - -func TestModelList(t *testing.T) { - m := Model{} - m.Id = "m" - l := ModelList{} - l.Put("m", m) - k, ok := l.At("m") - if !ok { - t.Error("want model back") - } - if got, want := k.Id, "m"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelList_Marshal(t *testing.T) { - l := ModelList{} - m := Model{Id: "myid"} - l.Put("myid", m) - data, err := json.Marshal(l) - if err != nil { - t.Error(err) - } - if got, want := string(data), `{"myid":{"id":"myid","properties":{}}}`; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelList_Unmarshal(t *testing.T) { - data := `{"myid":{"id":"myid","properties":{}}}` - l := ModelList{} - if err := json.Unmarshal([]byte(data), &l); err != nil { - t.Error(err) - } - m, ok := l.At("myid") - if !ok { - t.Error("expected myid") - } - if got, want := m.Id, "myid"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_ext_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_ext_test.go deleted file mode 100644 index eff0d59d3..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_ext_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package swagger - -import ( - "net" - "testing" -) - -// clear && go test -v -test.run TestThatExtraTagsAreReadIntoModel ...swagger -func TestThatExtraTagsAreReadIntoModel(t *testing.T) { - type fakeint int - type Anything struct { - Name string `description:"name" modelDescription:"a test"` - Size int `minimum:"0" maximum:"10"` - Stati string `enum:"off|on" default:"on" modelDescription:"more description"` - ID string `unique:"true"` - FakeInt fakeint `type:"integer"` - IP net.IP `type:"string"` - Password string - } - m := modelsFromStruct(Anything{}) - props, _ := m.At("swagger.Anything") - p1, _ := props.Properties.At("Name") - if got, want := p1.Description, "name"; got != want { - t.Errorf("got %v want %v", got, want) - } - p2, _ := props.Properties.At("Size") - if got, want := p2.Minimum, "0"; got != want { - t.Errorf("got %v want %v", got, want) - } - if got, want := p2.Maximum, "10"; got != want { - t.Errorf("got %v want %v", got, want) - } - p3, _ := props.Properties.At("Stati") - if got, want := p3.Enum[0], "off"; got != want { - t.Errorf("got %v want %v", got, want) - } - if got, want := p3.Enum[1], "on"; got != want { - t.Errorf("got %v want %v", got, want) - } - p4, _ := props.Properties.At("ID") - if got, want := *p4.UniqueItems, true; got != want { - t.Errorf("got %v want %v", got, want) - } - p5, _ := props.Properties.At("Password") - if got, want := *p5.Type, "string"; got != want { - t.Errorf("got %v want %v", got, want) - } - p6, _ := props.Properties.At("FakeInt") - if got, want := *p6.Type, "integer"; got != want { - t.Errorf("got %v want %v", got, want) - } - p7, _ := props.Properties.At("IP") - if got, want := *p7.Type, "string"; got != want { - t.Errorf("got %v want %v", got, want) - } - - if got, want := props.Description, "a test\nmore description"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_list_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_list_test.go deleted file mode 100644 index 2833ad8fd..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_list_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" -) - -func TestModelPropertyList(t *testing.T) { - l := ModelPropertyList{} - p := ModelProperty{Description: "d"} - l.Put("p", p) - q, ok := l.At("p") - if !ok { - t.Error("expected p") - } - if got, want := q.Description, "d"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelPropertyList_Marshal(t *testing.T) { - l := ModelPropertyList{} - p := ModelProperty{Description: "d"} - l.Put("p", p) - data, err := json.Marshal(l) - if err != nil { - t.Error(err) - } - if got, want := string(data), `{"p":{"description":"d"}}`; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelPropertyList_Unmarshal(t *testing.T) { - data := `{"p":{"description":"d"}}` - l := ModelPropertyList{} - if err := json.Unmarshal([]byte(data), &l); err != nil { - t.Error(err) - } - m, ok := l.At("p") - if !ok { - t.Error("expected p") - } - if got, want := m.Description, "d"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go deleted file mode 100644 index 964e7da05..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package swagger - -import ( - "testing" - - "github.com/emicklei/go-restful" -) - -// go test -v -test.run TestOrderedRouteMap ...swagger -func TestOrderedRouteMap(t *testing.T) { - m := newOrderedRouteMap() - r1 := restful.Route{Path: "/r1"} - r2 := restful.Route{Path: "/r2"} - m.Add("a", r1) - m.Add("b", r2) - m.Add("b", r1) - m.Add("d", r2) - m.Add("c", r2) - order := "" - m.Do(func(k string, routes []restful.Route) { - order += k - if len(routes) == 0 { - t.Fail() - } - }) - if order != "abdc" { - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/postbuild_model_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/postbuild_model_test.go deleted file mode 100644 index 3e20d2f5b..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/postbuild_model_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package swagger - -import "testing" - -type Boat struct { - Length int `json:"-"` // on default, this makes the fields not required - Weight int `json:"-"` -} - -// PostBuildModel is from swagger.ModelBuildable -func (b Boat) PostBuildModel(m *Model) *Model { - // override required - m.Required = []string{"Length", "Weight"} - - // add model property (just to test is can be added; is this a real usecase?) - extraType := "string" - m.Properties.Put("extra", ModelProperty{ - Description: "extra description", - DataTypeFields: DataTypeFields{ - Type: &extraType, - }, - }) - return m -} - -func TestCustomPostModelBuilde(t *testing.T) { - testJsonFromStruct(t, Boat{}, `{ - "swagger.Boat": { - "id": "swagger.Boat", - "required": [ - "Length", - "Weight" - ], - "properties": { - "extra": { - "type": "string", - "description": "extra description" - } - } - } -}`) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/swagger_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/swagger_test.go deleted file mode 100644 index 78e2d43cc..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/swagger_test.go +++ /dev/null @@ -1,284 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" - - "github.com/emicklei/go-restful" - "github.com/emicklei/go-restful/swagger/test_package" -) - -func TestInfoStruct_Issue231(t *testing.T) { - config := Config{ - Info: Info{ - Title: "Title", - Description: "Description", - TermsOfServiceUrl: "http://example.com", - Contact: "example@example.com", - License: "License", - LicenseUrl: "http://example.com/license.txt", - }, - } - sws := newSwaggerService(config) - str, err := json.MarshalIndent(sws.produceListing(), "", " ") - if err != nil { - t.Fatal(err) - } - compareJson(t, string(str), ` - { - "apiVersion": "", - "swaggerVersion": "1.2", - "apis": null, - "info": { - "title": "Title", - "description": "Description", - "termsOfServiceUrl": "http://example.com", - "contact": "example@example.com", - "license": "License", - "licenseUrl": "http://example.com/license.txt" - } - } - `) -} - -// go test -v -test.run TestThatMultiplePathsOnRootAreHandled ...swagger -func TestThatMultiplePathsOnRootAreHandled(t *testing.T) { - ws1 := new(restful.WebService) - ws1.Route(ws1.GET("/_ping").To(dummy)) - ws1.Route(ws1.GET("/version").To(dummy)) - - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws1}, - } - sws := newSwaggerService(cfg) - decl := sws.composeDeclaration(ws1, "/") - if got, want := len(decl.Apis), 2; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestWriteSamples(t *testing.T) { - ws1 := new(restful.WebService) - ws1.Route(ws1.GET("/object").To(dummy).Writes(test_package.TestStruct{})) - ws1.Route(ws1.GET("/array").To(dummy).Writes([]test_package.TestStruct{})) - ws1.Route(ws1.GET("/object_and_array").To(dummy).Writes(struct{ Abc test_package.TestStruct }{})) - - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws1}, - } - sws := newSwaggerService(cfg) - - decl := sws.composeDeclaration(ws1, "/") - - str, err := json.MarshalIndent(decl.Apis, "", " ") - if err != nil { - t.Fatal(err) - } - - compareJson(t, string(str), ` - [ - { - "path": "/object", - "description": "", - "operations": [ - { - "type": "test_package.TestStruct", - "method": "GET", - "nickname": "dummy", - "parameters": [] - } - ] - }, - { - "path": "/array", - "description": "", - "operations": [ - { - "type": "array", - "items": { - "$ref": "test_package.TestStruct" - }, - "method": "GET", - "nickname": "dummy", - "parameters": [] - } - ] - }, - { - "path": "/object_and_array", - "description": "", - "operations": [ - { - "type": "struct { Abc test_package.TestStruct }", - "method": "GET", - "nickname": "dummy", - "parameters": [] - } - ] - } - ]`) - - str, err = json.MarshalIndent(decl.Models, "", " ") - if err != nil { - t.Fatal(err) - } - compareJson(t, string(str), ` - { - "test_package.TestStruct": { - "id": "test_package.TestStruct", - "required": [ - "TestField" - ], - "properties": { - "TestField": { - "type": "string" - } - } - }, - "||test_package.TestStruct": { - "id": "||test_package.TestStruct", - "properties": {} - }, - "struct { Abc test_package.TestStruct }": { - "id": "struct { Abc test_package.TestStruct }", - "required": [ - "Abc" - ], - "properties": { - "Abc": { - "$ref": "test_package.TestStruct" - } - } - } - }`) -} - -// go test -v -test.run TestServiceToApi ...swagger -func TestServiceToApi(t *testing.T) { - ws := new(restful.WebService) - ws.Path("/tests") - ws.Consumes(restful.MIME_JSON) - ws.Produces(restful.MIME_XML) - ws.Route(ws.GET("/a").To(dummy).Writes(sample{})) - ws.Route(ws.PUT("/b").To(dummy).Writes(sample{})) - ws.Route(ws.POST("/c").To(dummy).Writes(sample{})) - ws.Route(ws.DELETE("/d").To(dummy).Writes(sample{})) - - ws.Route(ws.GET("/d").To(dummy).Writes(sample{})) - ws.Route(ws.PUT("/c").To(dummy).Writes(sample{})) - ws.Route(ws.POST("/b").To(dummy).Writes(sample{})) - ws.Route(ws.DELETE("/a").To(dummy).Writes(sample{})) - ws.ApiVersion("1.2.3") - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws}, - PostBuildHandler: func(in *ApiDeclarationList) {}, - } - sws := newSwaggerService(cfg) - decl := sws.composeDeclaration(ws, "/tests") - // checks - if decl.ApiVersion != "1.2.3" { - t.Errorf("got %v want %v", decl.ApiVersion, "1.2.3") - } - if decl.BasePath != "http://here.com" { - t.Errorf("got %v want %v", decl.BasePath, "http://here.com") - } - if len(decl.Apis) != 4 { - t.Errorf("got %v want %v", len(decl.Apis), 4) - } - pathOrder := "" - for _, each := range decl.Apis { - pathOrder += each.Path - for _, other := range each.Operations { - pathOrder += other.Method - } - } - - if pathOrder != "/tests/aGETDELETE/tests/bPUTPOST/tests/cPOSTPUT/tests/dDELETEGET" { - t.Errorf("got %v want %v", pathOrder, "see test source") - } -} - -func dummy(i *restful.Request, o *restful.Response) {} - -// go test -v -test.run TestIssue78 ...swagger -type Response struct { - Code int - Users *[]User - Items *[]TestItem -} -type User struct { - Id, Name string -} -type TestItem struct { - Id, Name string -} - -// clear && go test -v -test.run TestComposeResponseMessages ...swagger -func TestComposeResponseMessages(t *testing.T) { - responseErrors := map[int]restful.ResponseError{} - responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: TestItem{}} - route := restful.Route{ResponseErrors: responseErrors} - decl := new(ApiDeclaration) - decl.Models = ModelList{} - msgs := composeResponseMessages(route, decl) - if msgs[0].ResponseModel != "swagger.TestItem" { - t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) - } -} - -// clear && go test -v -test.run TestComposeResponseMessageArray ...swagger -func TestComposeResponseMessageArray(t *testing.T) { - responseErrors := map[int]restful.ResponseError{} - responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: []TestItem{}} - route := restful.Route{ResponseErrors: responseErrors} - decl := new(ApiDeclaration) - decl.Models = ModelList{} - msgs := composeResponseMessages(route, decl) - if msgs[0].ResponseModel != "array[swagger.TestItem]" { - t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) - } -} - -func TestIssue78(t *testing.T) { - sws := newSwaggerService(Config{}) - models := new(ModelList) - sws.addModelFromSampleTo(&Operation{}, true, Response{Items: &[]TestItem{}}, models) - model, ok := models.At("swagger.Response") - if !ok { - t.Fatal("missing response model") - } - if "swagger.Response" != model.Id { - t.Fatal("wrong model id:" + model.Id) - } - code, ok := model.Properties.At("Code") - if !ok { - t.Fatal("missing code") - } - if "integer" != *code.Type { - t.Fatal("wrong code type:" + *code.Type) - } - items, ok := model.Properties.At("Items") - if !ok { - t.Fatal("missing items") - } - if "array" != *items.Type { - t.Fatal("wrong items type:" + *items.Type) - } - items_items := items.Items - if items_items == nil { - t.Fatal("missing items->items") - } - ref := items_items.Ref - if ref == nil { - t.Fatal("missing $ref") - } - if *ref != "swagger.TestItem" { - t.Fatal("wrong $ref:" + *ref) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/test_package/struct.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/test_package/struct.go deleted file mode 100644 index b9a6f9308..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/test_package/struct.go +++ /dev/null @@ -1,5 +0,0 @@ -package test_package - -type TestStruct struct { - TestField string -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/utils_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/utils_test.go deleted file mode 100644 index dab871032..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/utils_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package swagger - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strings" - "testing" -) - -func testJsonFromStruct(t *testing.T, sample interface{}, expectedJson string) bool { - m := modelsFromStruct(sample) - data, _ := json.MarshalIndent(m, " ", " ") - return compareJson(t, string(data), expectedJson) -} - -func modelsFromStruct(sample interface{}) *ModelList { - models := new(ModelList) - builder := modelBuilder{models} - builder.addModelFrom(sample) - return models -} - -func compareJson(t *testing.T, actualJsonAsString string, expectedJsonAsString string) bool { - success := false - var actualMap map[string]interface{} - json.Unmarshal([]byte(actualJsonAsString), &actualMap) - var expectedMap map[string]interface{} - err := json.Unmarshal([]byte(expectedJsonAsString), &expectedMap) - if err != nil { - var actualArray []interface{} - json.Unmarshal([]byte(actualJsonAsString), &actualArray) - var expectedArray []interface{} - err := json.Unmarshal([]byte(expectedJsonAsString), &expectedArray) - success = reflect.DeepEqual(actualArray, expectedArray) - if err != nil { - t.Fatalf("Unparsable expected JSON: %s", err) - } - } else { - success = reflect.DeepEqual(actualMap, expectedMap) - } - if !success { - t.Log("---- expected -----") - t.Log(withLineNumbers(expectedJsonAsString)) - t.Log("---- actual -----") - t.Log(withLineNumbers(actualJsonAsString)) - t.Log("---- raw -----") - t.Log(actualJsonAsString) - t.Error("there are differences") - return false - } - return true -} - -func indexOfNonMatchingLine(actual, expected string) int { - a := strings.Split(actual, "\n") - e := strings.Split(expected, "\n") - size := len(a) - if len(e) < len(a) { - size = len(e) - } - for i := 0; i < size; i++ { - if a[i] != e[i] { - return i - } - } - return -1 -} - -func withLineNumbers(content string) string { - var buffer bytes.Buffer - lines := strings.Split(content, "\n") - for i, each := range lines { - buffer.WriteString(fmt.Sprintf("%d:%s\n", i, each)) - } - return buffer.String() -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/tracer_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/tracer_test.go deleted file mode 100644 index 60c1e9fc0..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/tracer_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package restful - -import "testing" - -// Use like this: -// -// TraceLogger(testLogger{t}) -type testLogger struct { - t *testing.T -} - -func (l testLogger) Print(v ...interface{}) { - l.t.Log(v...) -} - -func (l testLogger) Printf(format string, v ...interface{}) { - l.t.Logf(format, v...) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/web_service_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/web_service_test.go deleted file mode 100644 index 469890434..000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/web_service_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -const ( - pathGetFriends = "/get/{userId}/friends" -) - -func TestParameter(t *testing.T) { - p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} - p.AllowMultiple(true) - p.DataType("int") - p.Required(true) - values := map[string]string{"a": "b"} - p.AllowableValues(values) - p.bePath() - - ws := new(WebService) - ws.Param(p) - if ws.pathParameters[0].Data().Name != "name" { - t.Error("path parameter (or name) invalid") - } -} -func TestWebService_CanCreateParameterKinds(t *testing.T) { - ws := new(WebService) - if ws.BodyParameter("b", "b").Kind() != BodyParameterKind { - t.Error("body parameter expected") - } - if ws.PathParameter("p", "p").Kind() != PathParameterKind { - t.Error("path parameter expected") - } - if ws.QueryParameter("q", "q").Kind() != QueryParameterKind { - t.Error("query parameter expected") - } -} - -func TestCapturePanic(t *testing.T) { - tearDown() - Add(newPanicingService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 500 != httpWriter.Code { - t.Error("500 expected on fire") - } -} - -func TestCapturePanicWithEncoded(t *testing.T) { - tearDown() - Add(newPanicingService()) - DefaultContainer.EnableContentEncoding(true) - httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) - httpRequest.Header.Set("Accept", "*/*") - httpRequest.Header.Set("Accept-Encoding", "gzip") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 500 != httpWriter.Code { - t.Error("500 expected on fire, got", httpWriter.Code) - } -} - -func TestNotFound(t *testing.T) { - tearDown() - httpRequest, _ := http.NewRequest("GET", "http://here.com/missing", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 404 != httpWriter.Code { - t.Error("404 expected on missing") - } -} - -func TestMethodNotAllowed(t *testing.T) { - tearDown() - Add(newGetOnlyService()) - httpRequest, _ := http.NewRequest("POST", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 405 != httpWriter.Code { - t.Error("405 expected method not allowed") - } -} - -func TestSelectedRoutePath_Issue100(t *testing.T) { - tearDown() - Add(newSelectedRouteTestingService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get/232452/friends", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if http.StatusOK != httpWriter.Code { - t.Error(http.StatusOK, "expected,", httpWriter.Code, "received.") - } -} - -func TestContentType415_Issue170(t *testing.T) { - tearDown() - Add(newGetOnlyJsonOnlyService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -func TestContentType415_POST_Issue170(t *testing.T) { - tearDown() - Add(newPostOnlyJsonOnlyService()) - httpRequest, _ := http.NewRequest("POST", "http://here.com/post", nil) - httpRequest.Header.Set("Content-Type", "application/json") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -// go test -v -test.run TestContentType406PlainJson ...restful -func TestContentType406PlainJson(t *testing.T) { - tearDown() - TraceLogger(testLogger{t}) - Add(newGetPlainTextOrJsonService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "text/plain") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 200; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestRemoveRoute(t *testing.T) { - tearDown() - TraceLogger(testLogger{t}) - ws := newGetPlainTextOrJsonService() - Add(ws) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "text/plain") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 200; got != want { - t.Errorf("got %v, want %v", got, want) - } - - // dynamic apis are disabled, should error and do nothing - if err := ws.RemoveRoute("/get", "GET"); err == nil { - t.Error("unexpected non-error") - } - - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 200; got != want { - t.Errorf("got %v, want %v", got, want) - } - - ws.SetDynamicRoutes(true) - if err := ws.RemoveRoute("/get", "GET"); err != nil { - t.Errorf("unexpected error %v", err) - } - - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 404; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -// go test -v -test.run TestContentTypeOctet_Issue170 ...restful -func TestContentTypeOctet_Issue170(t *testing.T) { - tearDown() - Add(newGetConsumingOctetStreamService()) - // with content-type - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Content-Type", MIME_OCTET) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } - // without content-type - httpRequest, _ = http.NewRequest("GET", "http://here.com/get", nil) - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -func newPanicingService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET("/fire").To(doPanic)) - return ws -} - -func newGetOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET("/get").To(doPanic)) - return ws -} - -func newPostOnlyJsonOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/json") - ws.Route(ws.POST("/post").To(doNothing)) - return ws -} - -func newGetOnlyJsonOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/json") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newGetPlainTextOrJsonService() *WebService { - ws := new(WebService).Path("") - ws.Produces("text/plain", "application/json") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newGetConsumingOctetStreamService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/octet-stream") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newSelectedRouteTestingService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET(pathGetFriends).To(selectedRouteChecker)) - return ws -} - -func selectedRouteChecker(req *Request, resp *Response) { - if req.SelectedRoutePath() != pathGetFriends { - resp.InternalServerError() - } -} - -func doPanic(req *Request, resp *Response) { - println("lightning...") - panic("fire") -} - -func doNothing(req *Request, resp *Response) { -} diff --git a/Godeps/_workspace/src/github.com/evanphx/json-patch/merge_test.go b/Godeps/_workspace/src/github.com/evanphx/json-patch/merge_test.go deleted file mode 100644 index e9e68ceef..000000000 --- a/Godeps/_workspace/src/github.com/evanphx/json-patch/merge_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package jsonpatch - -import ( - "strings" - "testing" -) - -func mergePatch(doc, patch string) string { - out, err := MergePatch([]byte(doc), []byte(patch)) - - if err != nil { - panic(err) - } - - return string(out) -} - -func TestMergePatchReplaceKey(t *testing.T) { - doc := `{ "title": "hello" }` - pat := `{ "title": "goodbye" }` - - res := mergePatch(doc, pat) - - if !compareJSON(pat, res) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergePatchIgnoresOtherValues(t *testing.T) { - doc := `{ "title": "hello", "age": 18 }` - pat := `{ "title": "goodbye" }` - - res := mergePatch(doc, pat) - - exp := `{ "title": "goodbye", "age": 18 }` - - if !compareJSON(exp, res) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergePatchNilDoc(t *testing.T) { - doc := `{ "title": null }` - pat := `{ "title": {"foo": "bar"} }` - - res := mergePatch(doc, pat) - - exp := `{ "title": {"foo": "bar"} }` - - if !compareJSON(exp, res) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergePatchRecursesIntoObjects(t *testing.T) { - doc := `{ "person": { "title": "hello", "age": 18 } }` - pat := `{ "person": { "title": "goodbye" } }` - - res := mergePatch(doc, pat) - - exp := `{ "person": { "title": "goodbye", "age": 18 } }` - - if !compareJSON(exp, res) { - t.Fatalf("Key was not replaced") - } -} - -type nonObjectCases struct { - doc, pat, res string -} - -func TestMergePatchReplacesNonObjectsWholesale(t *testing.T) { - a1 := `[1]` - a2 := `[2]` - o1 := `{ "a": 1 }` - o2 := `{ "a": 2 }` - o3 := `{ "a": 1, "b": 1 }` - o4 := `{ "a": 2, "b": 1 }` - - cases := []nonObjectCases{ - {a1, a2, a2}, - {o1, a2, a2}, - {a1, o1, o1}, - {o3, o2, o4}, - } - - for _, c := range cases { - act := mergePatch(c.doc, c.pat) - - if !compareJSON(c.res, act) { - t.Errorf("whole object replacement failed") - } - } -} - -func TestMergePatchReturnsErrorOnBadJSON(t *testing.T) { - _, err := MergePatch([]byte(`[[[[`), []byte(`1`)) - - if err == nil { - t.Errorf("Did not return an error for bad json: %s", err) - } - - _, err = MergePatch([]byte(`1`), []byte(`[[[[`)) - - if err == nil { - t.Errorf("Did not return an error for bad json: %s", err) - } -} - -var rfcTests = []struct { - target string - patch string - expected string -}{ - // test cases from https://tools.ietf.org/html/rfc7386#appendix-A - {target: `{"a":"b"}`, patch: `{"a":"c"}`, expected: `{"a":"c"}`}, - {target: `{"a":"b"}`, patch: `{"b":"c"}`, expected: `{"a":"b","b":"c"}`}, - {target: `{"a":"b"}`, patch: `{"a":null}`, expected: `{}`}, - {target: `{"a":"b","b":"c"}`, patch: `{"a":null}`, expected: `{"b":"c"}`}, - {target: `{"a":["b"]}`, patch: `{"a":"c"}`, expected: `{"a":"c"}`}, - {target: `{"a":"c"}`, patch: `{"a":["b"]}`, expected: `{"a":["b"]}`}, - {target: `{"a":{"b": "c"}}`, patch: `{"a": {"b": "d","c": null}}`, expected: `{"a":{"b":"d"}}`}, - {target: `{"a":[{"b":"c"}]}`, patch: `{"a":[1]}`, expected: `{"a":[1]}`}, - {target: `["a","b"]`, patch: `["c","d"]`, expected: `["c","d"]`}, - {target: `{"a":"b"}`, patch: `["c"]`, expected: `["c"]`}, - // {target: `{"a":"foo"}`, patch: `null`, expected: `null`}, - // {target: `{"a":"foo"}`, patch: `"bar"`, expected: `"bar"`}, - {target: `{"e":null}`, patch: `{"a":1}`, expected: `{"a":1,"e":null}`}, - {target: `[1,2]`, patch: `{"a":"b","c":null}`, expected: `{"a":"b"}`}, - {target: `{}`, patch: `{"a":{"bb":{"ccc":null}}}`, expected: `{"a":{"bb":{}}}`}, -} - -func TestMergePatchRFCCases(t *testing.T) { - for i, c := range rfcTests { - out := mergePatch(c.target, c.patch) - - if !compareJSON(out, c.expected) { - t.Errorf("case[%d], patch '%s' did not apply properly to '%s'. expected:\n'%s'\ngot:\n'%s'", i, c.patch, c.target, c.expected, out) - } - } -} - -var rfcFailTests = ` - {"a":"foo"} | null - {"a":"foo"} | "bar" -` - -func TestMergePatchFailRFCCases(t *testing.T) { - tests := strings.Split(rfcFailTests, "\n") - - for _, c := range tests { - if strings.TrimSpace(c) == "" { - continue - } - - parts := strings.SplitN(c, "|", 2) - - doc := strings.TrimSpace(parts[0]) - pat := strings.TrimSpace(parts[1]) - - out, err := MergePatch([]byte(doc), []byte(pat)) - - if err != errBadJSONPatch { - t.Errorf("error not returned properly: %s, %s", err, string(out)) - } - } - -} - -func TestMergeReplaceKey(t *testing.T) { - doc := `{ "title": "hello", "nested": {"one": 1, "two": 2} }` - pat := `{ "title": "goodbye", "nested": {"one": 2, "two": 2} }` - - exp := `{ "title": "goodbye", "nested": {"one": 2} }` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(exp, string(res)) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergeGetArray(t *testing.T) { - doc := `{ "title": "hello", "array": ["one", "two"], "notmatch": [1, 2, 3] }` - pat := `{ "title": "hello", "array": ["one", "two", "three"], "notmatch": [1, 2, 3] }` - - exp := `{ "array": ["one", "two", "three"] }` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(exp, string(res)) { - t.Fatalf("Array was not added") - } -} - -func TestMergeGetObjArray(t *testing.T) { - doc := `{ "title": "hello", "array": [{"banana": true}, {"evil": false}], "notmatch": [{"one":1}, {"two":2}, {"three":3}] }` - pat := `{ "title": "hello", "array": [{"banana": false}, {"evil": true}], "notmatch": [{"one":1}, {"two":2}, {"three":3}] }` - - exp := `{ "array": [{"banana": false}, {"evil": true}] }` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(exp, string(res)) { - t.Fatalf("Object array was not added") - } -} - -func TestMergeDeleteKey(t *testing.T) { - doc := `{ "title": "hello", "nested": {"one": 1, "two": 2} }` - pat := `{ "title": "hello", "nested": {"one": 1} }` - - exp := `{"nested":{"two":null}}` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if exp != string(res) { - t.Fatalf("Key was not removed") - } -} - -func TestMergeEmptyArray(t *testing.T) { - doc := `{ "array": null }` - pat := `{ "array": [] }` - - exp := `{"array":[]}` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if exp != string(res) { - t.Fatalf("Key was not removed") - } -} - -func TestMergeObjArray(t *testing.T) { - doc := `{ "array": [ {"a": {"b": 2}}, {"a": {"b": 3}} ]}` - exp := `{}` - - res, err := CreateMergePatch([]byte(doc), []byte(doc)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if exp != string(res) { - t.Fatalf("Array was not empty, was " + string(res)) - } -} - -func TestMergeComplexMatch(t *testing.T) { - doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` - empty := `{}` - res, err := CreateMergePatch([]byte(doc), []byte(doc)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if empty != string(res) { - t.Fatalf("Did not get empty result, was:%s", string(res)) - } -} - -func TestMergeComplexAddAll(t *testing.T) { - doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` - empty := `{}` - res, err := CreateMergePatch([]byte(empty), []byte(doc)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(doc, string(res)) { - t.Fatalf("Did not get everything as, it was:\n%s", string(res)) - } -} - -func TestMergeComplexRemoveAll(t *testing.T) { - doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` - exp := `{"a":null,"f":null,"hello":null,"i":null,"n":null,"nested":null,"pi":null,"t":null}` - empty := `{}` - res, err := CreateMergePatch([]byte(doc), []byte(empty)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if exp != string(res) { - t.Fatalf("Did not get result, was:%s", string(res)) - } - - // FIXME: Crashes if using compareJSON like this: - /* - if !compareJSON(doc, string(res)) { - t.Fatalf("Did not get everything as, it was:\n%s", string(res)) - } - */ -} diff --git a/Godeps/_workspace/src/github.com/evanphx/json-patch/patch_test.go b/Godeps/_workspace/src/github.com/evanphx/json-patch/patch_test.go deleted file mode 100644 index 493c4f165..000000000 --- a/Godeps/_workspace/src/github.com/evanphx/json-patch/patch_test.go +++ /dev/null @@ -1,234 +0,0 @@ -package jsonpatch - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "testing" -) - -func reformatJSON(j string) string { - buf := new(bytes.Buffer) - - json.Indent(buf, []byte(j), "", " ") - - return buf.String() -} - -func compareJSON(a, b string) bool { - // return Equal([]byte(a), []byte(b)) - - var obj_a, obj_b map[string]interface{} - json.Unmarshal([]byte(a), &obj_a) - json.Unmarshal([]byte(b), &obj_b) - - // fmt.Printf("Comparing %#v\nagainst %#v\n", obj_a, obj_b) - return reflect.DeepEqual(obj_a, obj_b) -} - -func applyPatch(doc, patch string) (string, error) { - obj, err := DecodePatch([]byte(patch)) - - if err != nil { - panic(err) - } - - out, err := obj.Apply([]byte(doc)) - - if err != nil { - return "", err - } - - return string(out), nil -} - -type Case struct { - doc, patch, result string -} - -var Cases = []Case{ - { - `{ "foo": "bar"}`, - `[ - { "op": "add", "path": "/baz", "value": "qux" } - ]`, - `{ - "baz": "qux", - "foo": "bar" - }`, - }, - { - `{ "foo": [ "bar", "baz" ] }`, - `[ - { "op": "add", "path": "/foo/1", "value": "qux" } - ]`, - `{ "foo": [ "bar", "qux", "baz" ] }`, - }, - { - `{ "baz": "qux", "foo": "bar" }`, - `[ { "op": "remove", "path": "/baz" } ]`, - `{ "foo": "bar" }`, - }, - { - `{ "foo": [ "bar", "qux", "baz" ] }`, - `[ { "op": "remove", "path": "/foo/1" } ]`, - `{ "foo": [ "bar", "baz" ] }`, - }, - { - `{ "baz": "qux", "foo": "bar" }`, - `[ { "op": "replace", "path": "/baz", "value": "boo" } ]`, - `{ "baz": "boo", "foo": "bar" }`, - }, - { - `{ - "foo": { - "bar": "baz", - "waldo": "fred" - }, - "qux": { - "corge": "grault" - } - }`, - `[ { "op": "move", "from": "/foo/waldo", "path": "/qux/thud" } ]`, - `{ - "foo": { - "bar": "baz" - }, - "qux": { - "corge": "grault", - "thud": "fred" - } - }`, - }, - { - `{ "foo": [ "all", "grass", "cows", "eat" ] }`, - `[ { "op": "move", "from": "/foo/1", "path": "/foo/3" } ]`, - `{ "foo": [ "all", "cows", "eat", "grass" ] }`, - }, - { - `{ "foo": "bar" }`, - `[ { "op": "add", "path": "/child", "value": { "grandchild": { } } } ]`, - `{ "foo": "bar", "child": { "grandchild": { } } }`, - }, - { - `{ "foo": ["bar"] }`, - `[ { "op": "add", "path": "/foo/-", "value": ["abc", "def"] } ]`, - `{ "foo": ["bar", ["abc", "def"]] }`, - }, - { - `{ "foo": "bar", "qux": { "baz": 1, "bar": null } }`, - `[ { "op": "remove", "path": "/qux/bar" } ]`, - `{ "foo": "bar", "qux": { "baz": 1 } }`, - }, -} - -type BadCase struct { - doc, patch string -} - -var MutationTestCases = []BadCase{ - { - `{ "foo": "bar", "qux": { "baz": 1, "bar": null } }`, - `[ { "op": "remove", "path": "/qux/bar" } ]`, - }, -} - -var BadCases = []BadCase{ - { - `{ "foo": "bar" }`, - `[ { "op": "add", "path": "/baz/bat", "value": "qux" } ]`, - }, -} - -func TestAllCases(t *testing.T) { - for _, c := range Cases { - out, err := applyPatch(c.doc, c.patch) - - if err != nil { - t.Errorf("Unable to apply patch: %s", err) - } - - if !compareJSON(out, c.result) { - t.Errorf("Patch did not apply. Expected:\n%s\n\nActual:\n%s", - reformatJSON(c.result), reformatJSON(out)) - } - } - - for _, c := range MutationTestCases { - out, err := applyPatch(c.doc, c.patch) - - if err != nil { - t.Errorf("Unable to apply patch: %s", err) - } - - if compareJSON(out, c.doc) { - t.Errorf("Patch did not apply. Original:\n%s\n\nPatched:\n%s", - reformatJSON(c.doc), reformatJSON(out)) - } - } - - for _, c := range BadCases { - _, err := applyPatch(c.doc, c.patch) - - if err == nil { - t.Errorf("Patch should have failed to apply but it did not") - } - } -} - -type TestCase struct { - doc, patch string - result bool - failedPath string -} - -var TestCases = []TestCase{ - { - `{ - "baz": "qux", - "foo": [ "a", 2, "c" ] - }`, - `[ - { "op": "test", "path": "/baz", "value": "qux" }, - { "op": "test", "path": "/foo/1", "value": 2 } - ]`, - true, - "", - }, - { - `{ "baz": "qux" }`, - `[ { "op": "test", "path": "/baz", "value": "bar" } ]`, - false, - "/baz", - }, - { - `{ - "baz": "qux", - "foo": ["a", 2, "c"] - }`, - `[ - { "op": "test", "path": "/baz", "value": "qux" }, - { "op": "test", "path": "/foo/1", "value": "c" } - ]`, - false, - "/foo/1", - }, -} - -func TestAllTest(t *testing.T) { - for _, c := range TestCases { - _, err := applyPatch(c.doc, c.patch) - - if c.result && err != nil { - t.Errorf("Testing failed when it should have passed: %s", err) - } else if !c.result && err == nil { - t.Errorf("Testing passed when it should have faild: %s", err) - } else if !c.result { - expected := fmt.Sprintf("Testing value %s failed", c.failedPath) - if err.Error() != expected { - t.Errorf("Testing failed as expected but invalid message: expected [%s], got [%s]", expected, err) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/field.go b/Godeps/_workspace/src/github.com/fatih/structs/field.go index 1178b0ca6..566f5497e 100644 --- a/Godeps/_workspace/src/github.com/fatih/structs/field.go +++ b/Godeps/_workspace/src/github.com/fatih/structs/field.go @@ -41,7 +41,7 @@ func (f *Field) IsExported() bool { return f.field.PkgPath == "" } -// IsZero returns true if the given field is not initalized (has a zero value). +// IsZero returns true if the given field is not initialized (has a zero value). // It panics if the field is not exported. func (f *Field) IsZero() bool { zero := reflect.Zero(f.value.Type()).Interface() @@ -60,8 +60,8 @@ func (f *Field) Kind() reflect.Kind { return f.value.Kind() } -// Set sets the field to given value v. It retuns an error if the field is not -// settable (not addresable or not exported) or if the given value's type +// Set sets the field to given value v. It returns an error if the field is not +// settable (not addressable or not exported) or if the given value's type // doesn't match the fields type. func (f *Field) Set(val interface{}) error { // we can't set unexported fields, so be sure this field is exported diff --git a/Godeps/_workspace/src/github.com/fatih/structs/field_test.go b/Godeps/_workspace/src/github.com/fatih/structs/field_test.go deleted file mode 100644 index b77e95120..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/field_test.go +++ /dev/null @@ -1,383 +0,0 @@ -package structs - -import ( - "reflect" - "testing" -) - -// A test struct that defines all cases -type Foo struct { - A string - B int `structs:"y"` - C bool `json:"c"` - d string // not exported - E *Baz - x string `xml:"x"` // not exported, with tag - Y []string - Z map[string]interface{} - *Bar // embedded -} - -type Baz struct { - A string - B int -} - -type Bar struct { - E string - F int - g []string -} - -func newStruct() *Struct { - b := &Bar{ - E: "example", - F: 2, - g: []string{"zeynep", "fatih"}, - } - - // B and x is not initialized for testing - f := &Foo{ - A: "gopher", - C: true, - d: "small", - E: nil, - Y: []string{"example"}, - Z: nil, - } - f.Bar = b - - return New(f) -} - -func TestField_Set(t *testing.T) { - s := newStruct() - - f := s.Field("A") - err := f.Set("fatih") - if err != nil { - t.Error(err) - } - - if f.Value().(string) != "fatih" { - t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih") - } - - f = s.Field("Y") - err = f.Set([]string{"override", "with", "this"}) - if err != nil { - t.Error(err) - } - - sliceLen := len(f.Value().([]string)) - if sliceLen != 3 { - t.Errorf("Setted values slice length is wrong: %d, want: %d", sliceLen, 3) - } - - f = s.Field("C") - err = f.Set(false) - if err != nil { - t.Error(err) - } - - if f.Value().(bool) { - t.Errorf("Setted value is wrong: %t want: %t", f.Value().(bool), false) - } - - // let's pass a different type - f = s.Field("A") - err = f.Set(123) // Field A is of type string, but we are going to pass an integer - if err == nil { - t.Error("Setting a field's value with a different type than the field's type should return an error") - } - - // old value should be still there :) - if f.Value().(string) != "fatih" { - t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih") - } - - // let's access an unexported field, which should give an error - f = s.Field("d") - err = f.Set("large") - if err != errNotExported { - t.Error(err) - } - - // let's set a pointer to struct - b := &Bar{ - E: "gopher", - F: 2, - } - - f = s.Field("Bar") - err = f.Set(b) - if err != nil { - t.Error(err) - } - - baz := &Baz{ - A: "helloWorld", - B: 42, - } - - f = s.Field("E") - err = f.Set(baz) - if err != nil { - t.Error(err) - } - - ba := s.Field("E").Value().(*Baz) - - if ba.A != "helloWorld" { - t.Errorf("could not set baz. Got: %s Want: helloWorld", ba.A) - } -} - -func TestField_Zero(t *testing.T) { - s := newStruct() - - f := s.Field("A") - err := f.Zero() - if err != nil { - t.Error(err) - } - - if f.Value().(string) != "" { - t.Errorf("Zeroed value is wrong: %s want: %s", f.Value().(string), "") - } - - f = s.Field("Y") - err = f.Zero() - if err != nil { - t.Error(err) - } - - sliceLen := len(f.Value().([]string)) - if sliceLen != 0 { - t.Errorf("Zeroed values slice length is wrong: %d, want: %d", sliceLen, 0) - } - - f = s.Field("C") - err = f.Zero() - if err != nil { - t.Error(err) - } - - if f.Value().(bool) { - t.Errorf("Zeroed value is wrong: %t want: %t", f.Value().(bool), false) - } - - // let's access an unexported field, which should give an error - f = s.Field("d") - err = f.Zero() - if err != errNotExported { - t.Error(err) - } - - f = s.Field("Bar") - err = f.Zero() - if err != nil { - t.Error(err) - } - - f = s.Field("E") - err = f.Zero() - if err != nil { - t.Error(err) - } - - v := s.Field("E").value - if !v.IsNil() { - t.Errorf("could not set baz. Got: %s Want: ", v.Interface()) - } -} - -func TestField(t *testing.T) { - s := newStruct() - - defer func() { - err := recover() - if err == nil { - t.Error("Retrieveing a non existing field from the struct should panic") - } - }() - - _ = s.Field("no-field") -} - -func TestField_Kind(t *testing.T) { - s := newStruct() - - f := s.Field("A") - if f.Kind() != reflect.String { - t.Errorf("Field A has wrong kind: %s want: %s", f.Kind(), reflect.String) - } - - f = s.Field("B") - if f.Kind() != reflect.Int { - t.Errorf("Field B has wrong kind: %s want: %s", f.Kind(), reflect.Int) - } - - // unexported - f = s.Field("d") - if f.Kind() != reflect.String { - t.Errorf("Field d has wrong kind: %s want: %s", f.Kind(), reflect.String) - } -} - -func TestField_Tag(t *testing.T) { - s := newStruct() - - v := s.Field("B").Tag("json") - if v != "" { - t.Errorf("Field's tag value of a non existing tag should return empty, got: %s", v) - } - - v = s.Field("C").Tag("json") - if v != "c" { - t.Errorf("Field's tag value of the existing field C should return 'c', got: %s", v) - } - - v = s.Field("d").Tag("json") - if v != "" { - t.Errorf("Field's tag value of a non exported field should return empty, got: %s", v) - } - - v = s.Field("x").Tag("xml") - if v != "x" { - t.Errorf("Field's tag value of a non exported field with a tag should return 'x', got: %s", v) - } - - v = s.Field("A").Tag("json") - if v != "" { - t.Errorf("Field's tag value of a existing field without a tag should return empty, got: %s", v) - } -} - -func TestField_Value(t *testing.T) { - s := newStruct() - - v := s.Field("A").Value() - val, ok := v.(string) - if !ok { - t.Errorf("Field's value of a A should be string") - } - - if val != "gopher" { - t.Errorf("Field's value of a existing tag should return 'gopher', got: %s", val) - } - - defer func() { - err := recover() - if err == nil { - t.Error("Value of a non exported field from the field should panic") - } - }() - - // should panic - _ = s.Field("d").Value() -} - -func TestField_IsEmbedded(t *testing.T) { - s := newStruct() - - if !s.Field("Bar").IsEmbedded() { - t.Errorf("Fields 'Bar' field is an embedded field") - } - - if s.Field("d").IsEmbedded() { - t.Errorf("Fields 'd' field is not an embedded field") - } -} - -func TestField_IsExported(t *testing.T) { - s := newStruct() - - if !s.Field("Bar").IsExported() { - t.Errorf("Fields 'Bar' field is an exported field") - } - - if !s.Field("A").IsExported() { - t.Errorf("Fields 'A' field is an exported field") - } - - if s.Field("d").IsExported() { - t.Errorf("Fields 'd' field is not an exported field") - } -} - -func TestField_IsZero(t *testing.T) { - s := newStruct() - - if s.Field("A").IsZero() { - t.Errorf("Fields 'A' field is an initialized field") - } - - if !s.Field("B").IsZero() { - t.Errorf("Fields 'B' field is not an initialized field") - } -} - -func TestField_Name(t *testing.T) { - s := newStruct() - - if s.Field("A").Name() != "A" { - t.Errorf("Fields 'A' field should have the name 'A'") - } -} - -func TestField_Field(t *testing.T) { - s := newStruct() - - e := s.Field("Bar").Field("E") - - val, ok := e.Value().(string) - if !ok { - t.Error("The value of the field 'e' inside 'Bar' struct should be string") - } - - if val != "example" { - t.Errorf("The value of 'e' should be 'example, got: %s", val) - } - - defer func() { - err := recover() - if err == nil { - t.Error("Field of a non existing nested struct should panic") - } - }() - - _ = s.Field("Bar").Field("e") -} - -func TestField_Fields(t *testing.T) { - s := newStruct() - fields := s.Field("Bar").Fields() - - if len(fields) != 3 { - t.Errorf("We expect 3 fields in embedded struct, was: %d", len(fields)) - } -} - -func TestField_FieldOk(t *testing.T) { - s := newStruct() - - b, ok := s.FieldOk("Bar") - if !ok { - t.Error("The field 'Bar' should exists.") - } - - e, ok := b.FieldOk("E") - if !ok { - t.Error("The field 'E' should exists.") - } - - val, ok := e.Value().(string) - if !ok { - t.Error("The value of the field 'e' inside 'Bar' struct should be string") - } - - if val != "example" { - t.Errorf("The value of 'e' should be 'example, got: %s", val) - } -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/structs.go b/Godeps/_workspace/src/github.com/fatih/structs/structs.go index a0b77e67d..7ac88369f 100644 --- a/Godeps/_workspace/src/github.com/fatih/structs/structs.go +++ b/Godeps/_workspace/src/github.com/fatih/structs/structs.go @@ -1,7 +1,11 @@ // Package structs contains various utilities functions to work with structs. package structs -import "reflect" +import ( + "fmt" + + "reflect" +) var ( // DefaultTagName is the default tag name for struct fields which provides @@ -42,6 +46,12 @@ func New(s interface{}) *Struct { // // Field is ignored by this package. // Field bool `structs:"-"` // +// A tag value with the content of "string" uses the stringer to get the value. Example: +// +// // The value will be output of Animal's String() func. +// // Map will panic if Animal does not implement String(). +// Field *Animal `structs:"field,string"` +// // A tag value with the option of "omitnested" stops iterating further if the type // is a struct. Example: // @@ -94,11 +104,24 @@ func (s *Struct) Map() map[string]interface{} { // map[string]interface{} too n := New(val.Interface()) n.TagName = s.TagName - finalVal = n.Map() + m := n.Map() + if len(m) == 0 { + finalVal = val.Interface() + } else { + finalVal = m + } } else { finalVal = val.Interface() } + if tagOpts.Has("string") { + s, ok := val.Interface().(fmt.Stringer) + if ok { + out[name] = s.String() + } + continue + } + out[name] = finalVal } @@ -148,6 +171,14 @@ func (s *Struct) Values() []interface{} { } } + if tagOpts.Has("string") { + s, ok := val.Interface().(fmt.Stringer) + if ok { + t = append(t, s.String()) + } + continue + } + if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { // look out for embedded structs, and convert them to a // []interface{} to be added to the final values slice diff --git a/Godeps/_workspace/src/github.com/fatih/structs/structs_example_test.go b/Godeps/_workspace/src/github.com/fatih/structs/structs_example_test.go deleted file mode 100644 index 32bb82937..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/structs_example_test.go +++ /dev/null @@ -1,351 +0,0 @@ -package structs - -import ( - "fmt" - "time" -) - -func ExampleNew() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - server := &Server{ - Name: "Arslan", - ID: 123456, - Enabled: true, - } - - s := New(server) - - fmt.Printf("Name : %v\n", s.Name()) - fmt.Printf("Values : %v\n", s.Values()) - fmt.Printf("Value of ID : %v\n", s.Field("ID").Value()) - // Output: - // Name : Server - // Values : [Arslan 123456 true] - // Value of ID : 123456 - -} - -func ExampleMap() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - s := &Server{ - Name: "Arslan", - ID: 123456, - Enabled: true, - } - - m := Map(s) - - fmt.Printf("%#v\n", m["Name"]) - fmt.Printf("%#v\n", m["ID"]) - fmt.Printf("%#v\n", m["Enabled"]) - // Output: - // "Arslan" - // 123456 - // true - -} - -func ExampleMap_tags() { - // Custom tags can change the map keys instead of using the fields name - type Server struct { - Name string `structs:"server_name"` - ID int32 `structs:"server_id"` - Enabled bool `structs:"enabled"` - } - - s := &Server{ - Name: "Zeynep", - ID: 789012, - } - - m := Map(s) - - // access them by the custom tags defined above - fmt.Printf("%#v\n", m["server_name"]) - fmt.Printf("%#v\n", m["server_id"]) - fmt.Printf("%#v\n", m["enabled"]) - // Output: - // "Zeynep" - // 789012 - // false - -} - -func ExampleMap_nested() { - // By default field with struct types are processed too. We can stop - // processing them via "omitnested" tag option. - type Server struct { - Name string `structs:"server_name"` - ID int32 `structs:"server_id"` - Time time.Time `structs:"time,omitnested"` // do not convert to map[string]interface{} - } - - const shortForm = "2006-Jan-02" - t, _ := time.Parse("2006-Jan-02", "2013-Feb-03") - - s := &Server{ - Name: "Zeynep", - ID: 789012, - Time: t, - } - - m := Map(s) - - // access them by the custom tags defined above - fmt.Printf("%v\n", m["server_name"]) - fmt.Printf("%v\n", m["server_id"]) - fmt.Printf("%v\n", m["time"].(time.Time)) - // Output: - // Zeynep - // 789012 - // 2013-02-03 00:00:00 +0000 UTC -} - -func ExampleMap_omitEmpty() { - // By default field with struct types of zero values are processed too. We - // can stop processing them via "omitempty" tag option. - type Server struct { - Name string `structs:",omitempty"` - ID int32 `structs:"server_id,omitempty"` - Location string - } - - // Only add location - s := &Server{ - Location: "Tokyo", - } - - m := Map(s) - - // map contains only the Location field - fmt.Printf("%v\n", m) - // Output: - // map[Location:Tokyo] -} - -func ExampleValues() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - s := &Server{ - Name: "Fatih", - ID: 135790, - Enabled: false, - } - - m := Values(s) - - fmt.Printf("Values: %+v\n", m) - // Output: - // Values: [Fatih 135790 false] -} - -func ExampleValues_omitEmpty() { - // By default field with struct types of zero values are processed too. We - // can stop processing them via "omitempty" tag option. - type Server struct { - Name string `structs:",omitempty"` - ID int32 `structs:"server_id,omitempty"` - Location string - } - - // Only add location - s := &Server{ - Location: "Ankara", - } - - m := Values(s) - - // values contains only the Location field - fmt.Printf("Values: %+v\n", m) - // Output: - // Values: [Ankara] -} - -func ExampleValues_tags() { - type Location struct { - City string - Country string - } - - type Server struct { - Name string - ID int32 - Enabled bool - Location Location `structs:"-"` // values from location are not included anymore - } - - s := &Server{ - Name: "Fatih", - ID: 135790, - Enabled: false, - Location: Location{City: "Ankara", Country: "Turkey"}, - } - - // Let get all values from the struct s. Note that we don't include values - // from the Location field - m := Values(s) - - fmt.Printf("Values: %+v\n", m) - // Output: - // Values: [Fatih 135790 false] -} - -func ExampleFields() { - type Access struct { - Name string - LastAccessed time.Time - Number int - } - - s := &Access{ - Name: "Fatih", - LastAccessed: time.Now(), - Number: 1234567, - } - - fields := Fields(s) - - for i, field := range fields { - fmt.Printf("[%d] %+v\n", i, field.Name()) - } - - // Output: - // [0] Name - // [1] LastAccessed - // [2] Number -} - -func ExampleFields_nested() { - type Person struct { - Name string - Number int - } - - type Access struct { - Person Person - HasPermission bool - LastAccessed time.Time - } - - s := &Access{ - Person: Person{Name: "fatih", Number: 1234567}, - LastAccessed: time.Now(), - HasPermission: true, - } - - // Let's get all fields from the struct s. - fields := Fields(s) - - for _, field := range fields { - if field.Name() == "Person" { - fmt.Printf("Access.Person.Name: %+v\n", field.Field("Name").Value()) - } - } - - // Output: - // Access.Person.Name: fatih -} - -func ExampleField() { - type Person struct { - Name string - Number int - } - - type Access struct { - Person Person - HasPermission bool - LastAccessed time.Time - } - - access := &Access{ - Person: Person{Name: "fatih", Number: 1234567}, - LastAccessed: time.Now(), - HasPermission: true, - } - - // Create a new Struct type - s := New(access) - - // Get the Field type for "Person" field - p := s.Field("Person") - - // Get the underlying "Name field" and print the value of it - name := p.Field("Name") - - fmt.Printf("Value of Person.Access.Name: %+v\n", name.Value()) - - // Output: - // Value of Person.Access.Name: fatih - -} - -func ExampleIsZero() { - type Server struct { - Name string - ID int32 - Enabled bool - } - - // Nothing is initalized - a := &Server{} - isZeroA := IsZero(a) - - // Name and Enabled is initialized, but not ID - b := &Server{ - Name: "Golang", - Enabled: true, - } - isZeroB := IsZero(b) - - fmt.Printf("%#v\n", isZeroA) - fmt.Printf("%#v\n", isZeroB) - // Output: - // true - // false -} - -func ExampleHasZero() { - // Let's define an Access struct. Note that the "Enabled" field is not - // going to be checked because we added the "structs" tag to the field. - type Access struct { - Name string - LastAccessed time.Time - Number int - Enabled bool `structs:"-"` - } - - // Name and Number is not initialized. - a := &Access{ - LastAccessed: time.Now(), - } - hasZeroA := HasZero(a) - - // Name and Number is initialized. - b := &Access{ - Name: "Fatih", - LastAccessed: time.Now(), - Number: 12345, - } - hasZeroB := HasZero(b) - - fmt.Printf("%#v\n", hasZeroA) - fmt.Printf("%#v\n", hasZeroB) - // Output: - // true - // false -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go b/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go deleted file mode 100644 index 14e3de72f..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go +++ /dev/null @@ -1,898 +0,0 @@ -package structs - -import ( - "fmt" - "reflect" - "testing" - "time" -) - -func TestMapNonStruct(t *testing.T) { - foo := []string{"foo"} - - defer func() { - err := recover() - if err == nil { - t.Error("Passing a non struct into Map should panic") - } - }() - - // this should panic. We are going to recover and and test it - _ = Map(foo) -} - -func TestStructIndexes(t *testing.T) { - type C struct { - something int - Props map[string]interface{} - } - - defer func() { - err := recover() - if err != nil { - fmt.Printf("err %+v\n", err) - t.Error("Using mixed indexes should not panic") - } - }() - - // They should not panic - _ = Map(&C{}) - _ = Fields(&C{}) - _ = Values(&C{}) - _ = IsZero(&C{}) - _ = HasZero(&C{}) -} - -func TestMap(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - a := Map(T) - - if typ := reflect.TypeOf(a).Kind(); typ != reflect.Map { - t.Errorf("Map should return a map type, got: %v", typ) - } - - // we have three fields - if len(a) != 3 { - t.Errorf("Map should return a map of len 3, got: %d", len(a)) - } - - inMap := func(val interface{}) bool { - for _, v := range a { - if reflect.DeepEqual(v, val) { - return true - } - } - - return false - } - - for _, val := range []interface{}{"a-value", 2, true} { - if !inMap(val) { - t.Errorf("Map should have the value %v", val) - } - } - -} - -func TestMap_Tag(t *testing.T) { - var T = struct { - A string `structs:"x"` - B int `structs:"y"` - C bool `structs:"z"` - }{ - A: "a-value", - B: 2, - C: true, - } - - a := Map(T) - - inMap := func(key interface{}) bool { - for k := range a { - if reflect.DeepEqual(k, key) { - return true - } - } - return false - } - - for _, key := range []string{"x", "y", "z"} { - if !inMap(key) { - t.Errorf("Map should have the key %v", key) - } - } - -} - -func TestMap_CustomTag(t *testing.T) { - var T = struct { - A string `json:"x"` - B int `json:"y"` - C bool `json:"z"` - D struct { - E string `json:"jkl"` - } `json:"nested"` - }{ - A: "a-value", - B: 2, - C: true, - } - T.D.E = "e-value" - - s := New(T) - s.TagName = "json" - - a := s.Map() - - inMap := func(key interface{}) bool { - for k := range a { - if reflect.DeepEqual(k, key) { - return true - } - } - return false - } - - for _, key := range []string{"x", "y", "z"} { - if !inMap(key) { - t.Errorf("Map should have the key %v", key) - } - } - - nested, ok := a["nested"].(map[string]interface{}) - if !ok { - t.Fatalf("Map should contain the D field that is tagged as 'nested'") - } - - e, ok := nested["jkl"].(string) - if !ok { - t.Fatalf("Map should contain the D.E field that is tagged as 'jkl'") - } - - if e != "e-value" { - t.Errorf("D.E field should be equal to 'e-value', got: '%v'", e) - } - -} - -func TestMap_MultipleCustomTag(t *testing.T) { - var A = struct { - X string `aa:"ax"` - }{"a_value"} - - aStruct := New(A) - aStruct.TagName = "aa" - - var B = struct { - X string `bb:"bx"` - }{"b_value"} - - bStruct := New(B) - bStruct.TagName = "bb" - - a, b := aStruct.Map(), bStruct.Map() - if !reflect.DeepEqual(a, map[string]interface{}{"ax": "a_value"}) { - t.Error("Map should have field ax with value a_value") - } - - if !reflect.DeepEqual(b, map[string]interface{}{"bx": "b_value"}) { - t.Error("Map should have field bx with value b_value") - } -} - -func TestMap_OmitEmpty(t *testing.T) { - type A struct { - Name string - Value string `structs:",omitempty"` - Time time.Time `structs:",omitempty"` - } - a := A{} - - m := Map(a) - - _, ok := m["Value"].(map[string]interface{}) - if ok { - t.Error("Map should not contain the Value field that is tagged as omitempty") - } - - _, ok = m["Time"].(map[string]interface{}) - if ok { - t.Error("Map should not contain the Time field that is tagged as omitempty") - } -} - -func TestMap_OmitNested(t *testing.T) { - type A struct { - Name string - Value string - Time time.Time `structs:",omitnested"` - } - a := A{Time: time.Now()} - - type B struct { - Desc string - A A - } - b := &B{A: a} - - m := Map(b) - - in, ok := m["A"].(map[string]interface{}) - if !ok { - t.Error("Map nested structs is not available in the map") - } - - // should not happen - if _, ok := in["Time"].(map[string]interface{}); ok { - t.Error("Map nested struct should omit recursiving parsing of Time") - } - - if _, ok := in["Time"].(time.Time); !ok { - t.Error("Map nested struct should stop parsing of Time at is current value") - } -} - -func TestMap_Nested(t *testing.T) { - type A struct { - Name string - } - a := &A{Name: "example"} - - type B struct { - A *A - } - b := &B{A: a} - - m := Map(b) - - if typ := reflect.TypeOf(m).Kind(); typ != reflect.Map { - t.Errorf("Map should return a map type, got: %v", typ) - } - - in, ok := m["A"].(map[string]interface{}) - if !ok { - t.Error("Map nested structs is not available in the map") - } - - if name := in["Name"].(string); name != "example" { - t.Errorf("Map nested struct's name field should give example, got: %s", name) - } -} - -func TestMap_Anonymous(t *testing.T) { - type A struct { - Name string - } - a := &A{Name: "example"} - - type B struct { - *A - } - b := &B{} - b.A = a - - m := Map(b) - - if typ := reflect.TypeOf(m).Kind(); typ != reflect.Map { - t.Errorf("Map should return a map type, got: %v", typ) - } - - in, ok := m["A"].(map[string]interface{}) - if !ok { - t.Error("Embedded structs is not available in the map") - } - - if name := in["Name"].(string); name != "example" { - t.Errorf("Embedded A struct's Name field should give example, got: %s", name) - } -} - -func TestStruct(t *testing.T) { - var T = struct{}{} - - if !IsStruct(T) { - t.Errorf("T should be a struct, got: %T", T) - } - - if !IsStruct(&T) { - t.Errorf("T should be a struct, got: %T", T) - } - -} - -func TestValues(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - s := Values(T) - - if typ := reflect.TypeOf(s).Kind(); typ != reflect.Slice { - t.Errorf("Values should return a slice type, got: %v", typ) - } - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"a-value", 2, true} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestValues_OmitEmpty(t *testing.T) { - type A struct { - Name string - Value int `structs:",omitempty"` - } - - a := A{Name: "example"} - s := Values(a) - - if len(s) != 1 { - t.Errorf("Values of omitted empty fields should be not counted") - } - - if s[0].(string) != "example" { - t.Errorf("Values of omitted empty fields should left the value example") - } -} - -func TestValues_OmitNested(t *testing.T) { - type A struct { - Name string - Value int - } - - a := A{ - Name: "example", - Value: 123, - } - - type B struct { - A A `structs:",omitnested"` - C int - } - b := &B{A: a, C: 123} - - s := Values(b) - - if len(s) != 2 { - t.Errorf("Values of omitted nested struct should be not counted") - } - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{123, a} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestValues_Nested(t *testing.T) { - type A struct { - Name string - } - a := A{Name: "example"} - - type B struct { - A A - C int - } - b := &B{A: a, C: 123} - - s := Values(b) - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"example", 123} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestValues_Anonymous(t *testing.T) { - type A struct { - Name string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - s := Values(b) - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"example", 123} { - if !inSlice(val) { - t.Errorf("Values should have the value %v", val) - } - } -} - -func TestNames(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - s := Names(T) - - if len(s) != 3 { - t.Errorf("Names should return a slice of len 3, got: %d", len(s)) - } - - inSlice := func(val string) bool { - for _, v := range s { - if reflect.DeepEqual(v, val) { - return true - } - } - return false - } - - for _, val := range []string{"A", "B", "C"} { - if !inSlice(val) { - t.Errorf("Names should have the value %v", val) - } - } -} - -func TestFields(t *testing.T) { - var T = struct { - A string - B int - C bool - }{ - A: "a-value", - B: 2, - C: true, - } - - s := Fields(T) - - if len(s) != 3 { - t.Errorf("Fields should return a slice of len 3, got: %d", len(s)) - } - - inSlice := func(val string) bool { - for _, v := range s { - if reflect.DeepEqual(v.Name(), val) { - return true - } - } - return false - } - - for _, val := range []string{"A", "B", "C"} { - if !inSlice(val) { - t.Errorf("Fields should have the value %v", val) - } - } -} - -func TestFields_OmitNested(t *testing.T) { - type A struct { - Name string - Enabled bool - } - a := A{Name: "example"} - - type B struct { - A A - C int - Value string `structs:"-"` - Number int - } - b := &B{A: a, C: 123} - - s := Fields(b) - - if len(s) != 3 { - t.Errorf("Fields should omit nested struct. Expecting 2 got: %d", len(s)) - } - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v.Name(), val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"A", "C"} { - if !inSlice(val) { - t.Errorf("Fields should have the value %v", val) - } - } -} - -func TestFields_Anonymous(t *testing.T) { - type A struct { - Name string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - s := Fields(b) - - inSlice := func(val interface{}) bool { - for _, v := range s { - if reflect.DeepEqual(v.Name(), val) { - return true - } - } - return false - } - - for _, val := range []interface{}{"A", "C"} { - if !inSlice(val) { - t.Errorf("Fields should have the value %v", val) - } - } -} - -func TestIsZero(t *testing.T) { - var T = struct { - A string - B int - C bool `structs:"-"` - D []string - }{} - - ok := IsZero(T) - if !ok { - t.Error("IsZero should return true because none of the fields are initialized.") - } - - var X = struct { - A string - F *bool - }{ - A: "a-value", - } - - ok = IsZero(X) - if ok { - t.Error("IsZero should return false because A is initialized") - } - - var Y = struct { - A string - B int - }{ - A: "a-value", - B: 123, - } - - ok = IsZero(Y) - if ok { - t.Error("IsZero should return false because A and B is initialized") - } -} - -func TestIsZero_OmitNested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A `structs:",omitnested"` - C int - } - b := &B{A: a, C: 123} - - ok := IsZero(b) - if ok { - t.Error("IsZero should return false because A, B and C are initialized") - } - - aZero := A{} - bZero := &B{A: aZero} - - ok = IsZero(bZero) - if !ok { - t.Error("IsZero should return true because neither A nor B is initialized") - } - -} - -func TestIsZero_Nested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A - C int - } - b := &B{A: a, C: 123} - - ok := IsZero(b) - if ok { - t.Error("IsZero should return false because A, B and C are initialized") - } - - aZero := A{} - bZero := &B{A: aZero} - - ok = IsZero(bZero) - if !ok { - t.Error("IsZero should return true because neither A nor B is initialized") - } - -} - -func TestIsZero_Anonymous(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - ok := IsZero(b) - if ok { - t.Error("IsZero should return false because A, B and C are initialized") - } - - aZero := A{} - bZero := &B{} - bZero.A = aZero - - ok = IsZero(bZero) - if !ok { - t.Error("IsZero should return true because neither A nor B is initialized") - } -} - -func TestHasZero(t *testing.T) { - var T = struct { - A string - B int - C bool `structs:"-"` - D []string - }{ - A: "a-value", - B: 2, - } - - ok := HasZero(T) - if !ok { - t.Error("HasZero should return true because A and B are initialized.") - } - - var X = struct { - A string - F *bool - }{ - A: "a-value", - } - - ok = HasZero(X) - if !ok { - t.Error("HasZero should return true because A is initialized") - } - - var Y = struct { - A string - B int - }{ - A: "a-value", - B: 123, - } - - ok = HasZero(Y) - if ok { - t.Error("HasZero should return false because A and B is initialized") - } -} - -func TestHasZero_OmitNested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A `structs:",omitnested"` - C int - } - b := &B{A: a, C: 123} - - // Because the Field A inside B is omitted HasZero should return false - // because it will stop iterating deeper andnot going to lookup for D - ok := HasZero(b) - if ok { - t.Error("HasZero should return false because A and C are initialized") - } -} - -func TestHasZero_Nested(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A A - C int - } - b := &B{A: a, C: 123} - - ok := HasZero(b) - if !ok { - t.Error("HasZero should return true because D is not initialized") - } -} - -func TestHasZero_Anonymous(t *testing.T) { - type A struct { - Name string - D string - } - a := A{Name: "example"} - - type B struct { - A - C int - } - b := &B{C: 123} - b.A = a - - ok := HasZero(b) - if !ok { - t.Error("HasZero should return false because D is not initialized") - } -} - -func TestName(t *testing.T) { - type Foo struct { - A string - B bool - } - f := &Foo{} - - n := Name(f) - if n != "Foo" { - t.Errorf("Name should return Foo, got: %s", n) - } - - unnamed := struct{ Name string }{Name: "Cihangir"} - m := Name(unnamed) - if m != "" { - t.Errorf("Name should return empty string for unnamed struct, got: %s", n) - } - - defer func() { - err := recover() - if err == nil { - t.Error("Name should panic if a non struct is passed") - } - }() - - Name([]string{}) -} - -func TestNestedNilPointer(t *testing.T) { - type Collar struct { - Engraving string - } - - type Dog struct { - Name string - Collar *Collar - } - - type Person struct { - Name string - Dog *Dog - } - - person := &Person{ - Name: "John", - } - - personWithDog := &Person{ - Name: "Ron", - Dog: &Dog{ - Name: "Rover", - }, - } - - personWithDogWithCollar := &Person{ - Name: "Kon", - Dog: &Dog{ - Name: "Ruffles", - Collar: &Collar{ - Engraving: "If lost, call Kon", - }, - }, - } - - defer func() { - err := recover() - if err != nil { - fmt.Printf("err %+v\n", err) - t.Error("Internal nil pointer should not panic") - } - }() - - _ = Map(person) // Panics - _ = Map(personWithDog) // Panics - _ = Map(personWithDogWithCollar) // Doesn't panic -} diff --git a/Godeps/_workspace/src/github.com/fatih/structs/tags_test.go b/Godeps/_workspace/src/github.com/fatih/structs/tags_test.go deleted file mode 100644 index 5d12724f1..000000000 --- a/Godeps/_workspace/src/github.com/fatih/structs/tags_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package structs - -import "testing" - -func TestParseTag_Name(t *testing.T) { - tags := []struct { - tag string - has bool - }{ - {"", false}, - {"name", true}, - {"name,opt", true}, - {"name , opt, opt2", false}, // has a single whitespace - {", opt, opt2", false}, - } - - for _, tag := range tags { - name, _ := parseTag(tag.tag) - - if (name != "name") && tag.has { - t.Errorf("Parse tag should return name: %#v", tag) - } - } -} - -func TestParseTag_Opts(t *testing.T) { - tags := []struct { - opts string - has bool - }{ - {"name", false}, - {"name,opt", true}, - {"name , opt, opt2", false}, // has a single whitespace - {",opt, opt2", true}, - {", opt3, opt4", false}, - } - - // search for "opt" - for _, tag := range tags { - _, opts := parseTag(tag.opts) - - if opts.Has("opt") != tag.has { - t.Errorf("Tag opts should have opt: %#v", tag) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/.travis.yml b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/.travis.yml index 6b9cd96ae..4a6a01fb7 100644 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/.travis.yml +++ b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/.travis.yml @@ -4,7 +4,7 @@ go: - 1.3.3 - 1.4.2 - 1.5.3 - - 1.6beta2 + - 1.6rc2 - tip env: - GOARCH=amd64 DOCKER_VERSION=1.7.1 @@ -13,6 +13,8 @@ env: - GOARCH=386 DOCKER_VERSION=1.8.3 - GOARCH=amd64 DOCKER_VERSION=1.9.1 - GOARCH=386 DOCKER_VERSION=1.9.1 + - GOARCH=amd64 DOCKER_VERSION=1.10.0 + - GOARCH=386 DOCKER_VERSION=1.10.0 install: - make prepare_docker script: diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/AUTHORS b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/AUTHORS index 988849612..0c42ae344 100644 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/AUTHORS +++ b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/AUTHORS @@ -50,6 +50,7 @@ Flavia Missi Francisco Souza Grégoire Delattre Guillermo Álvarez Fernández +Harry Zhang He Simei Ivan Mikushin James Bardin @@ -111,6 +112,7 @@ Summer Mousa Sunjin Lee Tarsis Azevedo Tim Schindler +Timothy St. Clair Tobi Knaup Tom Wilkie Tonic diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/Makefile b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/Makefile index 205d8f3c2..7a94eaa1e 100644 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/Makefile +++ b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/Makefile @@ -41,7 +41,7 @@ prepare_docker: sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" | sudo tee /etc/apt/sources.list.d/docker.list sudo apt-get update - sudo apt-get install docker-engine=$(DOCKER_VERSION)-0~$(shell lsb_release -cs) -y --force-yes + sudo apt-get install docker-engine=$(DOCKER_VERSION)-0~$(shell lsb_release -cs) -y --force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" pretest: lint vet fmtcheck diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/auth_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/auth_test.go deleted file mode 100644 index e53b17601..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/auth_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/base64" - "fmt" - "net/http" - "strings" - "testing" -) - -func TestAuthLegacyConfig(t *testing.T) { - auth := base64.StdEncoding.EncodeToString([]byte("user:pa:ss")) - read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth)) - ac, err := NewAuthConfigurations(read) - if err != nil { - t.Error(err) - } - c, ok := ac.Configs["docker.io"] - if !ok { - t.Error("NewAuthConfigurations: Expected Configs to contain docker.io") - } - if got, want := c.Email, "user@example.com"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Username, "user"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Password, "pa:ss"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.ServerAddress, "docker.io"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got) - } -} - -func TestAuthBadConfig(t *testing.T) { - auth := base64.StdEncoding.EncodeToString([]byte("userpass")) - read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth)) - ac, err := NewAuthConfigurations(read) - if err != ErrCannotParseDockercfg { - t.Errorf("Incorrect error returned %v\n", err) - } - if ac != nil { - t.Errorf("Invalid auth configuration returned, should be nil %v\n", ac) - } -} - -func TestAuthConfig(t *testing.T) { - auth := base64.StdEncoding.EncodeToString([]byte("user:pass")) - read := strings.NewReader(fmt.Sprintf(`{"auths":{"docker.io":{"auth":"%s","email":"user@example.com"}}}`, auth)) - ac, err := NewAuthConfigurations(read) - if err != nil { - t.Error(err) - } - c, ok := ac.Configs["docker.io"] - if !ok { - t.Error("NewAuthConfigurations: Expected Configs to contain docker.io") - } - if got, want := c.Email, "user@example.com"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Username, "user"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Password, "pass"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.ServerAddress, "docker.io"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got) - } -} - -func TestAuthCheck(t *testing.T) { - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - if err := client.AuthCheck(nil); err == nil { - t.Fatalf("expected error on nil auth config") - } - // test good auth - if err := client.AuthCheck(&AuthConfiguration{}); err != nil { - t.Fatal(err) - } - *fakeRT = FakeRoundTripper{status: http.StatusUnauthorized} - if err := client.AuthCheck(&AuthConfiguration{}); err == nil { - t.Fatal("expected failure from unauthorized auth") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/build_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/build_test.go deleted file mode 100644 index c9640f205..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/build_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package docker - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "os" - "reflect" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive" -) - -func TestBuildImageMultipleContextsError(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - InputStream: &buf, - OutputStream: &buf, - ContextDir: "testing/data", - } - err := client.BuildImage(opts) - if err != ErrMultipleContexts { - t.Errorf("BuildImage: providing both InputStream and ContextDir should produce an error") - } -} - -func TestBuildImageContextDirDockerignoreParsing(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - - if err := os.Symlink("doesnotexist", "testing/data/symlink"); err != nil { - t.Errorf("error creating symlink on demand: %s", err) - } - defer func() { - if err := os.Remove("testing/data/symlink"); err != nil { - t.Errorf("error removing symlink on demand: %s", err) - } - }() - - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - OutputStream: &buf, - ContextDir: "testing/data", - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - reqBody := fakeRT.requests[0].Body - tmpdir, err := unpackBodyTarball(reqBody) - if err != nil { - t.Fatal(err) - } - - defer func() { - if err := os.RemoveAll(tmpdir); err != nil { - t.Fatal(err) - } - }() - - files, err := ioutil.ReadDir(tmpdir) - if err != nil { - t.Fatal(err) - } - - foundFiles := []string{} - for _, file := range files { - foundFiles = append(foundFiles, file.Name()) - } - - expectedFiles := []string{ - ".dockerignore", - "Dockerfile", - "barfile", - "ca.pem", - "cert.pem", - "key.pem", - "server.pem", - "serverkey.pem", - "symlink", - } - - if !reflect.DeepEqual(expectedFiles, foundFiles) { - t.Errorf( - "BuildImage: incorrect files sent in tarball to docker server\nexpected %+v, found %+v", - expectedFiles, foundFiles, - ) - } -} - -func TestBuildImageSendXRegistryConfig(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - OutputStream: &buf, - ContextDir: "testing/data", - AuthConfigs: AuthConfigurations{ - Configs: map[string]AuthConfiguration{ - "quay.io": { - Username: "foo", - Password: "bar", - Email: "baz", - ServerAddress: "quay.io", - }, - }, - }, - } - - encodedConfig := "eyJjb25maWdzIjp7InF1YXkuaW8iOnsidXNlcm5hbWUiOiJmb28iLCJwYXNzd29yZCI6ImJhciIsImVtYWlsIjoiYmF6Iiwic2VydmVyYWRkcmVzcyI6InF1YXkuaW8ifX19Cg==" - - if err := client.BuildImage(opts); err != nil { - t.Fatal(err) - } - - xRegistryConfig := fakeRT.requests[0].Header["X-Registry-Config"][0] - if xRegistryConfig != encodedConfig { - t.Errorf( - "BuildImage: X-Registry-Config not set currectly: expected %q, got %q", - encodedConfig, - xRegistryConfig, - ) - } -} - -func unpackBodyTarball(req io.ReadCloser) (tmpdir string, err error) { - tmpdir, err = ioutil.TempDir("", "go-dockerclient-test") - if err != nil { - return - } - err = archive.Untar(req, tmpdir, &archive.TarOptions{ - Compression: archive.Uncompressed, - NoLchown: true, - }) - return -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/change_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/change_test.go deleted file mode 100644 index 9418b183c..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/change_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import "testing" - -func TestChangeString(t *testing.T) { - var tests = []struct { - change Change - expected string - }{ - {Change{"/etc/passwd", ChangeModify}, "C /etc/passwd"}, - {Change{"/etc/passwd", ChangeAdd}, "A /etc/passwd"}, - {Change{"/etc/passwd", ChangeDelete}, "D /etc/passwd"}, - {Change{"/etc/passwd", 33}, " /etc/passwd"}, - } - for _, tt := range tests { - if got := tt.change.String(); got != tt.expected { - t.Errorf("Change.String(): want %q. Got %q.", tt.expected, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client.go index 3a7d755f5..114fb87b7 100644 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client.go +++ b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client.go @@ -60,7 +60,8 @@ func NewAPIVersion(input string) (APIVersion, error) { if !strings.Contains(input, ".") { return nil, fmt.Errorf("Unable to parse version %q", input) } - arr := strings.Split(input, ".") + raw := strings.Split(input, "-") + arr := strings.Split(raw[0], ".") ret := make(APIVersion, len(arr)) var err error for i, val := range arr { @@ -586,7 +587,7 @@ func (c *Client) hijack(method, path string, hijackOptions hijackOptions) (Close if err != nil { return nil, err } - req.Header.Set("Content-Type", "plain/text") + req.Header.Set("Content-Type", "application/json") req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", "tcp") protocol := c.endpointURL.Scheme diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client_test.go deleted file mode 100644 index 721352757..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client_test.go +++ /dev/null @@ -1,518 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bytes" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "path/filepath" - "reflect" - "strconv" - "strings" - "testing" - "time" - - "github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp" -) - -func TestNewAPIClient(t *testing.T) { - endpoint := "http://localhost:4243" - client, err := NewClient(endpoint) - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - // test unix socket endpoints - endpoint = "unix:///var/run/docker.sock" - client, err = NewClient(endpoint) - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if !client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be true, got false") - } - if client.requestedAPIVersion != nil { - t.Errorf("Expected requestedAPIVersion to be nil, got %#v.", client.requestedAPIVersion) - } -} - -func newTLSClient(endpoint string) (*Client, error) { - return NewTLSClient(endpoint, - "testing/data/cert.pem", - "testing/data/key.pem", - "testing/data/ca.pem") -} - -func TestNewTSLAPIClient(t *testing.T) { - endpoint := "https://localhost:4243" - client, err := newTLSClient(endpoint) - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if !client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be true, got false") - } - if client.requestedAPIVersion != nil { - t.Errorf("Expected requestedAPIVersion to be nil, got %#v.", client.requestedAPIVersion) - } -} - -func TestNewVersionedClient(t *testing.T) { - endpoint := "http://localhost:4243" - client, err := NewVersionedClient(endpoint, "1.12") - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.12" { - t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.12", reqVersion) - } - if client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be false, got true") - } -} - -func TestNewVersionedClientFromEnv(t *testing.T) { - endpoint := "tcp://localhost:2376" - endpointURL := "http://localhost:2376" - os.Setenv("DOCKER_HOST", endpoint) - os.Setenv("DOCKER_TLS_VERIFY", "") - client, err := NewVersionedClientFromEnv("1.12") - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if client.endpointURL.String() != endpointURL { - t.Errorf("Expected endpointURL %s. Got %s.", endpoint, client.endpoint) - } - if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.12" { - t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.12", reqVersion) - } - if client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be false, got true") - } -} - -func TestNewVersionedClientFromEnvTLS(t *testing.T) { - endpoint := "tcp://localhost:2376" - endpointURL := "https://localhost:2376" - base, _ := os.Getwd() - os.Setenv("DOCKER_CERT_PATH", filepath.Join(base, "/testing/data/")) - os.Setenv("DOCKER_HOST", endpoint) - os.Setenv("DOCKER_TLS_VERIFY", "1") - client, err := NewVersionedClientFromEnv("1.12") - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if client.endpointURL.String() != endpointURL { - t.Errorf("Expected endpointURL %s. Got %s.", endpoint, client.endpoint) - } - if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.12" { - t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.12", reqVersion) - } - if client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be false, got true") - } -} - -func TestNewTLSVersionedClient(t *testing.T) { - certPath := "testing/data/cert.pem" - keyPath := "testing/data/key.pem" - caPath := "testing/data/ca.pem" - endpoint := "https://localhost:4243" - client, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14") - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.14" { - t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.14", reqVersion) - } - if client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be false, got true") - } -} - -func TestNewTLSVersionedClientInvalidCA(t *testing.T) { - certPath := "testing/data/cert.pem" - keyPath := "testing/data/key.pem" - caPath := "testing/data/key.pem" - endpoint := "https://localhost:4243" - _, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14") - if err == nil { - t.Errorf("Expected invalid ca at %s", caPath) - } -} - -func TestNewClientInvalidEndpoint(t *testing.T) { - cases := []string{ - "htp://localhost:3243", "http://localhost:a", - "", "http://localhost:8080:8383", "http://localhost:65536", - "https://localhost:-20", - } - for _, c := range cases { - client, err := NewClient(c) - if client != nil { - t.Errorf("Want client for invalid endpoint, got %#v.", client) - } - if !reflect.DeepEqual(err, ErrInvalidEndpoint) { - t.Errorf("NewClient(%q): Got invalid error for invalid endpoint. Want %#v. Got %#v.", c, ErrInvalidEndpoint, err) - } - } -} - -func TestNewClientNoSchemeEndpoint(t *testing.T) { - cases := []string{"localhost", "localhost:8080"} - for _, c := range cases { - client, err := NewClient(c) - if client == nil { - t.Errorf("Want client for scheme-less endpoint, got ") - } - if err != nil { - t.Errorf("Got unexpected error scheme-less endpoint: %q", err) - } - } -} - -func TestNewTLSClient(t *testing.T) { - var tests = []struct { - endpoint string - expected string - }{ - {"tcp://localhost:2376", "https"}, - {"tcp://localhost:2375", "https"}, - {"tcp://localhost:4000", "https"}, - {"http://localhost:4000", "https"}, - } - for _, tt := range tests { - client, err := newTLSClient(tt.endpoint) - if err != nil { - t.Error(err) - } - got := client.endpointURL.Scheme - if got != tt.expected { - t.Errorf("endpointURL.Scheme: Got %s. Want %s.", got, tt.expected) - } - } -} - -func TestEndpoint(t *testing.T) { - client, err := NewVersionedClient("http://localhost:4243", "1.12") - if err != nil { - t.Fatal(err) - } - if endpoint := client.Endpoint(); endpoint != client.endpoint { - t.Errorf("Client.Endpoint(): want %q. Got %q", client.endpoint, endpoint) - } -} - -func TestGetURL(t *testing.T) { - var tests = []struct { - endpoint string - path string - expected string - }{ - {"http://localhost:4243/", "/", "http://localhost:4243/"}, - {"http://localhost:4243", "/", "http://localhost:4243/"}, - {"http://localhost:4243", "/containers/ps", "http://localhost:4243/containers/ps"}, - {"tcp://localhost:4243", "/containers/ps", "http://localhost:4243/containers/ps"}, - {"http://localhost:4243/////", "/", "http://localhost:4243/"}, - {"unix:///var/run/docker.socket", "/containers", "/containers"}, - } - for _, tt := range tests { - client, _ := NewClient(tt.endpoint) - client.endpoint = tt.endpoint - client.SkipServerVersionCheck = true - got := client.getURL(tt.path) - if got != tt.expected { - t.Errorf("getURL(%q): Got %s. Want %s.", tt.path, got, tt.expected) - } - } -} - -func TestGetFakeUnixURL(t *testing.T) { - var tests = []struct { - endpoint string - path string - expected string - }{ - {"unix://var/run/docker.sock", "/", "http://unix.sock/"}, - {"unix://var/run/docker.socket", "/", "http://unix.sock/"}, - {"unix://var/run/docker.sock", "/containers/ps", "http://unix.sock/containers/ps"}, - } - for _, tt := range tests { - client, _ := NewClient(tt.endpoint) - client.endpoint = tt.endpoint - client.SkipServerVersionCheck = true - got := client.getFakeUnixURL(tt.path) - if got != tt.expected { - t.Errorf("getURL(%q): Got %s. Want %s.", tt.path, got, tt.expected) - } - } -} - -func TestError(t *testing.T) { - fakeBody := ioutil.NopCloser(bytes.NewBufferString("bad parameter")) - resp := &http.Response{ - StatusCode: 400, - Body: fakeBody, - } - err := newError(resp) - expected := Error{Status: 400, Message: "bad parameter"} - if !reflect.DeepEqual(expected, *err) { - t.Errorf("Wrong error type. Want %#v. Got %#v.", expected, *err) - } - message := "API error (400): bad parameter" - if err.Error() != message { - t.Errorf("Wrong error message. Want %q. Got %q.", message, err.Error()) - } -} - -func TestQueryString(t *testing.T) { - v := float32(2.4) - f32QueryString := fmt.Sprintf("w=%s&x=10&y=10.35", strconv.FormatFloat(float64(v), 'f', -1, 64)) - jsonPerson := url.QueryEscape(`{"Name":"gopher","age":4}`) - var tests = []struct { - input interface{} - want string - }{ - {&ListContainersOptions{All: true}, "all=1"}, - {ListContainersOptions{All: true}, "all=1"}, - {ListContainersOptions{Before: "something"}, "before=something"}, - {ListContainersOptions{Before: "something", Since: "other"}, "before=something&since=other"}, - {ListContainersOptions{Filters: map[string][]string{"status": {"paused", "running"}}}, "filters=%7B%22status%22%3A%5B%22paused%22%2C%22running%22%5D%7D"}, - {dumb{X: 10, Y: 10.35000}, "x=10&y=10.35"}, - {dumb{W: v, X: 10, Y: 10.35000}, f32QueryString}, - {dumb{X: 10, Y: 10.35000, Z: 10}, "x=10&y=10.35&zee=10"}, - {dumb{v: 4, X: 10, Y: 10.35000}, "x=10&y=10.35"}, - {dumb{T: 10, Y: 10.35000}, "y=10.35"}, - {dumb{Person: &person{Name: "gopher", Age: 4}}, "p=" + jsonPerson}, - {nil, ""}, - {10, ""}, - {"not_a_struct", ""}, - } - for _, tt := range tests { - got := queryString(tt.input) - if got != tt.want { - t.Errorf("queryString(%v). Want %q. Got %q.", tt.input, tt.want, got) - } - } -} - -func TestNewAPIVersionFailures(t *testing.T) { - var tests = []struct { - input string - expectedError string - }{ - {"1-0", `Unable to parse version "1-0"`}, - {"1.0-beta", `Unable to parse version "1.0-beta": "0-beta" is not an integer`}, - } - for _, tt := range tests { - v, err := NewAPIVersion(tt.input) - if v != nil { - t.Errorf("Expected version, got %v.", v) - } - if err.Error() != tt.expectedError { - t.Errorf("NewAPIVersion(%q): wrong error. Want %q. Got %q", tt.input, tt.expectedError, err.Error()) - } - } -} - -func TestAPIVersions(t *testing.T) { - var tests = []struct { - a string - b string - expectedALessThanB bool - expectedALessThanOrEqualToB bool - expectedAGreaterThanB bool - expectedAGreaterThanOrEqualToB bool - }{ - {"1.11", "1.11", false, true, false, true}, - {"1.10", "1.11", true, true, false, false}, - {"1.11", "1.10", false, false, true, true}, - - {"1.9", "1.11", true, true, false, false}, - {"1.11", "1.9", false, false, true, true}, - - {"1.1.1", "1.1", false, false, true, true}, - {"1.1", "1.1.1", true, true, false, false}, - - {"2.1", "1.1.1", false, false, true, true}, - {"2.1", "1.3.1", false, false, true, true}, - {"1.1.1", "2.1", true, true, false, false}, - {"1.3.1", "2.1", true, true, false, false}, - } - - for _, tt := range tests { - a, _ := NewAPIVersion(tt.a) - b, _ := NewAPIVersion(tt.b) - - if tt.expectedALessThanB && !a.LessThan(b) { - t.Errorf("Expected %#v < %#v", a, b) - } - if tt.expectedALessThanOrEqualToB && !a.LessThanOrEqualTo(b) { - t.Errorf("Expected %#v <= %#v", a, b) - } - if tt.expectedAGreaterThanB && !a.GreaterThan(b) { - t.Errorf("Expected %#v > %#v", a, b) - } - if tt.expectedAGreaterThanOrEqualToB && !a.GreaterThanOrEqualTo(b) { - t.Errorf("Expected %#v >= %#v", a, b) - } - } -} - -func TestPing(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - err := client.Ping() - if err != nil { - t.Fatal(err) - } -} - -func TestPingFailing(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusInternalServerError} - client := newTestClient(fakeRT) - err := client.Ping() - if err == nil { - t.Fatal("Expected non nil error, got nil") - } - expectedErrMsg := "API error (500): " - if err.Error() != expectedErrMsg { - t.Fatalf("Expected error to be %q, got: %q", expectedErrMsg, err.Error()) - } -} - -func TestPingFailingWrongStatus(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusAccepted} - client := newTestClient(fakeRT) - err := client.Ping() - if err == nil { - t.Fatal("Expected non nil error, got nil") - } - expectedErrMsg := "API error (202): " - if err.Error() != expectedErrMsg { - t.Fatalf("Expected error to be %q, got: %q", expectedErrMsg, err.Error()) - } -} - -func TestPingErrorWithUnixSocket(t *testing.T) { - go func() { - li, err := net.Listen("unix", "/tmp/echo.sock") - if err != nil { - t.Fatal(err) - } - defer li.Close() - if err != nil { - t.Fatalf("Expected to get listener, but failed: %#v", err) - } - - fd, err := li.Accept() - if err != nil { - t.Fatalf("Expected to accept connection, but failed: %#v", err) - } - - buf := make([]byte, 512) - nr, err := fd.Read(buf) - - // Create invalid response message to trigger error. - data := buf[0:nr] - for i := 0; i < 10; i++ { - data[i] = 63 - } - - _, err = fd.Write(data) - if err != nil { - t.Fatalf("Expected to write to socket, but failed: %#v", err) - } - - return - }() - - // Wait for unix socket to listen - time.Sleep(10 * time.Millisecond) - - endpoint := "unix:///tmp/echo.sock" - u, _ := parseEndpoint(endpoint, false) - client := Client{ - HTTPClient: cleanhttp.DefaultClient(), - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - SkipServerVersionCheck: true, - } - - err := client.Ping() - if err == nil { - t.Fatal("Expected non nil error, got nil") - } -} - -type FakeRoundTripper struct { - message string - status int - header map[string]string - requests []*http.Request -} - -func (rt *FakeRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { - body := strings.NewReader(rt.message) - rt.requests = append(rt.requests, r) - res := &http.Response{ - StatusCode: rt.status, - Body: ioutil.NopCloser(body), - Header: make(http.Header), - } - for k, v := range rt.header { - res.Header.Set(k, v) - } - return res, nil -} - -func (rt *FakeRoundTripper) Reset() { - rt.requests = nil -} - -type person struct { - Name string - Age int `json:"age"` -} - -type dumb struct { - T int `qs:"-"` - v int - W float32 - X int - Y float64 - Z int `qs:"zee"` - Person *person `qs:"p"` -} - -type fakeEndpointURL struct { - Scheme string -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container.go index 0baf01f97..317814b90 100644 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container.go +++ b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container.go @@ -510,6 +510,7 @@ type HostConfig struct { BlkioWeight int64 `json:"BlkioWeight,omitempty" yaml:"BlkioWeight"` Ulimits []ULimit `json:"Ulimits,omitempty" yaml:"Ulimits,omitempty"` VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty"` + OomScoreAdj int `json:"OomScoreAdj,omitempty" yaml:"OomScoreAdj,omitempty"` } // StartContainer starts a container, returning an error in case of failure. @@ -638,6 +639,7 @@ func (c *Client) TopContainer(id string, psArgs string) (TopResult, error) { // See https://goo.gl/GNmLHb for more details. type Stats struct { Read time.Time `json:"read,omitempty" yaml:"read,omitempty"` + Network NetworkStats `json:"network,omitempty" yaml:"network,omitempty"` Networks map[string]NetworkStats `json:"networks,omitempty" yaml:"networks,omitempty"` MemoryStats struct { Stats struct { @@ -670,6 +672,8 @@ type Stats struct { Pgfault uint64 `json:"pgfault,omitempty" yaml:"pgfault,omitempty"` InactiveFile uint64 `json:"inactive_file,omitempty" yaml:"inactive_file,omitempty"` TotalPgpgin uint64 `json:"total_pgpgin,omitempty" yaml:"total_pgpgin,omitempty"` + HierarchicalMemswLimit uint64 `json:"hierarchical_memsw_limit,omitempty" yaml:"hierarchical_memsw_limit,omitempty"` + Swap uint64 `json:"swap,omitempty" yaml:"swap,omitempty"` } `json:"stats,omitempty" yaml:"stats,omitempty"` MaxUsage uint64 `json:"max_usage,omitempty" yaml:"max_usage,omitempty"` Usage uint64 `json:"usage,omitempty" yaml:"usage,omitempty"` diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container_test.go deleted file mode 100644 index 3e09c5f63..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container_test.go +++ /dev/null @@ -1,2248 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - "testing" - "time" - - "github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp" -) - -func TestStateString(t *testing.T) { - started := time.Now().Add(-3 * time.Hour) - var tests = []struct { - input State - expected string - }{ - {State{Running: true, Paused: true}, "^paused$"}, - {State{Running: true, StartedAt: started}, "^Up 3h.*$"}, - {State{Running: false, ExitCode: 7}, "^Exit 7$"}, - } - for _, tt := range tests { - re := regexp.MustCompile(tt.expected) - if got := tt.input.String(); !re.MatchString(got) { - t.Errorf("State.String(): wrong result. Want %q. Got %q.", tt.expected, got) - } - } -} - -func TestListContainers(t *testing.T) { - jsonContainers := `[ - { - "Id": "8dfafdbc3a40", - "Image": "base:latest", - "Command": "echo 1", - "Created": 1367854155, - "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], - "Status": "Exit 0" - }, - { - "Id": "9cd87474be90", - "Image": "base:latest", - "Command": "echo 222222", - "Created": 1367854155, - "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], - "Status": "Exit 0" - }, - { - "Id": "3176a2479c92", - "Image": "base:latest", - "Command": "echo 3333333333333333", - "Created": 1367854154, - "Ports":[{"PrivatePort": 2221, "PublicPort": 3331, "Type": "tcp"}], - "Status": "Exit 0" - }, - { - "Id": "4cb07b47f9fb", - "Image": "base:latest", - "Command": "echo 444444444444444444444444444444444", - "Ports":[{"PrivatePort": 2223, "PublicPort": 3332, "Type": "tcp"}], - "Created": 1367854152, - "Status": "Exit 0" - } -]` - var expected []APIContainers - err := json.Unmarshal([]byte(jsonContainers), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: jsonContainers, status: http.StatusOK}) - containers, err := client.ListContainers(ListContainersOptions{}) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(containers, expected) { - t.Errorf("ListContainers: Expected %#v. Got %#v.", expected, containers) - } -} - -func TestListContainersParams(t *testing.T) { - var tests = []struct { - input ListContainersOptions - params map[string][]string - }{ - {ListContainersOptions{}, map[string][]string{}}, - {ListContainersOptions{All: true}, map[string][]string{"all": {"1"}}}, - {ListContainersOptions{All: true, Limit: 10}, map[string][]string{"all": {"1"}, "limit": {"10"}}}, - { - ListContainersOptions{All: true, Limit: 10, Since: "adf9983", Before: "abdeef"}, - map[string][]string{"all": {"1"}, "limit": {"10"}, "since": {"adf9983"}, "before": {"abdeef"}}, - }, - { - ListContainersOptions{Filters: map[string][]string{"status": {"paused", "running"}}}, - map[string][]string{"filters": {"{\"status\":[\"paused\",\"running\"]}"}}, - }, - { - ListContainersOptions{All: true, Filters: map[string][]string{"exited": {"0"}, "status": {"exited"}}}, - map[string][]string{"all": {"1"}, "filters": {"{\"exited\":[\"0\"],\"status\":[\"exited\"]}"}}, - }, - } - fakeRT := &FakeRoundTripper{message: "[]", status: http.StatusOK} - client := newTestClient(fakeRT) - u, _ := url.Parse(client.getURL("/containers/json")) - for _, tt := range tests { - if _, err := client.ListContainers(tt.input); err != nil { - t.Error(err) - } - got := map[string][]string(fakeRT.requests[0].URL.Query()) - if !reflect.DeepEqual(got, tt.params) { - t.Errorf("Expected %#v, got %#v.", tt.params, got) - } - if path := fakeRT.requests[0].URL.Path; path != u.Path { - t.Errorf("Wrong path on request. Want %q. Got %q.", u.Path, path) - } - if meth := fakeRT.requests[0].Method; meth != "GET" { - t.Errorf("Wrong HTTP method. Want GET. Got %s.", meth) - } - fakeRT.Reset() - } -} - -func TestListContainersFailure(t *testing.T) { - var tests = []struct { - status int - message string - }{ - {400, "bad parameter"}, - {500, "internal server error"}, - } - for _, tt := range tests { - client := newTestClient(&FakeRoundTripper{message: tt.message, status: tt.status}) - expected := Error{Status: tt.status, Message: tt.message} - containers, err := client.ListContainers(ListContainersOptions{}) - if !reflect.DeepEqual(expected, *err.(*Error)) { - t.Errorf("Wrong error in ListContainers. Want %#v. Got %#v.", expected, err) - } - if len(containers) > 0 { - t.Errorf("ListContainers failure. Expected empty list. Got %#v.", containers) - } - } -} - -func TestInspectContainer(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "AppArmorProfile": "Profile", - "Created": "2013-05-07T14:51:42.087658+02:00", - "Path": "date", - "Args": [], - "Config": { - "Hostname": "4fa6e0f0c678", - "User": "", - "Memory": 17179869184, - "MemorySwap": 34359738368, - "AttachStdin": false, - "AttachStdout": true, - "AttachStderr": true, - "PortSpecs": null, - "Tty": false, - "OpenStdin": false, - "StdinOnce": false, - "Env": null, - "Cmd": [ - "date" - ], - "Image": "base", - "Volumes": {}, - "VolumesFrom": "", - "SecurityOpt": [ - "label:user:USER" - ], - "Ulimits": [ - { "Name": "nofile", "Soft": 1024, "Hard": 2048 } - ] - }, - "State": { - "Running": false, - "Pid": 0, - "ExitCode": 0, - "StartedAt": "2013-05-07T14:51:42.087658+02:00", - "Ghost": false - }, - "Node": { - "ID": "4I4E:QR4I:Z733:QEZK:5X44:Q4T7:W2DD:JRDY:KB2O:PODO:Z5SR:XRB6", - "IP": "192.168.99.105", - "Addra": "192.168.99.105:2376", - "Name": "node-01", - "Cpus": 4, - "Memory": 1048436736, - "Labels": { - "executiondriver": "native-0.2", - "kernelversion": "3.18.5-tinycore64", - "operatingsystem": "Boot2Docker 1.5.0 (TCL 5.4); master : a66bce5 - Tue Feb 10 23:31:27 UTC 2015", - "provider": "virtualbox", - "storagedriver": "aufs" - } - }, - "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - "NetworkSettings": { - "IpAddress": "", - "IpPrefixLen": 0, - "Gateway": "", - "Bridge": "", - "PortMapping": null - }, - "SysInitPath": "/home/kitty/go/src/github.com/dotcloud/docker/bin/docker", - "ResolvConfPath": "/etc/resolv.conf", - "Volumes": {}, - "HostConfig": { - "Binds": null, - "ContainerIDFile": "", - "LxcConf": [], - "Privileged": false, - "PortBindings": { - "80/tcp": [ - { - "HostIp": "0.0.0.0", - "HostPort": "49153" - } - ] - }, - "Links": null, - "PublishAllPorts": false, - "CgroupParent": "/mesos", - "Memory": 17179869184, - "MemorySwap": 34359738368, - "GroupAdd": ["fake", "12345"] - } -}` - var expected Container - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c678" - container, err := client.InspectContainer(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*container, expected) { - t.Errorf("InspectContainer(%q): Expected %#v. Got %#v.", id, expected, container) - } - expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/json")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("InspectContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestInspectContainerNetwork(t *testing.T) { - jsonContainer := `{ - "Id": "81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c", - "Created": "2015-11-12T14:54:04.791485659Z", - "Path": "consul-template", - "Args": [ - "-config=/tmp/haproxy.json", - "-consul=192.168.99.120:8500" - ], - "State": { - "Status": "running", - "Running": true, - "Paused": false, - "Restarting": false, - "OOMKilled": false, - "Dead": false, - "Pid": 3196, - "ExitCode": 0, - "Error": "", - "StartedAt": "2015-11-12T14:54:05.026747471Z", - "FinishedAt": "0001-01-01T00:00:00Z" - }, - "Image": "4921c5917fc117df3dec32f4c1976635dc6c56ccd3336fe1db3477f950e78bf7", - "ResolvConfPath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/resolv.conf", - "HostnamePath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/hostname", - "HostsPath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/hosts", - "LogPath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c-json.log", - "Node": { - "ID": "AUIB:LFOT:3LSF:SCFS:OYDQ:NLXD:JZNE:4INI:3DRC:ZFBB:GWCY:DWJK", - "IP": "192.168.99.121", - "Addr": "192.168.99.121:2376", - "Name": "swl-demo1", - "Cpus": 1, - "Memory": 2099945472, - "Labels": { - "executiondriver": "native-0.2", - "kernelversion": "4.1.12-boot2docker", - "operatingsystem": "Boot2Docker 1.9.0 (TCL 6.4); master : 16e4a2a - Tue Nov 3 19:49:22 UTC 2015", - "provider": "virtualbox", - "storagedriver": "aufs" - } - }, - "Name": "/docker-proxy.swl-demo1", - "RestartCount": 0, - "Driver": "aufs", - "ExecDriver": "native-0.2", - "MountLabel": "", - "ProcessLabel": "", - "AppArmorProfile": "", - "ExecIDs": null, - "HostConfig": { - "Binds": null, - "ContainerIDFile": "", - "LxcConf": [], - "Memory": 0, - "MemoryReservation": 0, - "MemorySwap": 0, - "KernelMemory": 0, - "CpuShares": 0, - "CpuPeriod": 0, - "CpusetCpus": "", - "CpusetMems": "", - "CpuQuota": 0, - "BlkioWeight": 0, - "OomKillDisable": false, - "MemorySwappiness": -1, - "Privileged": false, - "PortBindings": { - "443/tcp": [ - { - "HostIp": "", - "HostPort": "443" - } - ] - }, - "Links": null, - "PublishAllPorts": false, - "Dns": null, - "DnsOptions": null, - "DnsSearch": null, - "ExtraHosts": null, - "VolumesFrom": null, - "Devices": [], - "NetworkMode": "swl-net", - "IpcMode": "", - "PidMode": "", - "UTSMode": "", - "CapAdd": null, - "CapDrop": null, - "GroupAdd": null, - "RestartPolicy": { - "Name": "no", - "MaximumRetryCount": 0 - }, - "SecurityOpt": null, - "ReadonlyRootfs": false, - "Ulimits": null, - "LogConfig": { - "Type": "json-file", - "Config": {} - }, - "CgroupParent": "", - "ConsoleSize": [ - 0, - 0 - ], - "VolumeDriver": "" - }, - "GraphDriver": { - "Name": "aufs", - "Data": null - }, - "Mounts": [], - "Config": { - "Hostname": "81e1bbe20b55", - "Domainname": "", - "User": "", - "AttachStdin": false, - "AttachStdout": false, - "AttachStderr": false, - "ExposedPorts": { - "443/tcp": {} - }, - "Tty": false, - "OpenStdin": false, - "StdinOnce": false, - "Env": [ - "DOMAIN=local.auto", - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "CONSUL_TEMPLATE_VERSION=0.11.1" - ], - "Cmd": [ - "-consul=192.168.99.120:8500" - ], - "Image": "docker-proxy:latest", - "Volumes": null, - "WorkingDir": "", - "Entrypoint": [ - "consul-template", - "-config=/tmp/haproxy.json" - ], - "OnBuild": null, - "Labels": {}, - "StopSignal": "SIGTERM" - }, - "NetworkSettings": { - "Bridge": "", - "SandboxID": "c6b903dc5c1a96113a22dbc44709e30194079bd2d262eea1eb4f38d85821f6e1", - "HairpinMode": false, - "LinkLocalIPv6Address": "", - "LinkLocalIPv6PrefixLen": 0, - "Ports": { - "443/tcp": [ - { - "HostIp": "192.168.99.121", - "HostPort": "443" - } - ] - }, - "SandboxKey": "/var/run/docker/netns/c6b903dc5c1a", - "SecondaryIPAddresses": null, - "SecondaryIPv6Addresses": null, - "EndpointID": "", - "Gateway": "", - "GlobalIPv6Address": "", - "GlobalIPv6PrefixLen": 0, - "IPAddress": "", - "IPPrefixLen": 0, - "IPv6Gateway": "", - "MacAddress": "", - "Networks": { - "swl-net": { - "EndpointID": "683e3092275782a53c3b0968cc7e3a10f23264022ded9cb20490902f96fc5981", - "Gateway": "", - "IPAddress": "10.0.0.3", - "IPPrefixLen": 24, - "IPv6Gateway": "", - "GlobalIPv6Address": "", - "GlobalIPv6PrefixLen": 0, - "MacAddress": "02:42:0a:00:00:03" - } - } - } -}` - - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "81e1bbe20b55" - exp := "10.0.0.3" - - container, err := client.InspectContainer(id) - if err != nil { - t.Fatal(err) - } - - s := reflect.Indirect(reflect.ValueOf(container.NetworkSettings)) - networks := s.FieldByName("Networks") - if networks.IsValid() { - var ip string - for _, net := range networks.MapKeys() { - if net.Interface().(string) == container.HostConfig.NetworkMode { - ip = networks.MapIndex(net).FieldByName("IPAddress").Interface().(string) - t.Logf("%s %v", net, ip) - } - } - if ip != exp { - t.Errorf("InspectContainerNetworks(%q): Expected %#v. Got %#v.", id, exp, ip) - } - } else { - t.Errorf("InspectContainerNetworks(%q): No method Networks for NetworkSettings", id) - } - -} - -func TestInspectContainerNegativeSwap(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "Created": "2013-05-07T14:51:42.087658+02:00", - "Path": "date", - "Args": [], - "Config": { - "Hostname": "4fa6e0f0c678", - "User": "", - "Memory": 17179869184, - "MemorySwap": -1, - "AttachStdin": false, - "AttachStdout": true, - "AttachStderr": true, - "PortSpecs": null, - "Tty": false, - "OpenStdin": false, - "StdinOnce": false, - "Env": null, - "Cmd": [ - "date" - ], - "Image": "base", - "Volumes": {}, - "VolumesFrom": "" - }, - "State": { - "Running": false, - "Pid": 0, - "ExitCode": 0, - "StartedAt": "2013-05-07T14:51:42.087658+02:00", - "Ghost": false - }, - "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - "NetworkSettings": { - "IpAddress": "", - "IpPrefixLen": 0, - "Gateway": "", - "Bridge": "", - "PortMapping": null - }, - "SysInitPath": "/home/kitty/go/src/github.com/dotcloud/docker/bin/docker", - "ResolvConfPath": "/etc/resolv.conf", - "Volumes": {}, - "HostConfig": { - "Binds": null, - "ContainerIDFile": "", - "LxcConf": [], - "Privileged": false, - "PortBindings": { - "80/tcp": [ - { - "HostIp": "0.0.0.0", - "HostPort": "49153" - } - ] - }, - "Links": null, - "PublishAllPorts": false - } -}` - var expected Container - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c678" - container, err := client.InspectContainer(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*container, expected) { - t.Errorf("InspectContainer(%q): Expected %#v. Got %#v.", id, expected, container) - } - expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/json")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("InspectContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestInspectContainerFailure(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "server error", status: 500}) - expected := Error{Status: 500, Message: "server error"} - container, err := client.InspectContainer("abe033") - if container != nil { - t.Errorf("InspectContainer: Expected container, got %#v", container) - } - if !reflect.DeepEqual(expected, *err.(*Error)) { - t.Errorf("InspectContainer: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestInspectContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: 404}) - container, err := client.InspectContainer("abe033") - if container != nil { - t.Errorf("InspectContainer: Expected container, got %#v", container) - } - expected := &NoSuchContainer{ID: "abe033"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("InspectContainer: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestContainerChanges(t *testing.T) { - jsonChanges := `[ - { - "Path":"/dev", - "Kind":0 - }, - { - "Path":"/dev/kmsg", - "Kind":1 - }, - { - "Path":"/test", - "Kind":1 - } -]` - var expected []Change - err := json.Unmarshal([]byte(jsonChanges), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonChanges, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c678" - changes, err := client.ContainerChanges(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(changes, expected) { - t.Errorf("ContainerChanges(%q): Expected %#v. Got %#v.", id, expected, changes) - } - expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/changes")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("ContainerChanges(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestContainerChangesFailure(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "server error", status: 500}) - expected := Error{Status: 500, Message: "server error"} - changes, err := client.ContainerChanges("abe033") - if changes != nil { - t.Errorf("ContainerChanges: Expected changes, got %#v", changes) - } - if !reflect.DeepEqual(expected, *err.(*Error)) { - t.Errorf("ContainerChanges: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestContainerChangesNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: 404}) - changes, err := client.ContainerChanges("abe033") - if changes != nil { - t.Errorf("ContainerChanges: Expected changes, got %#v", changes) - } - expected := &NoSuchContainer{ID: "abe033"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("ContainerChanges: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestCreateContainer(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "Warnings": [] -}` - var expected Container - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - config := Config{AttachStdout: true, AttachStdin: true} - opts := CreateContainerOptions{Name: "TestCreateContainer", Config: &config} - container, err := client.CreateContainer(opts) - if err != nil { - t.Fatal(err) - } - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - if container.ID != id { - t.Errorf("CreateContainer: wrong ID. Want %q. Got %q.", id, container.ID) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("CreateContainer: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/create")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("CreateContainer: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - var gotBody Config - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } -} - -func TestCreateContainerImageNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "No such image", status: http.StatusNotFound}) - config := Config{AttachStdout: true, AttachStdin: true} - container, err := client.CreateContainer(CreateContainerOptions{Config: &config}) - if container != nil { - t.Errorf("CreateContainer: expected container, got %#v.", container) - } - if !reflect.DeepEqual(err, ErrNoSuchImage) { - t.Errorf("CreateContainer: Wrong error type. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestCreateContainerDuplicateName(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "No such image", status: http.StatusConflict}) - config := Config{AttachStdout: true, AttachStdin: true} - container, err := client.CreateContainer(CreateContainerOptions{Config: &config}) - if container != nil { - t.Errorf("CreateContainer: expected container, got %#v.", container) - } - if err != ErrContainerAlreadyExists { - t.Errorf("CreateContainer: Wrong error type. Want %#v. Got %#v.", ErrContainerAlreadyExists, err) - } -} - -func TestCreateContainerWithHostConfig(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "{}", status: http.StatusOK} - client := newTestClient(fakeRT) - config := Config{} - hostConfig := HostConfig{PublishAllPorts: true} - opts := CreateContainerOptions{Name: "TestCreateContainerWithHostConfig", Config: &config, HostConfig: &hostConfig} - _, err := client.CreateContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - var gotBody map[string]interface{} - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } - if _, ok := gotBody["HostConfig"]; !ok { - t.Errorf("CreateContainer: wrong body. HostConfig was not serialized") - } -} - -func TestStartContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.StartContainer(id, &HostConfig{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("StartContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/start")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("StartContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } - expectedContentType := "application/json" - if contentType := req.Header.Get("Content-Type"); contentType != expectedContentType { - t.Errorf("StartContainer(%q): Wrong content-type in request. Want %q. Got %q.", id, expectedContentType, contentType) - } -} - -func TestStartContainerNilHostConfig(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.StartContainer(id, nil) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("StartContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/start")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("StartContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } - expectedContentType := "application/json" - if contentType := req.Header.Get("Content-Type"); contentType != expectedContentType { - t.Errorf("StartContainer(%q): Wrong content-type in request. Want %q. Got %q.", id, expectedContentType, contentType) - } - var buf [4]byte - req.Body.Read(buf[:]) - if string(buf[:]) != "null" { - t.Errorf("Startcontainer(%q): Wrong body. Want null. Got %s", id, buf[:]) - } -} - -func TestStartContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.StartContainer("a2344", &HostConfig{}) - expected := &NoSuchContainer{ID: "a2344", Err: err.(*NoSuchContainer).Err} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestStartContainerAlreadyRunning(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "container already running", status: http.StatusNotModified}) - err := client.StartContainer("a2334", &HostConfig{}) - expected := &ContainerAlreadyRunning{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestStopContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.StopContainer(id, 10) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("StopContainer(%q, 10): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/stop")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("StopContainer(%q, 10): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestStopContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.StopContainer("a2334", 10) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestStopContainerNotRunning(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "container not running", status: http.StatusNotModified}) - err := client.StopContainer("a2334", 10) - expected := &ContainerNotRunning{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestRestartContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.RestartContainer(id, 10) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("RestartContainer(%q, 10): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/restart")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("RestartContainer(%q, 10): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestRestartContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.RestartContainer("a2334", 10) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("RestartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestPauseContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.PauseContainer(id) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PauseContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/pause")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("PauseContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestPauseContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.PauseContainer("a2334") - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("PauseContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestUnpauseContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.UnpauseContainer(id) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PauseContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/unpause")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("PauseContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestUnpauseContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.UnpauseContainer("a2334") - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("PauseContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestKillContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.KillContainer(KillContainerOptions{ID: id}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("KillContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/kill")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("KillContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestKillContainerSignal(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.KillContainer(KillContainerOptions{ID: id, Signal: SIGTERM}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("KillContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - if signal := req.URL.Query().Get("signal"); signal != "15" { - t.Errorf("KillContainer(%q): Wrong query string in request. Want %q. Got %q.", id, "15", signal) - } -} - -func TestKillContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.KillContainer(KillContainerOptions{ID: "a2334"}) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("KillContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestRemoveContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - opts := RemoveContainerOptions{ID: id} - err := client.RemoveContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "DELETE" { - t.Errorf("RemoveContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "DELETE", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id)) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("RemoveContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestRemoveContainerRemoveVolumes(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - opts := RemoveContainerOptions{ID: id, RemoveVolumes: true} - err := client.RemoveContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - params := map[string][]string(req.URL.Query()) - expected := map[string][]string{"v": {"1"}} - if !reflect.DeepEqual(params, expected) { - t.Errorf("RemoveContainer(%q): wrong parameters. Want %#v. Got %#v.", id, expected, params) - } -} - -func TestRemoveContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.RemoveContainer(RemoveContainerOptions{ID: "a2334"}) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("RemoveContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestResizeContainerTTY(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.ResizeContainerTTY(id, 40, 80) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ResizeContainerTTY(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/resize")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("ResizeContainerTTY(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } - got := map[string][]string(req.URL.Query()) - expectedParams := map[string][]string{ - "w": {"80"}, - "h": {"40"}, - } - if !reflect.DeepEqual(got, expectedParams) { - t.Errorf("Expected %#v, got %#v.", expectedParams, got) - } -} - -func TestWaitContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: `{"StatusCode": 56}`, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - status, err := client.WaitContainer(id) - if err != nil { - t.Fatal(err) - } - if status != 56 { - t.Errorf("WaitContainer(%q): wrong return. Want 56. Got %d.", id, status) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("WaitContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/wait")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("WaitContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestWaitContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - _, err := client.WaitContainer("a2334") - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("WaitContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestCommitContainer(t *testing.T) { - response := `{"Id":"596069db4bf5"}` - client := newTestClient(&FakeRoundTripper{message: response, status: http.StatusOK}) - id := "596069db4bf5" - image, err := client.CommitContainer(CommitContainerOptions{}) - if err != nil { - t.Fatal(err) - } - if image.ID != id { - t.Errorf("CommitContainer: Wrong image id. Want %q. Got %q.", id, image.ID) - } -} - -func TestCommitContainerParams(t *testing.T) { - cfg := Config{Memory: 67108864} - json, _ := json.Marshal(&cfg) - var tests = []struct { - input CommitContainerOptions - params map[string][]string - body []byte - }{ - {CommitContainerOptions{}, map[string][]string{}, nil}, - {CommitContainerOptions{Container: "44c004db4b17"}, map[string][]string{"container": {"44c004db4b17"}}, nil}, - { - CommitContainerOptions{Container: "44c004db4b17", Repository: "tsuru/python", Message: "something"}, - map[string][]string{"container": {"44c004db4b17"}, "repo": {"tsuru/python"}, "comment": {"something"}}, - nil, - }, - { - CommitContainerOptions{Container: "44c004db4b17", Run: &cfg}, - map[string][]string{"container": {"44c004db4b17"}}, - json, - }, - } - fakeRT := &FakeRoundTripper{message: "{}", status: http.StatusOK} - client := newTestClient(fakeRT) - u, _ := url.Parse(client.getURL("/commit")) - for _, tt := range tests { - if _, err := client.CommitContainer(tt.input); err != nil { - t.Error(err) - } - got := map[string][]string(fakeRT.requests[0].URL.Query()) - if !reflect.DeepEqual(got, tt.params) { - t.Errorf("Expected %#v, got %#v.", tt.params, got) - } - if path := fakeRT.requests[0].URL.Path; path != u.Path { - t.Errorf("Wrong path on request. Want %q. Got %q.", u.Path, path) - } - if meth := fakeRT.requests[0].Method; meth != "POST" { - t.Errorf("Wrong HTTP method. Want POST. Got %s.", meth) - } - if tt.body != nil { - if requestBody, err := ioutil.ReadAll(fakeRT.requests[0].Body); err == nil { - if bytes.Compare(requestBody, tt.body) != 0 { - t.Errorf("Expected body %#v, got %#v", tt.body, requestBody) - } - } else { - t.Errorf("Error reading request body: %#v", err) - } - } - fakeRT.Reset() - } -} - -func TestCommitContainerFailure(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusInternalServerError}) - _, err := client.CommitContainer(CommitContainerOptions{}) - if err == nil { - t.Error("Expected non-nil error, got .") - } -} - -func TestCommitContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - _, err := client.CommitContainer(CommitContainerOptions{}) - expected := &NoSuchContainer{ID: ""} - if !reflect.DeepEqual(err, expected) { - t.Errorf("CommitContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestAttachToContainerLogs(t *testing.T) { - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 19}) - w.Write([]byte("something happened!")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &buf, - Stdout: true, - Stderr: true, - Logs: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("AttachToContainer for logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } - if req.Method != "POST" { - t.Errorf("AttachToContainer: wrong HTTP method. Want POST. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/a123456/attach")) - if req.URL.Path != u.Path { - t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQs := map[string][]string{ - "logs": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expectedQs) { - t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expectedQs, got) - } -} - -func TestAttachToContainer(t *testing.T) { - var reader = strings.NewReader("send value") - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } - expected := map[string][]string{ - "stdin": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "stream": {"1"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestAttachToContainerSentinel(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - success := make(chan struct{}) - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - Success: success, - } - go func() { - if err := client.AttachToContainer(opts); err != nil { - t.Error(err) - } - }() - success <- <-success -} - -func TestAttachToContainerNilStdout(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stderr bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: nil, - ErrorStream: &stderr, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestAttachToContainerNilStderr(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestAttachToContainerStdinOnly(t *testing.T) { - var reader = strings.NewReader("send value") - serverFinished := make(chan struct{}) - clientFinished := make(chan struct{}) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - hj, ok := w.(http.Hijacker) - if !ok { - t.Fatal("cannot hijack server connection") - } - conn, _, err := hj.Hijack() - if err != nil { - t.Fatal(err) - } - // wait for client to indicate it's finished - <-clientFinished - // inform test that the server has finished - close(serverFinished) - conn.Close() - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - success := make(chan struct{}) - opts := AttachToContainerOptions{ - Container: "a123456", - InputStream: reader, - Stdin: true, - Stdout: false, - Stderr: false, - Stream: true, - RawTerminal: false, - Success: success, - } - go func() { - if err := client.AttachToContainer(opts); err != nil { - t.Error(err) - } - // client's attach session is over - close(clientFinished) - }() - success <- <-success - // wait for server to finish handling attach - <-serverFinished -} - -func TestAttachToContainerRawTerminalFalse(t *testing.T) { - input := strings.NewReader("send value") - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req = *r - w.WriteHeader(http.StatusOK) - hj, ok := w.(http.Hijacker) - if !ok { - t.Fatal("cannot hijack server connection") - } - conn, _, err := hj.Hijack() - if err != nil { - t.Fatal(err) - } - conn.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - conn.Write([]byte("hello")) - conn.Write([]byte{2, 0, 0, 0, 0, 0, 0, 6}) - conn.Write([]byte("hello!")) - conn.Close() - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: input, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: false, - } - client.AttachToContainer(opts) - expected := map[string][]string{ - "stdin": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "stream": {"1"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expected, got) - } - if stdout.String() != "hello" { - t.Errorf("AttachToContainer: wrong content written to stdout. Want %q. Got %q.", "hello", stdout.String()) - } - if stderr.String() != "hello!" { - t.Errorf("AttachToContainer: wrong content written to stderr. Want %q. Got %q.", "hello!", stderr.String()) - } -} - -func TestAttachToContainerWithoutContainer(t *testing.T) { - var client Client - err := client.AttachToContainer(AttachToContainerOptions{}) - expected := &NoSuchContainer{ID: ""} - if !reflect.DeepEqual(err, expected) { - t.Errorf("AttachToContainer: wrong error. Want %#v. Got %#v.", expected, err) - } -} - -func TestLogs(t *testing.T) { - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := LogsOptions{ - Container: "a123456", - OutputStream: &buf, - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } - if req.Method != "GET" { - t.Errorf("Logs: wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/a123456/logs")) - if req.URL.Path != u.Path { - t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQs := map[string][]string{ - "follow": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "timestamps": {"1"}, - "tail": {"all"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expectedQs) { - t.Errorf("Logs: wrong query string. Want %#v. Got %#v.", expectedQs, got) - } -} - -func TestLogsNilStdoutDoesntFail(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - opts := LogsOptions{ - Container: "a123456", - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestLogsNilStderrDoesntFail(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{2, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - opts := LogsOptions{ - Container: "a123456", - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestLogsSpecifyingTail(t *testing.T) { - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := LogsOptions{ - Container: "a123456", - OutputStream: &buf, - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - Tail: "100", - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } - if req.Method != "GET" { - t.Errorf("Logs: wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/a123456/logs")) - if req.URL.Path != u.Path { - t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQs := map[string][]string{ - "follow": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "timestamps": {"1"}, - "tail": {"100"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expectedQs) { - t.Errorf("Logs: wrong query string. Want %#v. Got %#v.", expectedQs, got) - } -} - -func TestLogsRawTerminal(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("something happened!")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := LogsOptions{ - Container: "a123456", - OutputStream: &buf, - Follow: true, - RawTerminal: true, - Stdout: true, - Stderr: true, - Timestamps: true, - Tail: "100", - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } -} - -func TestLogsNoContainer(t *testing.T) { - var client Client - err := client.Logs(LogsOptions{}) - expected := &NoSuchContainer{ID: ""} - if !reflect.DeepEqual(err, expected) { - t.Errorf("AttachToContainer: wrong error. Want %#v. Got %#v.", expected, err) - } -} - -func TestNoSuchContainerError(t *testing.T) { - var err = &NoSuchContainer{ID: "i345"} - expected := "No such container: i345" - if got := err.Error(); got != expected { - t.Errorf("NoSuchContainer: wrong message. Want %q. Got %q.", expected, got) - } -} - -func TestNoSuchContainerErrorMessage(t *testing.T) { - var err = &NoSuchContainer{ID: "i345", Err: errors.New("some advanced error info")} - expected := "some advanced error info" - if got := err.Error(); got != expected { - t.Errorf("NoSuchContainer: wrong message. Want %q. Got %q.", expected, got) - } -} - -func TestExportContainer(t *testing.T) { - content := "exported container tar content" - out := stdoutMock{bytes.NewBufferString(content)} - client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) - opts := ExportContainerOptions{ID: "4fa6e0f0c678", OutputStream: out} - err := client.ExportContainer(opts) - if err != nil { - t.Errorf("ExportContainer: caugh error %#v while exporting container, expected nil", err.Error()) - } - if out.String() != content { - t.Errorf("ExportContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) - } -} - -func TestExportContainerViaUnixSocket(t *testing.T) { - if runtime.GOOS != "darwin" { - t.Skip(fmt.Sprintf("skipping test on %s", runtime.GOOS)) - } - content := "exported container tar content" - var buf []byte - out := bytes.NewBuffer(buf) - tempSocket := tempfile("export_socket") - defer os.Remove(tempSocket) - endpoint := "unix://" + tempSocket - u, _ := parseEndpoint(endpoint, false) - client := Client{ - HTTPClient: cleanhttp.DefaultClient(), - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - SkipServerVersionCheck: true, - } - listening := make(chan string) - done := make(chan int) - go runStreamConnServer(t, "unix", tempSocket, listening, done) - <-listening // wait for server to start - opts := ExportContainerOptions{ID: "4fa6e0f0c678", OutputStream: out} - err := client.ExportContainer(opts) - <-done // make sure server stopped - if err != nil { - t.Errorf("ExportContainer: caugh error %#v while exporting container, expected nil", err.Error()) - } - if out.String() != content { - t.Errorf("ExportContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) - } -} - -func runStreamConnServer(t *testing.T, network, laddr string, listening chan<- string, done chan<- int) { - defer close(done) - l, err := net.Listen(network, laddr) - if err != nil { - t.Errorf("Listen(%q, %q) failed: %v", network, laddr, err) - listening <- "" - return - } - defer l.Close() - listening <- l.Addr().String() - c, err := l.Accept() - if err != nil { - t.Logf("Accept failed: %v", err) - return - } - c.Write([]byte("HTTP/1.1 200 OK\n\nexported container tar content")) - c.Close() -} - -func tempfile(filename string) string { - return os.TempDir() + "/" + filename + "." + strconv.Itoa(os.Getpid()) -} - -func TestExportContainerNoId(t *testing.T) { - client := Client{} - out := stdoutMock{bytes.NewBufferString("")} - err := client.ExportContainer(ExportContainerOptions{OutputStream: out}) - e, ok := err.(*NoSuchContainer) - if !ok { - t.Errorf("ExportContainer: wrong error. Want NoSuchContainer. Got %#v.", e) - } - if e.ID != "" { - t.Errorf("ExportContainer: wrong ID. Want %q. Got %q", "", e.ID) - } -} - -func TestUploadToContainer(t *testing.T) { - content := "File content" - in := stdinMock{bytes.NewBufferString(content)} - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - opts := UploadToContainerOptions{ - Path: "abc", - InputStream: in, - } - err := client.UploadToContainer("a123456", opts) - if err != nil { - t.Errorf("UploadToContainer: caught error %#v while uploading archive to container, expected nil", err) - } - - req := fakeRT.requests[0] - - if req.Method != "PUT" { - t.Errorf("UploadToContainer{Path:abc}: Wrong HTTP method. Want PUT. Got %s", req.Method) - } - - if pathParam := req.URL.Query().Get("path"); pathParam != "abc" { - t.Errorf("ListImages({Path:abc}): Wrong parameter. Want path=abc. Got path=%s", pathParam) - } - -} - -func TestDownloadFromContainer(t *testing.T) { - filecontent := "File content" - client := newTestClient(&FakeRoundTripper{message: filecontent, status: http.StatusOK}) - - var out bytes.Buffer - opts := DownloadFromContainerOptions{ - OutputStream: &out, - } - err := client.DownloadFromContainer("a123456", opts) - if err != nil { - t.Errorf("DownloadFromContainer: caught error %#v while downloading from container, expected nil", err.Error()) - } - if out.String() != filecontent { - t.Errorf("DownloadFromContainer: wrong stdout. Want %#v. Got %#v.", filecontent, out.String()) - } -} - -func TestCopyFromContainer(t *testing.T) { - content := "File content" - out := stdoutMock{bytes.NewBufferString(content)} - client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) - opts := CopyFromContainerOptions{ - Container: "a123456", - OutputStream: &out, - } - err := client.CopyFromContainer(opts) - if err != nil { - t.Errorf("CopyFromContainer: caught error %#v while copying from container, expected nil", err.Error()) - } - if out.String() != content { - t.Errorf("CopyFromContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) - } -} - -func TestCopyFromContainerEmptyContainer(t *testing.T) { - client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) - err := client.CopyFromContainer(CopyFromContainerOptions{}) - _, ok := err.(*NoSuchContainer) - if !ok { - t.Errorf("CopyFromContainer: invalid error returned. Want NoSuchContainer, got %#v.", err) - } -} - -func TestPassingNameOptToCreateContainerReturnsItInContainer(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "Warnings": [] -}` - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - config := Config{AttachStdout: true, AttachStdin: true} - opts := CreateContainerOptions{Name: "TestCreateContainer", Config: &config} - container, err := client.CreateContainer(opts) - if err != nil { - t.Fatal(err) - } - if container.Name != "TestCreateContainer" { - t.Errorf("Container name expected to be TestCreateContainer, was %s", container.Name) - } -} - -func TestAlwaysRestart(t *testing.T) { - policy := AlwaysRestart() - if policy.Name != "always" { - t.Errorf("AlwaysRestart(): wrong policy name. Want %q. Got %q", "always", policy.Name) - } - if policy.MaximumRetryCount != 0 { - t.Errorf("AlwaysRestart(): wrong MaximumRetryCount. Want 0. Got %d", policy.MaximumRetryCount) - } -} - -func TestRestartOnFailure(t *testing.T) { - const retry = 5 - policy := RestartOnFailure(retry) - if policy.Name != "on-failure" { - t.Errorf("RestartOnFailure(%d): wrong policy name. Want %q. Got %q", retry, "on-failure", policy.Name) - } - if policy.MaximumRetryCount != retry { - t.Errorf("RestartOnFailure(%d): wrong MaximumRetryCount. Want %d. Got %d", retry, retry, policy.MaximumRetryCount) - } -} - -func TestNeverRestart(t *testing.T) { - policy := NeverRestart() - if policy.Name != "no" { - t.Errorf("NeverRestart(): wrong policy name. Want %q. Got %q", "always", policy.Name) - } - if policy.MaximumRetryCount != 0 { - t.Errorf("NeverRestart(): wrong MaximumRetryCount. Want 0. Got %d", policy.MaximumRetryCount) - } -} - -func TestTopContainer(t *testing.T) { - jsonTop := `{ - "Processes": [ - [ - "ubuntu", - "3087", - "815", - "0", - "01:44", - "?", - "00:00:00", - "cmd1" - ], - [ - "root", - "3158", - "3087", - "0", - "01:44", - "?", - "00:00:01", - "cmd2" - ] - ], - "Titles": [ - "UID", - "PID", - "PPID", - "C", - "STIME", - "TTY", - "TIME", - "CMD" - ] -}` - var expected TopResult - err := json.Unmarshal([]byte(jsonTop), &expected) - if err != nil { - t.Fatal(err) - } - id := "4fa6e0f0" - fakeRT := &FakeRoundTripper{message: jsonTop, status: http.StatusOK} - client := newTestClient(fakeRT) - processes, err := client.TopContainer(id, "") - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(processes, expected) { - t.Errorf("TopContainer: Expected %#v. Got %#v.", expected, processes) - } - if len(processes.Processes) != 2 || len(processes.Processes[0]) != 8 || - processes.Processes[0][7] != "cmd1" { - t.Errorf("TopContainer: Process list to include cmd1. Got %#v.", processes) - } - expectedURI := "/containers/" + id + "/top" - if !strings.HasSuffix(fakeRT.requests[0].URL.String(), expectedURI) { - t.Errorf("TopContainer: Expected URI to have %q. Got %q.", expectedURI, fakeRT.requests[0].URL.String()) - } -} - -func TestTopContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - _, err := client.TopContainer("abef348", "") - expected := &NoSuchContainer{ID: "abef348"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestTopContainerWithPsArgs(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "no such container", status: http.StatusNotFound} - client := newTestClient(fakeRT) - expectedErr := &NoSuchContainer{ID: "abef348"} - if _, err := client.TopContainer("abef348", "aux"); !reflect.DeepEqual(expectedErr, err) { - t.Errorf("TopContainer: Expected %v. Got %v.", expectedErr, err) - } - expectedURI := "/containers/abef348/top?ps_args=aux" - if !strings.HasSuffix(fakeRT.requests[0].URL.String(), expectedURI) { - t.Errorf("TopContainer: Expected URI to have %q. Got %q.", expectedURI, fakeRT.requests[0].URL.String()) - } -} - -func TestStatsTimeout(t *testing.T) { - l, err := net.Listen("unix", "/tmp/docker_test.sock") - if err != nil { - t.Fatal(err) - } - received := false - defer l.Close() - go func() { - l.Accept() - received = true - time.Sleep(time.Second) - }() - client, _ := NewClient("unix:///tmp/docker_test.sock") - client.SkipServerVersionCheck = true - errC := make(chan error, 1) - statsC := make(chan *Stats) - done := make(chan bool) - go func() { - errC <- client.Stats(StatsOptions{"c", statsC, true, done, time.Millisecond * 100}) - close(errC) - }() - err = <-errC - e, ok := err.(net.Error) - if !ok || !e.Timeout() { - t.Error("Failed to receive timeout exception") - } - if !received { - t.Fatal("Failed to receive message") - } -} - -func TestStats(t *testing.T) { - jsonStats1 := `{ - "read" : "2015-01-08T22:57:31.547920715Z", - "networks" : { - "eth0":{ - "rx_dropped" : 0, - "rx_bytes" : 648, - "rx_errors" : 0, - "tx_packets" : 8, - "tx_dropped" : 0, - "rx_packets" : 8, - "tx_errors" : 0, - "tx_bytes" : 648 - } - }, - "memory_stats" : { - "stats" : { - "total_pgmajfault" : 0, - "cache" : 0, - "mapped_file" : 0, - "total_inactive_file" : 0, - "pgpgout" : 414, - "rss" : 6537216, - "total_mapped_file" : 0, - "writeback" : 0, - "unevictable" : 0, - "pgpgin" : 477, - "total_unevictable" : 0, - "pgmajfault" : 0, - "total_rss" : 6537216, - "total_rss_huge" : 6291456, - "total_writeback" : 0, - "total_inactive_anon" : 0, - "rss_huge" : 6291456, - "hierarchical_memory_limit": 189204833, - "total_pgfault" : 964, - "total_active_file" : 0, - "active_anon" : 6537216, - "total_active_anon" : 6537216, - "total_pgpgout" : 414, - "total_cache" : 0, - "inactive_anon" : 0, - "active_file" : 0, - "pgfault" : 964, - "inactive_file" : 0, - "total_pgpgin" : 477 - }, - "max_usage" : 6651904, - "usage" : 6537216, - "failcnt" : 0, - "limit" : 67108864 - }, - "blkio_stats": { - "io_service_bytes_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 428795731968 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 388177920 - } - ], - "io_serviced_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 25994442 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 1734 - } - ], - "io_queue_recursive": [], - "io_service_time_recursive": [], - "io_wait_time_recursive": [], - "io_merged_recursive": [], - "io_time_recursive": [], - "sectors_recursive": [] - }, - "cpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - }, - "precpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - } - }` - // 1 second later, cache is 100 - jsonStats2 := `{ - "read" : "2015-01-08T22:57:32.547920715Z", - "networks" : { - "eth0":{ - "rx_dropped" : 0, - "rx_bytes" : 648, - "rx_errors" : 0, - "tx_packets" : 8, - "tx_dropped" : 0, - "rx_packets" : 8, - "tx_errors" : 0, - "tx_bytes" : 648 - } - }, - "memory_stats" : { - "stats" : { - "total_pgmajfault" : 0, - "cache" : 100, - "mapped_file" : 0, - "total_inactive_file" : 0, - "pgpgout" : 414, - "rss" : 6537216, - "total_mapped_file" : 0, - "writeback" : 0, - "unevictable" : 0, - "pgpgin" : 477, - "total_unevictable" : 0, - "pgmajfault" : 0, - "total_rss" : 6537216, - "total_rss_huge" : 6291456, - "total_writeback" : 0, - "total_inactive_anon" : 0, - "rss_huge" : 6291456, - "total_pgfault" : 964, - "total_active_file" : 0, - "active_anon" : 6537216, - "total_active_anon" : 6537216, - "total_pgpgout" : 414, - "total_cache" : 0, - "inactive_anon" : 0, - "active_file" : 0, - "pgfault" : 964, - "inactive_file" : 0, - "total_pgpgin" : 477 - }, - "max_usage" : 6651904, - "usage" : 6537216, - "failcnt" : 0, - "limit" : 67108864 - }, - "blkio_stats": { - "io_service_bytes_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 428795731968 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 388177920 - } - ], - "io_serviced_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 25994442 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 1734 - } - ], - "io_queue_recursive": [], - "io_service_time_recursive": [], - "io_wait_time_recursive": [], - "io_merged_recursive": [], - "io_time_recursive": [], - "sectors_recursive": [] - }, - "cpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - }, - "precpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - } - }` - var expected1 Stats - var expected2 Stats - err := json.Unmarshal([]byte(jsonStats1), &expected1) - if err != nil { - t.Fatal(err) - } - err = json.Unmarshal([]byte(jsonStats2), &expected2) - if err != nil { - t.Fatal(err) - } - id := "4fa6e0f0" - - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(jsonStats1)) - w.Write([]byte(jsonStats2)) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - errC := make(chan error, 1) - statsC := make(chan *Stats) - done := make(chan bool) - go func() { - errC <- client.Stats(StatsOptions{id, statsC, true, done, 0}) - close(errC) - }() - var resultStats []*Stats - for { - stats, ok := <-statsC - if !ok { - break - } - resultStats = append(resultStats, stats) - } - err = <-errC - if err != nil { - t.Fatal(err) - } - if len(resultStats) != 2 { - t.Fatalf("Stats: Expected 2 results. Got %d.", len(resultStats)) - } - if !reflect.DeepEqual(resultStats[0], &expected1) { - t.Errorf("Stats: Expected:\n%+v\nGot:\n%+v", expected1, resultStats[0]) - } - if !reflect.DeepEqual(resultStats[1], &expected2) { - t.Errorf("Stats: Expected:\n%+v\nGot:\n%+v", expected2, resultStats[1]) - } - if req.Method != "GET" { - t.Errorf("Stats: wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/" + id + "/stats")) - if req.URL.Path != u.Path { - t.Errorf("Stats: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestStatsContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - statsC := make(chan *Stats) - done := make(chan bool) - err := client.Stats(StatsOptions{"abef348", statsC, true, done, 0}) - expected := &NoSuchContainer{ID: "abef348"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("Stats: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestRenameContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := RenameContainerOptions{ID: "something_old", Name: "something_new"} - err := client.RenameContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("RenameContainer: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/something_old/rename?name=something_new")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("RenameContainer: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - expectedValues := expectedURL.Query()["name"] - actualValues := req.URL.Query()["name"] - if len(actualValues) != 1 || expectedValues[0] != actualValues[0] { - t.Errorf("RenameContainer: Wrong params in request. Want %q. Got %q.", expectedValues, actualValues) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/env_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/env_test.go deleted file mode 100644 index df5169d06..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/env_test.go +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the DOCKER-LICENSE file. - -package docker - -import ( - "bytes" - "errors" - "reflect" - "sort" - "testing" -) - -func TestGet(t *testing.T) { - var tests = []struct { - input []string - query string - expected string - }{ - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PATH", "/usr/bin:/bin"}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATH", "/usr/local"}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATHI", ""}, - {[]string{"WAT="}, "WAT", ""}, - } - for _, tt := range tests { - env := Env(tt.input) - got := env.Get(tt.query) - if got != tt.expected { - t.Errorf("Env.Get(%q): wrong result. Want %q. Got %q", tt.query, tt.expected, got) - } - } -} - -func TestExists(t *testing.T) { - var tests = []struct { - input []string - query string - expected bool - }{ - {[]string{"WAT=", "PYTHONPATH=/usr/local"}, "WAT", true}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATH", true}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATHI", false}, - } - for _, tt := range tests { - env := Env(tt.input) - got := env.Exists(tt.query) - if got != tt.expected { - t.Errorf("Env.Exists(%q): wrong result. Want %v. Got %v", tt.query, tt.expected, got) - } - } -} - -func TestGetBool(t *testing.T) { - var tests = []struct { - input string - expected bool - }{ - {"EMTPY_VAR", false}, {"ZERO_VAR", false}, {"NO_VAR", false}, - {"FALSE_VAR", false}, {"NONE_VAR", false}, {"TRUE_VAR", true}, - {"WAT", true}, {"PATH", true}, {"ONE_VAR", true}, {"NO_VAR_TAB", false}, - } - env := Env([]string{ - "EMPTY_VAR=", "ZERO_VAR=0", "NO_VAR=no", "FALSE_VAR=false", - "NONE_VAR=none", "TRUE_VAR=true", "WAT=wat", "PATH=/usr/bin:/bin", - "ONE_VAR=1", "NO_VAR_TAB=0 \t\t\t", - }) - for _, tt := range tests { - got := env.GetBool(tt.input) - if got != tt.expected { - t.Errorf("Env.GetBool(%q): wrong result. Want %v. Got %v.", tt.input, tt.expected, got) - } - } -} - -func TestSetBool(t *testing.T) { - var tests = []struct { - input bool - expected string - }{ - {true, "1"}, {false, "0"}, - } - for _, tt := range tests { - var env Env - env.SetBool("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetBool(%v): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestGetInt(t *testing.T) { - var tests = []struct { - input string - expected int - }{ - {"NEGATIVE_INTEGER", -10}, {"NON_INTEGER", -1}, {"ONE", 1}, {"TWO", 2}, - } - env := Env([]string{"NEGATIVE_INTEGER=-10", "NON_INTEGER=wat", "ONE=1", "TWO=2"}) - for _, tt := range tests { - got := env.GetInt(tt.input) - if got != tt.expected { - t.Errorf("Env.GetInt(%q): wrong result. Want %d. Got %d", tt.input, tt.expected, got) - } - } -} - -func TestSetInt(t *testing.T) { - var tests = []struct { - input int - expected string - }{ - {10, "10"}, {13, "13"}, {7, "7"}, {33, "33"}, - {0, "0"}, {-34, "-34"}, - } - for _, tt := range tests { - var env Env - env.SetInt("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetBool(%d): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestGetInt64(t *testing.T) { - var tests = []struct { - input string - expected int64 - }{ - {"NEGATIVE_INTEGER", -10}, {"NON_INTEGER", -1}, {"ONE", 1}, {"TWO", 2}, - } - env := Env([]string{"NEGATIVE_INTEGER=-10", "NON_INTEGER=wat", "ONE=1", "TWO=2"}) - for _, tt := range tests { - got := env.GetInt64(tt.input) - if got != tt.expected { - t.Errorf("Env.GetInt64(%q): wrong result. Want %d. Got %d", tt.input, tt.expected, got) - } - } -} - -func TestSetInt64(t *testing.T) { - var tests = []struct { - input int64 - expected string - }{ - {10, "10"}, {13, "13"}, {7, "7"}, {33, "33"}, - {0, "0"}, {-34, "-34"}, - } - for _, tt := range tests { - var env Env - env.SetInt64("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetBool(%d): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestGetJSON(t *testing.T) { - var p struct { - Name string `json:"name"` - Age int `json:"age"` - } - var env Env - env.Set("person", `{"name":"Gopher","age":5}`) - err := env.GetJSON("person", &p) - if err != nil { - t.Error(err) - } - if p.Name != "Gopher" { - t.Errorf("Env.GetJSON(%q): wrong name. Want %q. Got %q", "person", "Gopher", p.Name) - } - if p.Age != 5 { - t.Errorf("Env.GetJSON(%q): wrong age. Want %d. Got %d", "person", 5, p.Age) - } -} - -func TestGetJSONAbsent(t *testing.T) { - var l []string - var env Env - err := env.GetJSON("person", &l) - if err != nil { - t.Error(err) - } - if l != nil { - t.Errorf("Env.GetJSON(): get unexpected list %v", l) - } -} - -func TestGetJSONFailure(t *testing.T) { - var p []string - var env Env - env.Set("list-person", `{"name":"Gopher","age":5}`) - err := env.GetJSON("list-person", &p) - if err == nil { - t.Errorf("Env.GetJSON(%q): got unexpected error.", "list-person") - } -} - -func TestSetJSON(t *testing.T) { - var p1 = struct { - Name string `json:"name"` - Age int `json:"age"` - }{Name: "Gopher", Age: 5} - var env Env - err := env.SetJSON("person", p1) - if err != nil { - t.Error(err) - } - var p2 struct { - Name string `json:"name"` - Age int `json:"age"` - } - err = env.GetJSON("person", &p2) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(p1, p2) { - t.Errorf("Env.SetJSON(%q): wrong result. Want %v. Got %v", "person", p1, p2) - } -} - -func TestSetJSONFailure(t *testing.T) { - var env Env - err := env.SetJSON("person", unmarshable{}) - if err == nil { - t.Error("Env.SetJSON(): got unexpected error") - } - if env.Exists("person") { - t.Errorf("Env.SetJSON(): should not define the key %q, but did", "person") - } -} - -func TestGetList(t *testing.T) { - var tests = []struct { - input string - expected []string - }{ - {"WAT=wat", []string{"wat"}}, - {`WAT=["wat","wet","wit","wot","wut"]`, []string{"wat", "wet", "wit", "wot", "wut"}}, - {"WAT=", nil}, - } - for _, tt := range tests { - env := Env([]string{tt.input}) - got := env.GetList("WAT") - if !reflect.DeepEqual(got, tt.expected) { - t.Errorf("Env.GetList(%q): wrong result. Want %v. Got %v", "WAT", tt.expected, got) - } - } -} - -func TestSetList(t *testing.T) { - list := []string{"a", "b", "c"} - var env Env - if err := env.SetList("SOME", list); err != nil { - t.Error(err) - } - if got := env.GetList("SOME"); !reflect.DeepEqual(got, list) { - t.Errorf("Env.SetList(%v): wrong result. Got %v", list, got) - } -} - -func TestSet(t *testing.T) { - var env Env - env.Set("PATH", "/home/bin:/bin") - env.Set("SOMETHING", "/usr/bin") - env.Set("PATH", "/bin") - if expected, got := "/usr/bin", env.Get("SOMETHING"); got != expected { - t.Errorf("Env.Set(%q): wrong result. Want %q. Got %q", expected, expected, got) - } - if expected, got := "/bin", env.Get("PATH"); got != expected { - t.Errorf("Env.Set(%q): wrong result. Want %q. Got %q", expected, expected, got) - } -} - -func TestDecode(t *testing.T) { - var tests = []struct { - input string - expectedOut []string - expectedErr string - }{ - { - `{"PATH":"/usr/bin:/bin","containers":54,"wat":["123","345"]}`, - []string{"PATH=/usr/bin:/bin", "containers=54", `wat=["123","345"]`}, - "", - }, - {"}}", nil, "invalid character '}' looking for beginning of value"}, - {`{}`, nil, ""}, - } - for _, tt := range tests { - var env Env - err := env.Decode(bytes.NewBufferString(tt.input)) - if tt.expectedErr == "" { - if err != nil { - t.Error(err) - } - } else if tt.expectedErr != err.Error() { - t.Errorf("Env.Decode(): invalid error. Want %q. Got %q.", tt.expectedErr, err) - } - got := []string(env) - sort.Strings(got) - sort.Strings(tt.expectedOut) - if !reflect.DeepEqual(got, tt.expectedOut) { - t.Errorf("Env.Decode(): wrong result. Want %v. Got %v.", tt.expectedOut, got) - } - } -} - -func TestSetAuto(t *testing.T) { - buf := bytes.NewBufferString("oi") - var tests = []struct { - input interface{} - expected string - }{ - {10, "10"}, - {10.3, "10"}, - {"oi", "oi"}, - {buf, "{}"}, - {unmarshable{}, "{}"}, - } - for _, tt := range tests { - var env Env - env.SetAuto("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetAuto(%v): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestMap(t *testing.T) { - var tests = []struct { - input []string - expected map[string]string - }{ - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, map[string]string{"PATH": "/usr/bin:/bin", "PYTHONPATH": "/usr/local"}}, - {nil, nil}, - } - for _, tt := range tests { - env := Env(tt.input) - got := env.Map() - if !reflect.DeepEqual(got, tt.expected) { - t.Errorf("Env.Map(): wrong result. Want %v. Got %v", tt.expected, got) - } - } -} - -type unmarshable struct { -} - -func (unmarshable) MarshalJSON() ([]byte, error) { - return nil, errors.New("cannot marshal") -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/event_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/event_test.go deleted file mode 100644 index a308538cc..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/event_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bufio" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" -) - -func TestEventListeners(t *testing.T) { - testEventListeners("TestEventListeners", t, httptest.NewServer, NewClient) -} - -func TestTLSEventListeners(t *testing.T) { - testEventListeners("TestTLSEventListeners", t, func(handler http.Handler) *httptest.Server { - server := httptest.NewUnstartedServer(handler) - - cert, err := tls.LoadX509KeyPair("testing/data/server.pem", "testing/data/serverkey.pem") - if err != nil { - t.Fatalf("Error loading server key pair: %s", err) - } - - caCert, err := ioutil.ReadFile("testing/data/ca.pem") - if err != nil { - t.Fatalf("Error loading ca certificate: %s", err) - } - caPool := x509.NewCertPool() - if !caPool.AppendCertsFromPEM(caCert) { - t.Fatalf("Could not add ca certificate") - } - - server.TLS = &tls.Config{ - Certificates: []tls.Certificate{cert}, - RootCAs: caPool, - } - server.StartTLS() - return server - }, func(url string) (*Client, error) { - return NewTLSClient(url, "testing/data/cert.pem", "testing/data/key.pem", "testing/data/ca.pem") - }) -} - -func testEventListeners(testName string, t *testing.T, buildServer func(http.Handler) *httptest.Server, buildClient func(string) (*Client, error)) { - response := `{"status":"create","id":"dfdf82bd3881","from":"base:latest","time":1374067924} -{"status":"start","id":"dfdf82bd3881","from":"base:latest","time":1374067924} -{"status":"stop","id":"dfdf82bd3881","from":"base:latest","time":1374067966} -{"status":"destroy","id":"dfdf82bd3881","from":"base:latest","time":1374067970} -` - - server := buildServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - rsc := bufio.NewScanner(strings.NewReader(response)) - for rsc.Scan() { - w.Write([]byte(rsc.Text())) - w.(http.Flusher).Flush() - time.Sleep(10 * time.Millisecond) - } - })) - defer server.Close() - - client, err := buildClient(server.URL) - if err != nil { - t.Errorf("Failed to create client: %s", err) - } - client.SkipServerVersionCheck = true - - listener := make(chan *APIEvents, 10) - defer func() { - time.Sleep(10 * time.Millisecond) - if err := client.RemoveEventListener(listener); err != nil { - t.Error(err) - } - }() - - err = client.AddEventListener(listener) - if err != nil { - t.Errorf("Failed to add event listener: %s", err) - } - - timeout := time.After(1 * time.Second) - var count int - - for { - select { - case msg := <-listener: - t.Logf("Received: %v", *msg) - count++ - err = checkEvent(count, msg) - if err != nil { - t.Fatalf("Check event failed: %s", err) - } - if count == 4 { - return - } - case <-timeout: - t.Fatalf("%s timed out waiting on events", testName) - } - } -} - -func checkEvent(index int, event *APIEvents) error { - if event.ID != "dfdf82bd3881" { - return fmt.Errorf("event ID did not match. Expected dfdf82bd3881 got %s", event.ID) - } - if event.From != "base:latest" { - return fmt.Errorf("event from did not match. Expected base:latest got %s", event.From) - } - var status string - switch index { - case 1: - status = "create" - case 2: - status = "start" - case 3: - status = "stop" - case 4: - status = "destroy" - } - if event.Status != status { - return fmt.Errorf("event status did not match. Expected %s got %s", status, event.Status) - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/example_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/example_test.go deleted file mode 100644 index 8c2c719e6..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/example_test.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker_test - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "log" - "time" - - "github.com/fsouza/go-dockerclient" -) - -func ExampleClient_AttachToContainer() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - client.SkipServerVersionCheck = true - // Reading logs from container a84849 and sending them to buf. - var buf bytes.Buffer - err = client.AttachToContainer(docker.AttachToContainerOptions{ - Container: "a84849", - OutputStream: &buf, - Logs: true, - Stdout: true, - Stderr: true, - }) - if err != nil { - log.Fatal(err) - } - log.Println(buf.String()) - buf.Reset() - err = client.AttachToContainer(docker.AttachToContainerOptions{ - Container: "a84849", - OutputStream: &buf, - Stdout: true, - Stream: true, - }) - if err != nil { - log.Fatal(err) - } - log.Println(buf.String()) -} - -func ExampleClient_CopyFromContainer() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - cid := "a84849" - var buf bytes.Buffer - filename := "/tmp/output.txt" - err = client.CopyFromContainer(docker.CopyFromContainerOptions{ - Container: cid, - Resource: filename, - OutputStream: &buf, - }) - if err != nil { - log.Fatalf("Error while copying from %s: %s\n", cid, err) - } - content := new(bytes.Buffer) - r := bytes.NewReader(buf.Bytes()) - tr := tar.NewReader(r) - tr.Next() - if err != nil && err != io.EOF { - log.Fatal(err) - } - if _, err := io.Copy(content, tr); err != nil { - log.Fatal(err) - } - log.Println(buf.String()) -} - -func ExampleClient_BuildImage() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - - t := time.Now() - inputbuf, outputbuf := bytes.NewBuffer(nil), bytes.NewBuffer(nil) - tr := tar.NewWriter(inputbuf) - tr.WriteHeader(&tar.Header{Name: "Dockerfile", Size: 10, ModTime: t, AccessTime: t, ChangeTime: t}) - tr.Write([]byte("FROM base\n")) - tr.Close() - opts := docker.BuildImageOptions{ - Name: "test", - InputStream: inputbuf, - OutputStream: outputbuf, - } - if err := client.BuildImage(opts); err != nil { - log.Fatal(err) - } -} - -func ExampleClient_ListenEvents() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - - listener := make(chan *docker.APIEvents) - err = client.AddEventListener(listener) - if err != nil { - log.Fatal(err) - } - - defer func() { - - err = client.RemoveEventListener(listener) - if err != nil { - log.Fatal(err) - } - - }() - - timeout := time.After(1 * time.Second) - - for { - select { - case msg := <-listener: - log.Println(msg) - case <-timeout: - break - } - } - -} - -func ExampleEnv_Map() { - e := docker.Env([]string{"A=1", "B=2", "C=3"}) - envs := e.Map() - for k, v := range envs { - fmt.Printf("%s=%q\n", k, v) - } -} - -func ExampleEnv_SetJSON() { - type Person struct { - Name string - Age int - } - p := Person{Name: "Gopher", Age: 4} - var e docker.Env - err := e.SetJSON("person", p) - if err != nil { - log.Fatal(err) - } -} - -func ExampleEnv_GetJSON() { - type Person struct { - Name string - Age int - } - p := Person{Name: "Gopher", Age: 4} - var e docker.Env - e.Set("person", `{"name":"Gopher","age":4}`) - err := e.GetJSON("person", &p) - if err != nil { - log.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/exec_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/exec_test.go deleted file mode 100644 index 2dc8d2100..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/exec_test.go +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "strings" - "testing" -) - -func TestExecCreate(t *testing.T) { - jsonContainer := `{"Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2"}` - var expected struct{ ID string } - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - config := CreateExecOptions{ - Container: "test", - AttachStdin: true, - AttachStdout: true, - AttachStderr: false, - Tty: false, - Cmd: []string{"touch", "/tmp/file"}, - User: "a-user", - } - execObj, err := client.CreateExec(config) - if err != nil { - t.Fatal(err) - } - expectedID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - if execObj.ID != expectedID { - t.Errorf("ExecCreate: wrong ID. Want %q. Got %q.", expectedID, execObj.ID) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ExecCreate: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/test/exec")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - var gotBody struct{ ID string } - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } -} - -func TestExecStartDetached(t *testing.T) { - execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - config := StartExecOptions{ - Detach: true, - } - err := client.StartExec(execID, config) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ExecStart: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/exec/" + execID + "/start")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - t.Log(req.Body) - var gotBody struct{ Detach bool } - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } - if !gotBody.Detach { - t.Fatal("Expected Detach in StartExecOptions to be true") - } -} - -func TestExecStartAndAttach(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - success := make(chan struct{}) - execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - opts := StartExecOptions{ - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: reader, - RawTerminal: true, - Success: success, - } - go func() { - if err := client.StartExec(execID, opts); err != nil { - t.Error(err) - } - }() - <-success -} - -func TestExecResize(t *testing.T) { - execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - err := client.ResizeExecTTY(execID, 10, 20) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ExecStart: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/exec/" + execID + "/resize?h=10&w=20")) - if gotPath := req.URL.RequestURI(); gotPath != expectedURL.RequestURI() { - t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } -} - -func TestExecInspect(t *testing.T) { - jsonExec := `{ - "ID": "32adfeeec34250f9530ce1dafd40c6233832315e065ea6b362d745e2f63cde0e", - "Running": true, - "ExitCode": 0, - "ProcessConfig": { - "privileged": false, - "user": "", - "tty": true, - "entrypoint": "bash", - "arguments": [] - }, - "OpenStdin": true, - "OpenStderr": true, - "OpenStdout": true, - "Container": { - "State": { - "Running": true, - "Paused": false, - "Restarting": false, - "OOMKilled": false, - "Pid": 29392, - "ExitCode": 0, - "Error": "", - "StartedAt": "2015-01-21T17:08:59.634662178Z", - "FinishedAt": "0001-01-01T00:00:00Z" - }, - "ID": "922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521", - "Created": "2015-01-21T17:08:59.46407212Z", - "Path": "/bin/bash", - "Args": [ - "-lc", - "tsuru_unit_agent http://192.168.50.4:8080 689b30e0ab3adce374346de2e72512138e0e8b75 gtest /var/lib/tsuru/start && tail -f /dev/null" - ], - "Config": { - "Hostname": "922cd0568714", - "Domainname": "", - "User": "ubuntu", - "Memory": 0, - "MemorySwap": 0, - "CpuShares": 100, - "Cpuset": "", - "AttachStdin": false, - "AttachStdout": false, - "AttachStderr": false, - "PortSpecs": null, - "ExposedPorts": { - "8888/tcp": {} - }, - "Tty": false, - "OpenStdin": false, - "StdinOnce": false, - "Env": [ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - ], - "Cmd": [ - "/bin/bash", - "-lc", - "tsuru_unit_agent http://192.168.50.4:8080 689b30e0ab3adce374346de2e72512138e0e8b75 gtest /var/lib/tsuru/start && tail -f /dev/null" - ], - "Image": "tsuru/app-gtest", - "Volumes": null, - "WorkingDir": "", - "Entrypoint": null, - "NetworkDisabled": false, - "MacAddress": "", - "OnBuild": null - }, - "Image": "a88060b8b54fde0f7168c86742d0ce83b80f3f10925d85c98fdad9ed00bef544", - "NetworkSettings": { - "IPAddress": "172.17.0.8", - "IPPrefixLen": 16, - "MacAddress": "02:42:ac:11:00:08", - "LinkLocalIPv6Address": "fe80::42:acff:fe11:8", - "LinkLocalIPv6PrefixLen": 64, - "GlobalIPv6Address": "", - "GlobalIPv6PrefixLen": 0, - "Gateway": "172.17.42.1", - "IPv6Gateway": "", - "Bridge": "docker0", - "PortMapping": null, - "Ports": { - "8888/tcp": [ - { - "HostIp": "0.0.0.0", - "HostPort": "49156" - } - ] - } - }, - "ResolvConfPath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/resolv.conf", - "HostnamePath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/hostname", - "HostsPath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/hosts", - "Name": "/c7e43b72288ee9d0270a", - "Driver": "aufs", - "ExecDriver": "native-0.2", - "MountLabel": "", - "ProcessLabel": "", - "AppArmorProfile": "", - "RestartCount": 0, - "UpdateDns": false, - "Volumes": {}, - "VolumesRW": {} - } - }` - var expected ExecInspect - err := json.Unmarshal([]byte(jsonExec), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonExec, status: http.StatusOK} - client := newTestClient(fakeRT) - expectedID := "32adfeeec34250f9530ce1dafd40c6233832315e065ea6b362d745e2f63cde0e" - execObj, err := client.InspectExec(expectedID) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*execObj, expected) { - t.Errorf("ExecInspect: Expected %#v. Got %#v.", expected, *execObj) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ExecInspect: wrong HTTP method. Want %q. Got %q.", "GET", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/exec/" + expectedID + "/json")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("ExecInspect: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go deleted file mode 100644 index 2b1cc4e1d..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" -) - -func TestEntryWithError(t *testing.T) { - - assert := assert.New(t) - - defer func() { - ErrorKey = "error" - }() - - err := fmt.Errorf("kaboom at layer %d", 4711) - - assert.Equal(err, WithError(err).Data["error"]) - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - - assert.Equal(err, entry.WithError(err).Data["error"]) - - ErrorKey = "err" - - assert.Equal(err, entry.WithError(err).Data["err"]) - -} - -func TestEntryPanicln(t *testing.T) { - errBoom := fmt.Errorf("boom time") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicln("kaboom") -} - -func TestEntryPanicf(t *testing.T) { - errBoom := fmt.Errorf("boom again") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom true", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicf("kaboom %v", true) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go deleted file mode 100644 index c6d290c77..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package logrus - -import ( - "fmt" - "testing" - "time" -) - -// smallFields is a small size data set for benchmarking -var smallFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", -} - -// largeFields is a large size data set for benchmarking -var largeFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", - "five": "six", - "seven": "eight", - "nine": "ten", - "eleven": "twelve", - "thirteen": "fourteen", - "fifteen": "sixteen", - "seventeen": "eighteen", - "nineteen": "twenty", - "a": "b", - "c": "d", - "e": "f", - "g": "h", - "i": "j", - "k": "l", - "m": "n", - "o": "p", - "q": "r", - "s": "t", - "u": "v", - "w": "x", - "y": "z", - "this": "will", - "make": "thirty", - "entries": "yeah", -} - -var errorFields = Fields{ - "foo": fmt.Errorf("bar"), - "baz": fmt.Errorf("qux"), -} - -func BenchmarkErrorTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields) -} - -func BenchmarkSmallTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) -} - -func BenchmarkLargeTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) -} - -func BenchmarkSmallColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) -} - -func BenchmarkLargeColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) -} - -func BenchmarkSmallJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, smallFields) -} - -func BenchmarkLargeJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, largeFields) -} - -func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { - entry := &Entry{ - Time: time.Time{}, - Level: InfoLevel, - Message: "message", - Data: fields, - } - var d []byte - var err error - for i := 0; i < b.N; i++ { - d, err = formatter.Format(entry) - if err != nil { - b.Fatal(err) - } - b.SetBytes(int64(len(d))) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go deleted file mode 100644 index 938b97495..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package logrus - -import ( - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" -) - -type TestHook struct { - Fired bool -} - -func (hook *TestHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *TestHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookFires(t *testing.T) { - hook := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - assert.Equal(t, hook.Fired, false) - - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} - -type ModifyHook struct { -} - -func (hook *ModifyHook) Fire(entry *Entry) error { - entry.Data["wow"] = "whale" - return nil -} - -func (hook *ModifyHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookCanModifyEntry(t *testing.T) { - hook := new(ModifyHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - }) -} - -func TestCanFireMultipleHooks(t *testing.T) { - hook1 := new(ModifyHook) - hook2 := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook1) - log.Hooks.Add(hook2) - - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - assert.Equal(t, hook2.Fired, true) - }) -} - -type ErrorHook struct { - Fired bool -} - -func (hook *ErrorHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *ErrorHook) Levels() []Level { - return []Level{ - ErrorLevel, - } -} - -func TestErrorHookShouldntFireOnInfo(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, false) - }) -} - -func TestErrorHookShouldFireOnError(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Error("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go deleted file mode 100644 index 1d7087325..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package logrus - -import ( - "encoding/json" - "errors" - - "testing" -) - -func TestErrorNotLost(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("error", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["error"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestErrorNotLostOnFieldNotNamedError(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("omg", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["omg"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestFieldClashWithTime(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("time", "right now!")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.time"] != "right now!" { - t.Fatal("fields.time not set to original time field") - } - - if entry["time"] != "0001-01-01T00:00:00Z" { - t.Fatal("time field not set to current time, was: ", entry["time"]) - } -} - -func TestFieldClashWithMsg(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("msg", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.msg"] != "something" { - t.Fatal("fields.msg not set to original msg field") - } -} - -func TestFieldClashWithLevel(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.level"] != "something" { - t.Fatal("fields.level not set to original level field") - } -} - -func TestJSONEntryEndsWithNewline(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - if b[len(b)-1] != '\n' { - t.Fatal("Expected JSON log entry to end with a newline") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go deleted file mode 100644 index e8719b090..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package logrus - -import ( - "bytes" - "encoding/json" - "strconv" - "strings" - "sync" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" -) - -func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - log(logger) - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assertions(fields) -} - -func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { - var buffer bytes.Buffer - - logger := New() - logger.Out = &buffer - logger.Formatter = &TextFormatter{ - DisableColors: true, - } - - log(logger) - - fields := make(map[string]string) - for _, kv := range strings.Split(buffer.String(), " ") { - if !strings.Contains(kv, "=") { - continue - } - kvArr := strings.Split(kv, "=") - key := strings.TrimSpace(kvArr[0]) - val := kvArr[1] - if kvArr[1][0] == '"' { - var err error - val, err = strconv.Unquote(val) - assert.NoError(t, err) - } - fields[key] = val - } - assertions(fields) -} - -func TestPrint(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestInfo(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestWarn(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Warn("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "warning") - }) -} - -func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test test") - }) -} - -func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test 10") - }) -} - -func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "testtest") - }) -} - -func TestWithFieldsShouldAllowAssignments(t *testing.T) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - localLog := logger.WithFields(Fields{ - "key1": "value1", - }) - - localLog.WithField("key2", "value2").Info("test") - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assert.Equal(t, "value2", fields["key2"]) - assert.Equal(t, "value1", fields["key1"]) - - buffer = bytes.Buffer{} - fields = Fields{} - localLog.Info("test") - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - _, ok := fields["key2"] - assert.Equal(t, false, ok) - assert.Equal(t, "value1", fields["key1"]) -} - -func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - }) -} - -func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["fields.msg"], "hello") - }) -} - -func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("time", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["fields.time"], "hello") - }) -} - -func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("level", 1).Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["level"], "info") - assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only - }) -} - -func TestDefaultFieldsAreNotPrefixed(t *testing.T) { - LogAndAssertText(t, func(log *Logger) { - ll := log.WithField("herp", "derp") - ll.Info("hello") - ll.Info("bye") - }, func(fields map[string]string) { - for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { - if _, ok := fields[fieldName]; ok { - t.Fatalf("should not have prefixed %q: %v", fieldName, fields) - } - } - }) -} - -func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { - - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - llog := logger.WithField("context", "eating raw fish") - - llog.Info("looks delicious") - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded first message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "looks delicious") - assert.Equal(t, fields["context"], "eating raw fish") - - buffer.Reset() - - llog.Warn("omg it is!") - - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded second message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "omg it is!") - assert.Equal(t, fields["context"], "eating raw fish") - assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") - -} - -func TestConvertLevelToString(t *testing.T) { - assert.Equal(t, "debug", DebugLevel.String()) - assert.Equal(t, "info", InfoLevel.String()) - assert.Equal(t, "warning", WarnLevel.String()) - assert.Equal(t, "error", ErrorLevel.String()) - assert.Equal(t, "fatal", FatalLevel.String()) - assert.Equal(t, "panic", PanicLevel.String()) -} - -func TestParseLevel(t *testing.T) { - l, err := ParseLevel("panic") - assert.Nil(t, err) - assert.Equal(t, PanicLevel, l) - - l, err = ParseLevel("fatal") - assert.Nil(t, err) - assert.Equal(t, FatalLevel, l) - - l, err = ParseLevel("error") - assert.Nil(t, err) - assert.Equal(t, ErrorLevel, l) - - l, err = ParseLevel("warn") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("warning") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("info") - assert.Nil(t, err) - assert.Equal(t, InfoLevel, l) - - l, err = ParseLevel("debug") - assert.Nil(t, err) - assert.Equal(t, DebugLevel, l) - - l, err = ParseLevel("invalid") - assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) -} - -func TestGetSetLevelRace(t *testing.T) { - wg := sync.WaitGroup{} - for i := 0; i < 100; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - if i%2 == 0 { - SetLevel(InfoLevel) - } else { - GetLevel() - } - }(i) - - } - wg.Wait() -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go deleted file mode 100644 index e25a44f67..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package logrus - -import ( - "bytes" - "errors" - "testing" - "time" -) - -func TestQuoting(t *testing.T) { - tf := &TextFormatter{DisableColors: true} - - checkQuoting := func(q bool, value interface{}) { - b, _ := tf.Format(WithField("test", value)) - idx := bytes.Index(b, ([]byte)("test=")) - cont := bytes.Contains(b[idx+5:], []byte{'"'}) - if cont != q { - if q { - t.Errorf("quoting expected for: %#v", value) - } else { - t.Errorf("quoting not expected for: %#v", value) - } - } - } - - checkQuoting(false, "abcd") - checkQuoting(false, "v1.0") - checkQuoting(false, "1234567890") - checkQuoting(true, "/foobar") - checkQuoting(true, "x y") - checkQuoting(true, "x,y") - checkQuoting(false, errors.New("invalid")) - checkQuoting(true, errors.New("invalid argument")) -} - -func TestTimestampFormat(t *testing.T) { - checkTimeStr := func(format string) { - customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} - customStr, _ := customFormatter.Format(WithField("test", "test")) - timeStart := bytes.Index(customStr, ([]byte)("time=")) - timeEnd := bytes.Index(customStr, ([]byte)("level=")) - timeStr := customStr[timeStart+5 : timeEnd-1] - if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' { - timeStr = timeStr[1 : len(timeStr)-1] - } - if format == "" { - format = time.RFC3339 - } - _, e := time.Parse(format, (string)(timeStr)) - if e != nil { - t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e) - } - } - - checkTimeStr("2006-01-02T15:04:05.000000000Z07:00") - checkTimeStr("Mon Jan _2 15:04:05 2006") - checkTimeStr("") -} - -// TODO add tests for sorting etc., this requires a parser for the text -// formatter output. diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go deleted file mode 100644 index a2e2200fa..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package opts - -import ( - "bufio" - "fmt" - "io/ioutil" - "os" - "reflect" - "strings" - "testing" -) - -func tmpFileWithContent(content string, t *testing.T) string { - tmpFile, err := ioutil.TempFile("", "envfile-test") - if err != nil { - t.Fatal(err) - } - defer tmpFile.Close() - - tmpFile.WriteString(content) - return tmpFile.Name() -} - -// Test ParseEnvFile for a file with a few well formatted lines -func TestParseEnvFileGoodFile(t *testing.T) { - content := `foo=bar - baz=quux -# comment - -_foobar=foobaz -with.dots=working -and_underscore=working too -` - // Adding a newline + a line with pure whitespace. - // This is being done like this instead of the block above - // because it's common for editors to trim trailing whitespace - // from lines, which becomes annoying since that's the - // exact thing we need to test. - content += "\n \t " - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - lines, err := ParseEnvFile(tmpFile) - if err != nil { - t.Fatal(err) - } - - expectedLines := []string{ - "foo=bar", - "baz=quux", - "_foobar=foobaz", - "with.dots=working", - "and_underscore=working too", - } - - if !reflect.DeepEqual(lines, expectedLines) { - t.Fatal("lines not equal to expected_lines") - } -} - -// Test ParseEnvFile for an empty file -func TestParseEnvFileEmptyFile(t *testing.T) { - tmpFile := tmpFileWithContent("", t) - defer os.Remove(tmpFile) - - lines, err := ParseEnvFile(tmpFile) - if err != nil { - t.Fatal(err) - } - - if len(lines) != 0 { - t.Fatal("lines not empty; expected empty") - } -} - -// Test ParseEnvFile for a non existent file -func TestParseEnvFileNonExistentFile(t *testing.T) { - _, err := ParseEnvFile("foo_bar_baz") - if err == nil { - t.Fatal("ParseEnvFile succeeded; expected failure") - } - if _, ok := err.(*os.PathError); !ok { - t.Fatalf("Expected a PathError, got [%v]", err) - } -} - -// Test ParseEnvFile for a badly formatted file -func TestParseEnvFileBadlyFormattedFile(t *testing.T) { - content := `foo=bar - f =quux -` - - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - _, err := ParseEnvFile(tmpFile) - if err == nil { - t.Fatalf("Expected a ErrBadEnvVariable, got nothing") - } - if _, ok := err.(ErrBadEnvVariable); !ok { - t.Fatalf("Expected a ErrBadEnvVariable, got [%v]", err) - } - expectedMessage := "poorly formatted environment: variable 'f ' has white spaces" - if err.Error() != expectedMessage { - t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) - } -} - -// Test ParseEnvFile for a file with a line exceeding bufio.MaxScanTokenSize -func TestParseEnvFileLineTooLongFile(t *testing.T) { - content := strings.Repeat("a", bufio.MaxScanTokenSize+42) - content = fmt.Sprint("foo=", content) - - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - _, err := ParseEnvFile(tmpFile) - if err == nil { - t.Fatal("ParseEnvFile succeeded; expected failure") - } -} - -// ParseEnvFile with a random file, pass through -func TestParseEnvFileRandomFile(t *testing.T) { - content := `first line -another invalid line` - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - _, err := ParseEnvFile(tmpFile) - - if err == nil { - t.Fatalf("Expected a ErrBadEnvVariable, got nothing") - } - if _, ok := err.(ErrBadEnvVariable); !ok { - t.Fatalf("Expected a ErrBadEnvvariable, got [%v]", err) - } - expectedMessage := "poorly formatted environment: variable 'first line' has white spaces" - if err.Error() != expectedMessage { - t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_test.go deleted file mode 100644 index e497e2865..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package opts - -import ( - "runtime" - "testing" -) - -func TestParseHost(t *testing.T) { - invalid := map[string]string{ - "anything": "Invalid bind address format: anything", - "something with spaces": "Invalid bind address format: something with spaces", - "://": "Invalid bind address format: ://", - "unknown://": "Invalid bind address format: unknown://", - "tcp://:port": "Invalid bind address format: :port", - "tcp://invalid": "Invalid bind address format: invalid", - "tcp://invalid:port": "Invalid bind address format: invalid:port", - } - const defaultHTTPHost = "tcp://127.0.0.1:2375" - var defaultHOST = "unix:///var/run/docker.sock" - - if runtime.GOOS == "windows" { - defaultHOST = defaultHTTPHost - } - valid := map[string]string{ - "": defaultHOST, - "fd://": "fd://", - "fd://something": "fd://something", - "tcp://host:": "tcp://host:2375", - "tcp://": "tcp://localhost:2375", - "tcp://:2375": "tcp://localhost:2375", // default ip address - "tcp://:2376": "tcp://localhost:2376", // default ip address - "tcp://0.0.0.0:8080": "tcp://0.0.0.0:8080", - "tcp://192.168.0.0:12000": "tcp://192.168.0.0:12000", - "tcp://192.168:8080": "tcp://192.168:8080", - "tcp://0.0.0.0:1234567890": "tcp://0.0.0.0:1234567890", // yeah it's valid :P - "tcp://docker.com:2375": "tcp://docker.com:2375", - "unix://": "unix:///var/run/docker.sock", // default unix:// value - "unix://path/to/socket": "unix://path/to/socket", - } - - for value, errorMessage := range invalid { - if _, err := ParseHost(defaultHTTPHost, value); err == nil || err.Error() != errorMessage { - t.Fatalf("Expected an error for %v with [%v], got [%v]", value, errorMessage, err) - } - } - for value, expected := range valid { - if actual, err := ParseHost(defaultHTTPHost, value); err != nil || actual != expected { - t.Fatalf("Expected for %v [%v], got [%v, %v]", value, expected, actual, err) - } - } -} - -func TestParseDockerDaemonHost(t *testing.T) { - var ( - defaultHTTPHost = "tcp://localhost:2375" - defaultHTTPSHost = "tcp://localhost:2376" - defaultUnix = "/var/run/docker.sock" - defaultHOST = "unix:///var/run/docker.sock" - ) - if runtime.GOOS == "windows" { - defaultHOST = defaultHTTPHost - } - invalids := map[string]string{ - "0.0.0.0": "Invalid bind address format: 0.0.0.0", - "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", - "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", - "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1", - "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375", - "tcp://unix:///run/docker.sock": "Invalid bind address format: unix", - "tcp": "Invalid bind address format: tcp", - "unix": "Invalid bind address format: unix", - "fd": "Invalid bind address format: fd", - } - valids := map[string]string{ - "0.0.0.1:": "tcp://0.0.0.1:2375", - "0.0.0.1:5555": "tcp://0.0.0.1:5555", - "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", - "[::1]:": "tcp://[::1]:2375", - "[::1]:5555/path": "tcp://[::1]:5555/path", - "[0:0:0:0:0:0:0:1]:": "tcp://[0:0:0:0:0:0:0:1]:2375", - "[0:0:0:0:0:0:0:1]:5555/path": "tcp://[0:0:0:0:0:0:0:1]:5555/path", - ":6666": "tcp://localhost:6666", - ":6666/path": "tcp://localhost:6666/path", - "": defaultHOST, - " ": defaultHOST, - " ": defaultHOST, - "tcp://": defaultHTTPHost, - "tcp://:7777": "tcp://localhost:7777", - "tcp://:7777/path": "tcp://localhost:7777/path", - " tcp://:7777/path ": "tcp://localhost:7777/path", - "unix:///run/docker.sock": "unix:///run/docker.sock", - "unix://": "unix:///var/run/docker.sock", - "fd://": "fd://", - "fd://something": "fd://something", - "localhost:": "tcp://localhost:2375", - "localhost:5555": "tcp://localhost:5555", - "localhost:5555/path": "tcp://localhost:5555/path", - } - for invalidAddr, expectedError := range invalids { - if addr, err := parseDockerDaemonHost(defaultHTTPHost, defaultHTTPSHost, defaultUnix, "", invalidAddr); err == nil || err.Error() != expectedError { - t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr) - } - } - for validAddr, expectedAddr := range valids { - if addr, err := parseDockerDaemonHost(defaultHTTPHost, defaultHTTPSHost, defaultUnix, "", validAddr); err != nil || addr != expectedAddr { - t.Errorf("%v -> expected %v, got (%v) addr (%v)", validAddr, expectedAddr, err, addr) - } - } -} - -func TestParseTCP(t *testing.T) { - var ( - defaultHTTPHost = "tcp://127.0.0.1:2376" - ) - invalids := map[string]string{ - "0.0.0.0": "Invalid bind address format: 0.0.0.0", - "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", - "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", - "udp://127.0.0.1": "Invalid proto, expected tcp: udp://127.0.0.1", - "udp://127.0.0.1:2375": "Invalid proto, expected tcp: udp://127.0.0.1:2375", - } - valids := map[string]string{ - "": defaultHTTPHost, - "tcp://": defaultHTTPHost, - "0.0.0.1:": "tcp://0.0.0.1:2376", - "0.0.0.1:5555": "tcp://0.0.0.1:5555", - "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", - ":6666": "tcp://127.0.0.1:6666", - ":6666/path": "tcp://127.0.0.1:6666/path", - "tcp://:7777": "tcp://127.0.0.1:7777", - "tcp://:7777/path": "tcp://127.0.0.1:7777/path", - "[::1]:": "tcp://[::1]:2376", - "[::1]:5555": "tcp://[::1]:5555", - "[::1]:5555/path": "tcp://[::1]:5555/path", - "[0:0:0:0:0:0:0:1]:": "tcp://[0:0:0:0:0:0:0:1]:2376", - "[0:0:0:0:0:0:0:1]:5555": "tcp://[0:0:0:0:0:0:0:1]:5555", - "[0:0:0:0:0:0:0:1]:5555/path": "tcp://[0:0:0:0:0:0:0:1]:5555/path", - "localhost:": "tcp://localhost:2376", - "localhost:5555": "tcp://localhost:5555", - "localhost:5555/path": "tcp://localhost:5555/path", - } - for invalidAddr, expectedError := range invalids { - if addr, err := parseTCPAddr(invalidAddr, defaultHTTPHost); err == nil || err.Error() != expectedError { - t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr) - } - } - for validAddr, expectedAddr := range valids { - if addr, err := parseTCPAddr(validAddr, defaultHTTPHost); err != nil || addr != expectedAddr { - t.Errorf("%v -> expected %v, got %v and addr %v", validAddr, expectedAddr, err, addr) - } - } -} - -func TestParseInvalidUnixAddrInvalid(t *testing.T) { - if _, err := parseUnixAddr("tcp://127.0.0.1", "unix:///var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" { - t.Fatalf("Expected an error, got %v", err) - } - if _, err := parseUnixAddr("unix://tcp://127.0.0.1", "/var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" { - t.Fatalf("Expected an error, got %v", err) - } - if v, err := parseUnixAddr("", "/var/run/docker.sock"); err != nil || v != "unix:///var/run/docker.sock" { - t.Fatalf("Expected an %v, got %v", v, "unix:///var/run/docker.sock") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go deleted file mode 100644 index 1027d84a0..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package opts - -import ( - "net" - "testing" -) - -func TestIpOptString(t *testing.T) { - addresses := []string{"", "0.0.0.0"} - var ip net.IP - - for _, address := range addresses { - stringAddress := NewIPOpt(&ip, address).String() - if stringAddress != address { - t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress) - } - } -} - -func TestNewIpOptInvalidDefaultVal(t *testing.T) { - ip := net.IPv4(127, 0, 0, 1) - defaultVal := "Not an ip" - - ipOpt := NewIPOpt(&ip, defaultVal) - - expected := "127.0.0.1" - if ipOpt.String() != expected { - t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) - } -} - -func TestNewIpOptValidDefaultVal(t *testing.T) { - ip := net.IPv4(127, 0, 0, 1) - defaultVal := "192.168.1.1" - - ipOpt := NewIPOpt(&ip, defaultVal) - - expected := "192.168.1.1" - if ipOpt.String() != expected { - t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) - } -} - -func TestIpOptSetInvalidVal(t *testing.T) { - ip := net.IPv4(127, 0, 0, 1) - ipOpt := &IPOpt{IP: &ip} - - invalidIP := "invalid ip" - expectedError := "invalid ip is not an ip address" - err := ipOpt.Set(invalidIP) - if err == nil || err.Error() != expectedError { - t.Fatalf("Expected an Error with [%v], got [%v]", expectedError, err.Error()) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go deleted file mode 100644 index e2af1c11d..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package opts - -import ( - "fmt" - "os" - "strings" - "testing" -) - -func TestValidateIPAddress(t *testing.T) { - if ret, err := ValidateIPAddress(`1.2.3.4`); err != nil || ret == "" { - t.Fatalf("ValidateIPAddress(`1.2.3.4`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`127.0.0.1`); err != nil || ret == "" { - t.Fatalf("ValidateIPAddress(`127.0.0.1`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`::1`); err != nil || ret == "" { - t.Fatalf("ValidateIPAddress(`::1`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`127`); err == nil || ret != "" { - t.Fatalf("ValidateIPAddress(`127`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`random invalid string`); err == nil || ret != "" { - t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err) - } - -} - -func TestMapOpts(t *testing.T) { - tmpMap := make(map[string]string) - o := NewMapOpts(tmpMap, logOptsValidator) - o.Set("max-size=1") - if o.String() != "map[max-size:1]" { - t.Errorf("%s != [map[max-size:1]", o.String()) - } - - o.Set("max-file=2") - if len(tmpMap) != 2 { - t.Errorf("map length %d != 2", len(tmpMap)) - } - - if tmpMap["max-file"] != "2" { - t.Errorf("max-file = %s != 2", tmpMap["max-file"]) - } - - if tmpMap["max-size"] != "1" { - t.Errorf("max-size = %s != 1", tmpMap["max-size"]) - } - if o.Set("dummy-val=3") == nil { - t.Errorf("validator is not being called") - } -} - -func TestValidateMACAddress(t *testing.T) { - if _, err := ValidateMACAddress(`92:d0:c6:0a:29:33`); err != nil { - t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:29:33`) got %s", err) - } - - if _, err := ValidateMACAddress(`92:d0:c6:0a:33`); err == nil { - t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:33`) succeeded; expected failure on invalid MAC") - } - - if _, err := ValidateMACAddress(`random invalid string`); err == nil { - t.Fatalf("ValidateMACAddress(`random invalid string`) succeeded; expected failure on invalid MAC") - } -} - -func TestListOptsWithoutValidator(t *testing.T) { - o := NewListOpts(nil) - o.Set("foo") - if o.String() != "[foo]" { - t.Errorf("%s != [foo]", o.String()) - } - o.Set("bar") - if o.Len() != 2 { - t.Errorf("%d != 2", o.Len()) - } - o.Set("bar") - if o.Len() != 3 { - t.Errorf("%d != 3", o.Len()) - } - if !o.Get("bar") { - t.Error("o.Get(\"bar\") == false") - } - if o.Get("baz") { - t.Error("o.Get(\"baz\") == true") - } - o.Delete("foo") - if o.String() != "[bar bar]" { - t.Errorf("%s != [bar bar]", o.String()) - } - listOpts := o.GetAll() - if len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" { - t.Errorf("Expected [[bar bar]], got [%v]", listOpts) - } - mapListOpts := o.GetMap() - if len(mapListOpts) != 1 { - t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts) - } - -} - -func TestListOptsWithValidator(t *testing.T) { - // Re-using logOptsvalidator (used by MapOpts) - o := NewListOpts(logOptsValidator) - o.Set("foo") - if o.String() != "[]" { - t.Errorf("%s != []", o.String()) - } - o.Set("foo=bar") - if o.String() != "[]" { - t.Errorf("%s != []", o.String()) - } - o.Set("max-file=2") - if o.Len() != 1 { - t.Errorf("%d != 1", o.Len()) - } - if !o.Get("max-file=2") { - t.Error("o.Get(\"max-file=2\") == false") - } - if o.Get("baz") { - t.Error("o.Get(\"baz\") == true") - } - o.Delete("max-file=2") - if o.String() != "[]" { - t.Errorf("%s != []", o.String()) - } -} - -func TestValidateDNSSearch(t *testing.T) { - valid := []string{ - `.`, - `a`, - `a.`, - `1.foo`, - `17.foo`, - `foo.bar`, - `foo.bar.baz`, - `foo.bar.`, - `foo.bar.baz`, - `foo1.bar2`, - `foo1.bar2.baz`, - `1foo.2bar.`, - `1foo.2bar.baz`, - `foo-1.bar-2`, - `foo-1.bar-2.baz`, - `foo-1.bar-2.`, - `foo-1.bar-2.baz`, - `1-foo.2-bar`, - `1-foo.2-bar.baz`, - `1-foo.2-bar.`, - `1-foo.2-bar.baz`, - } - - invalid := []string{ - ``, - ` `, - ` `, - `17`, - `17.`, - `.17`, - `17-.`, - `17-.foo`, - `.foo`, - `foo-.bar`, - `-foo.bar`, - `foo.bar-`, - `foo.bar-.baz`, - `foo.-bar`, - `foo.-bar.baz`, - `foo.bar.baz.this.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbe`, - } - - for _, domain := range valid { - if ret, err := ValidateDNSSearch(domain); err != nil || ret == "" { - t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) - } - } - - for _, domain := range invalid { - if ret, err := ValidateDNSSearch(domain); err == nil || ret != "" { - t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) - } - } -} - -func TestValidateExtraHosts(t *testing.T) { - valid := []string{ - `myhost:192.168.0.1`, - `thathost:10.0.2.1`, - `anipv6host:2003:ab34:e::1`, - `ipv6local:::1`, - } - - invalid := map[string]string{ - `myhost:192.notanipaddress.1`: `invalid IP`, - `thathost-nosemicolon10.0.0.1`: `bad format`, - `anipv6host:::::1`: `invalid IP`, - `ipv6local:::0::`: `invalid IP`, - } - - for _, extrahost := range valid { - if _, err := ValidateExtraHost(extrahost); err != nil { - t.Fatalf("ValidateExtraHost(`"+extrahost+"`) should succeed: error %v", err) - } - } - - for extraHost, expectedError := range invalid { - if _, err := ValidateExtraHost(extraHost); err == nil { - t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost) - } else { - if !strings.Contains(err.Error(), expectedError) { - t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError) - } - } - } -} - -func TestValidateAttach(t *testing.T) { - valid := []string{ - "stdin", - "stdout", - "stderr", - "STDIN", - "STDOUT", - "STDERR", - } - if _, err := ValidateAttach("invalid"); err == nil { - t.Fatalf("Expected error with [valid streams are STDIN, STDOUT and STDERR], got nothing") - } - - for _, attach := range valid { - value, err := ValidateAttach(attach) - if err != nil { - t.Fatal(err) - } - if value != strings.ToLower(attach) { - t.Fatalf("Expected [%v], got [%v]", attach, value) - } - } -} - -func TestValidateEnv(t *testing.T) { - valids := map[string]string{ - "a": "a", - "something": "something", - "_=a": "_=a", - "env1=value1": "env1=value1", - "_env1=value1": "_env1=value1", - "env2=value2=value3": "env2=value2=value3", - "env3=abc!qwe": "env3=abc!qwe", - "env_4=value 4": "env_4=value 4", - "PATH": fmt.Sprintf("PATH=%v", os.Getenv("PATH")), - "PATH=something": "PATH=something", - "asd!qwe": "asd!qwe", - "1asd": "1asd", - "123": "123", - "some space": "some space", - " some space before": " some space before", - "some space after ": "some space after ", - } - for value, expected := range valids { - actual, err := ValidateEnv(value) - if err != nil { - t.Fatal(err) - } - if actual != expected { - t.Fatalf("Expected [%v], got [%v]", expected, actual) - } - } -} - -func TestValidateLabel(t *testing.T) { - if _, err := ValidateLabel("label"); err == nil || err.Error() != "bad attribute format: label" { - t.Fatalf("Expected an error [bad attribute format: label], go %v", err) - } - if actual, err := ValidateLabel("key1=value1"); err != nil || actual != "key1=value1" { - t.Fatalf("Expected [key1=value1], got [%v,%v]", actual, err) - } - // Validate it's working with more than one = - if actual, err := ValidateLabel("key1=value1=value2"); err != nil { - t.Fatalf("Expected [key1=value1=value2], got [%v,%v]", actual, err) - } - // Validate it's working with one more - if actual, err := ValidateLabel("key1=value1=value2=value3"); err != nil { - t.Fatalf("Expected [key1=value1=value2=value2], got [%v,%v]", actual, err) - } -} - -func logOptsValidator(val string) (string, error) { - allowedKeys := map[string]string{"max-size": "1", "max-file": "2"} - vals := strings.Split(val, "=") - if allowedKeys[vals[0]] != "" { - return val, nil - } - return "", fmt.Errorf("invalid key %s", vals[0]) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go deleted file mode 100644 index 94deff3f4..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go +++ /dev/null @@ -1,1248 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - "syscall" - "testing" - "time" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -func TestIsArchiveNilHeader(t *testing.T) { - out := IsArchive(nil) - if out { - t.Fatalf("isArchive should return false as nil is not a valid archive header") - } -} - -func TestIsArchiveInvalidHeader(t *testing.T) { - header := []byte{0x00, 0x01, 0x02} - out := IsArchive(header) - if out { - t.Fatalf("isArchive should return false as %s is not a valid archive header", header) - } -} - -func TestIsArchiveBzip2(t *testing.T) { - header := []byte{0x42, 0x5A, 0x68} - out := IsArchive(header) - if !out { - t.Fatalf("isArchive should return true as %s is a bz2 header", header) - } -} - -func TestIsArchive7zip(t *testing.T) { - header := []byte{0x50, 0x4b, 0x03, 0x04} - out := IsArchive(header) - if out { - t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header) - } -} - -func TestIsArchivePathDir(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "mkdir -p /tmp/archivedir") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - if IsArchivePath("/tmp/archivedir") { - t.Fatalf("Incorrectly recognised directory as an archive") - } -} - -func TestIsArchivePathInvalidFile(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1K count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - if IsArchivePath("/tmp/archive") { - t.Fatalf("Incorrectly recognised invalid tar path as archive") - } - if IsArchivePath("/tmp/archive.gz") { - t.Fatalf("Incorrectly recognised invalid compressed tar path as archive") - } -} - -func TestIsArchivePathTar(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archivedata && tar -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - if !IsArchivePath("/tmp/archive") { - t.Fatalf("Did not recognise valid tar path as archive") - } - if !IsArchivePath("/tmp/archive.gz") { - t.Fatalf("Did not recognise valid compressed tar path as archive") - } -} - -func TestDecompressStreamGzip(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && gzip -f /tmp/archive") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - archive, err := os.Open("/tmp/archive.gz") - _, err = DecompressStream(archive) - if err != nil { - t.Fatalf("Failed to decompress a gzip file.") - } -} - -func TestDecompressStreamBzip2(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && bzip2 -f /tmp/archive") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - archive, err := os.Open("/tmp/archive.bz2") - _, err = DecompressStream(archive) - if err != nil { - t.Fatalf("Failed to decompress a bzip2 file.") - } -} - -func TestDecompressStreamXz(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && xz -f /tmp/archive") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - archive, err := os.Open("/tmp/archive.xz") - _, err = DecompressStream(archive) - if err != nil { - t.Fatalf("Failed to decompress a xz file.") - } -} - -func TestCompressStreamXzUnsuported(t *testing.T) { - dest, err := os.Create("/tmp/dest") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - _, err = CompressStream(dest, Xz) - if err == nil { - t.Fatalf("Should fail as xz is unsupported for compression format.") - } -} - -func TestCompressStreamBzip2Unsupported(t *testing.T) { - dest, err := os.Create("/tmp/dest") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - _, err = CompressStream(dest, Xz) - if err == nil { - t.Fatalf("Should fail as xz is unsupported for compression format.") - } -} - -func TestCompressStreamInvalid(t *testing.T) { - dest, err := os.Create("/tmp/dest") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - _, err = CompressStream(dest, -1) - if err == nil { - t.Fatalf("Should fail as xz is unsupported for compression format.") - } -} - -func TestExtensionInvalid(t *testing.T) { - compression := Compression(-1) - output := compression.Extension() - if output != "" { - t.Fatalf("The extension of an invalid compression should be an empty string.") - } -} - -func TestExtensionUncompressed(t *testing.T) { - compression := Uncompressed - output := compression.Extension() - if output != "tar" { - t.Fatalf("The extension of a uncompressed archive should be 'tar'.") - } -} -func TestExtensionBzip2(t *testing.T) { - compression := Bzip2 - output := compression.Extension() - if output != "tar.bz2" { - t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'") - } -} -func TestExtensionGzip(t *testing.T) { - compression := Gzip - output := compression.Extension() - if output != "tar.gz" { - t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'") - } -} -func TestExtensionXz(t *testing.T) { - compression := Xz - output := compression.Extension() - if output != "tar.xz" { - t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'") - } -} - -func TestCmdStreamLargeStderr(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello") - out, _, err := cmdStream(cmd, nil) - if err != nil { - t.Fatalf("Failed to start command: %s", err) - } - errCh := make(chan error) - go func() { - _, err := io.Copy(ioutil.Discard, out) - errCh <- err - }() - select { - case err := <-errCh: - if err != nil { - t.Fatalf("Command should not have failed (err=%.100s...)", err) - } - case <-time.After(5 * time.Second): - t.Fatalf("Command did not complete in 5 seconds; probable deadlock") - } -} - -func TestCmdStreamBad(t *testing.T) { - badCmd := exec.Command("/bin/sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1") - out, _, err := cmdStream(badCmd, nil) - if err != nil { - t.Fatalf("Failed to start command: %s", err) - } - if output, err := ioutil.ReadAll(out); err == nil { - t.Fatalf("Command should have failed") - } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" { - t.Fatalf("Wrong error value (%s)", err) - } else if s := string(output); s != "hello\n" { - t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) - } -} - -func TestCmdStreamGood(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "echo hello; exit 0") - out, _, err := cmdStream(cmd, nil) - if err != nil { - t.Fatal(err) - } - if output, err := ioutil.ReadAll(out); err != nil { - t.Fatalf("Command should not have failed (err=%s)", err) - } else if s := string(output); s != "hello\n" { - t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) - } -} - -func TestUntarPathWithInvalidDest(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - invalidDestFolder := path.Join(tempFolder, "invalidDest") - // Create a src file - srcFile := path.Join(tempFolder, "src") - tarFile := path.Join(tempFolder, "src.tar") - os.Create(srcFile) - os.Create(invalidDestFolder) // being a file (not dir) should cause an error - cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) - _, err = cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - - err = UntarPath(tarFile, invalidDestFolder) - if err == nil { - t.Fatalf("UntarPath with invalid destination path should throw an error.") - } -} - -func TestUntarPathWithInvalidSrc(t *testing.T) { - dest, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - defer os.RemoveAll(dest) - err = UntarPath("/invalid/path", dest) - if err == nil { - t.Fatalf("UntarPath with invalid src path should throw an error.") - } -} - -func TestUntarPath(t *testing.T) { - tmpFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpFolder) - srcFile := path.Join(tmpFolder, "src") - tarFile := path.Join(tmpFolder, "src.tar") - os.Create(path.Join(tmpFolder, "src")) - cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) - _, err = cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - destFolder := path.Join(tmpFolder, "dest") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatalf("Fail to create the destination file") - } - err = UntarPath(tarFile, destFolder) - if err != nil { - t.Fatalf("UntarPath shouldn't throw an error, %s.", err) - } - expectedFile := path.Join(destFolder, srcFile) - _, err = os.Stat(expectedFile) - if err != nil { - t.Fatalf("Destination folder should contain the source file but did not.") - } -} - -// Do the same test as above but with the destination as file, it should fail -func TestUntarPathWithDestinationFile(t *testing.T) { - tmpFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpFolder) - srcFile := path.Join(tmpFolder, "src") - tarFile := path.Join(tmpFolder, "src.tar") - os.Create(path.Join(tmpFolder, "src")) - cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) - _, err = cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - destFile := path.Join(tmpFolder, "dest") - _, err = os.Create(destFile) - if err != nil { - t.Fatalf("Fail to create the destination file") - } - err = UntarPath(tarFile, destFile) - if err == nil { - t.Fatalf("UntarPath should throw an error if the destination if a file") - } -} - -// Do the same test as above but with the destination folder already exists -// and the destination file is a directory -// It's working, see https://github.com/docker/docker/issues/10040 -func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) { - tmpFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpFolder) - srcFile := path.Join(tmpFolder, "src") - tarFile := path.Join(tmpFolder, "src.tar") - os.Create(srcFile) - cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) - _, err = cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - destFolder := path.Join(tmpFolder, "dest") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatalf("Fail to create the destination folder") - } - // Let's create a folder that will has the same path as the extracted file (from tar) - destSrcFileAsFolder := path.Join(destFolder, srcFile) - err = os.MkdirAll(destSrcFileAsFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = UntarPath(tarFile, destFolder) - if err != nil { - t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder") - } -} - -func TestCopyWithTarInvalidSrc(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(nil) - } - destFolder := path.Join(tempFolder, "dest") - invalidSrc := path.Join(tempFolder, "doesnotexists") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = CopyWithTar(invalidSrc, destFolder) - if err == nil { - t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") - } -} - -func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(nil) - } - srcFolder := path.Join(tempFolder, "src") - inexistentDestFolder := path.Join(tempFolder, "doesnotexists") - err = os.MkdirAll(srcFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = CopyWithTar(srcFolder, inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") - } - _, err = os.Stat(inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder should create it.") - } -} - -// Test CopyWithTar with a file as src -func TestCopyWithTarSrcFile(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - srcFolder := path.Join(folder, "src") - src := path.Join(folder, path.Join("src", "src")) - err = os.MkdirAll(srcFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - ioutil.WriteFile(src, []byte("content"), 0777) - err = CopyWithTar(src, dest) - if err != nil { - t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) - } - _, err = os.Stat(dest) - // FIXME Check the content - if err != nil { - t.Fatalf("Destination file should be the same as the source.") - } -} - -// Test CopyWithTar with a folder as src -func TestCopyWithTarSrcFolder(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - src := path.Join(folder, path.Join("src", "folder")) - err = os.MkdirAll(src, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - ioutil.WriteFile(path.Join(src, "file"), []byte("content"), 0777) - err = CopyWithTar(src, dest) - if err != nil { - t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) - } - _, err = os.Stat(dest) - // FIXME Check the content (the file inside) - if err != nil { - t.Fatalf("Destination folder should contain the source file but did not.") - } -} - -func TestCopyFileWithTarInvalidSrc(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - destFolder := path.Join(tempFolder, "dest") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatal(err) - } - invalidFile := path.Join(tempFolder, "doesnotexists") - err = CopyFileWithTar(invalidFile, destFolder) - if err == nil { - t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") - } -} - -func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(nil) - } - defer os.RemoveAll(tempFolder) - srcFile := path.Join(tempFolder, "src") - inexistentDestFolder := path.Join(tempFolder, "doesnotexists") - _, err = os.Create(srcFile) - if err != nil { - t.Fatal(err) - } - err = CopyFileWithTar(srcFile, inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") - } - _, err = os.Stat(inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder should create it.") - } - // FIXME Test the src file and content -} - -func TestCopyFileWithTarSrcFolder(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - src := path.Join(folder, "srcfolder") - err = os.MkdirAll(src, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - err = CopyFileWithTar(src, dest) - if err == nil { - t.Fatalf("CopyFileWithTar should throw an error with a folder.") - } -} - -func TestCopyFileWithTarSrcFile(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - srcFolder := path.Join(folder, "src") - src := path.Join(folder, path.Join("src", "src")) - err = os.MkdirAll(srcFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - ioutil.WriteFile(src, []byte("content"), 0777) - err = CopyWithTar(src, dest+"/") - if err != nil { - t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err) - } - _, err = os.Stat(dest) - if err != nil { - t.Fatalf("Destination folder should contain the source file but did not.") - } -} - -func TestTarFiles(t *testing.T) { - // try without hardlinks - if err := checkNoChanges(1000, false); err != nil { - t.Fatal(err) - } - // try with hardlinks - if err := checkNoChanges(1000, true); err != nil { - t.Fatal(err) - } -} - -func checkNoChanges(fileNum int, hardlinks bool) error { - srcDir, err := ioutil.TempDir("", "docker-test-srcDir") - if err != nil { - return err - } - defer os.RemoveAll(srcDir) - - destDir, err := ioutil.TempDir("", "docker-test-destDir") - if err != nil { - return err - } - defer os.RemoveAll(destDir) - - _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks) - if err != nil { - return err - } - - err = TarUntar(srcDir, destDir) - if err != nil { - return err - } - - changes, err := ChangesDirs(destDir, srcDir) - if err != nil { - return err - } - if len(changes) > 0 { - return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes)) - } - return nil -} - -func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) { - archive, err := TarWithOptions(origin, options) - if err != nil { - t.Fatal(err) - } - defer archive.Close() - - buf := make([]byte, 10) - if _, err := archive.Read(buf); err != nil { - return nil, err - } - wrap := io.MultiReader(bytes.NewReader(buf), archive) - - detectedCompression := DetectCompression(buf) - compression := options.Compression - if detectedCompression.Extension() != compression.Extension() { - return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension()) - } - - tmp, err := ioutil.TempDir("", "docker-test-untar") - if err != nil { - return nil, err - } - defer os.RemoveAll(tmp) - if err := Untar(wrap, tmp, nil); err != nil { - return nil, err - } - if _, err := os.Stat(tmp); err != nil { - return nil, err - } - - return ChangesDirs(origin, tmp) -} - -func TestTarUntar(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { - t.Fatal(err) - } - - for _, c := range []Compression{ - Uncompressed, - Gzip, - } { - changes, err := tarUntar(t, origin, &TarOptions{ - Compression: c, - ExcludePatterns: []string{"3"}, - }) - - if err != nil { - t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) - } - - if len(changes) != 1 || changes[0].Path != "/3" { - t.Fatalf("Unexpected differences after tarUntar: %v", changes) - } - } -} - -func TestTarUntarWithXattr(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { - t.Fatal(err) - } - if err := system.Lsetxattr(path.Join(origin, "2"), "security.capability", []byte{0x00}, 0); err != nil { - t.Fatal(err) - } - - for _, c := range []Compression{ - Uncompressed, - Gzip, - } { - changes, err := tarUntar(t, origin, &TarOptions{ - Compression: c, - ExcludePatterns: []string{"3"}, - }) - - if err != nil { - t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) - } - - if len(changes) != 1 || changes[0].Path != "/3" { - t.Fatalf("Unexpected differences after tarUntar: %v", changes) - } - capability, _ := system.Lgetxattr(path.Join(origin, "2"), "security.capability") - if capability == nil && capability[0] != 0x00 { - t.Fatalf("Untar should have kept the 'security.capability' xattr.") - } - } -} - -func TestTarWithOptions(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - t.Fatal(err) - } - if _, err := ioutil.TempDir(origin, "folder"); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { - t.Fatal(err) - } - - cases := []struct { - opts *TarOptions - numChanges int - }{ - {&TarOptions{IncludeFiles: []string{"1"}}, 2}, - {&TarOptions{ExcludePatterns: []string{"2"}}, 1}, - {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2}, - {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2}, - {&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4}, - } - for _, testCase := range cases { - changes, err := tarUntar(t, origin, testCase.opts) - if err != nil { - t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err) - } - if len(changes) != testCase.numChanges { - t.Errorf("Expected %d changes, got %d for %+v:", - testCase.numChanges, len(changes), testCase.opts) - } - } -} - -// Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz -// use PAX Global Extended Headers. -// Failing prevents the archives from being uncompressed during ADD -func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) { - hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader} - tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir) - err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil) - if err != nil { - t.Fatal(err) - } -} - -// Some tar have both GNU specific (huge uid) and Ustar specific (long name) things. -// Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work. -func TestUntarUstarGnuConflict(t *testing.T) { - f, err := os.Open("testdata/broken.tar") - if err != nil { - t.Fatal(err) - } - found := false - tr := tar.NewReader(f) - // Iterate through the files in the archive. - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - t.Fatal(err) - } - if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" { - found = true - break - } - } - if !found { - t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm") - } -} - -func TestTarWithBlockCharFifo(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := system.Mknod(path.Join(origin, "2"), syscall.S_IFBLK, int(system.Mkdev(int64(12), int64(5)))); err != nil { - t.Fatal(err) - } - if err := system.Mknod(path.Join(origin, "3"), syscall.S_IFCHR, int(system.Mkdev(int64(12), int64(5)))); err != nil { - t.Fatal(err) - } - if err := system.Mknod(path.Join(origin, "4"), syscall.S_IFIFO, int(system.Mkdev(int64(12), int64(5)))); err != nil { - t.Fatal(err) - } - - dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dest) - - // we'll do this in two steps to separate failure - fh, err := Tar(origin, Uncompressed) - if err != nil { - t.Fatal(err) - } - - // ensure we can read the whole thing with no error, before writing back out - buf, err := ioutil.ReadAll(fh) - if err != nil { - t.Fatal(err) - } - - bRdr := bytes.NewReader(buf) - err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) - if err != nil { - t.Fatal(err) - } - - changes, err := ChangesDirs(origin, dest) - if err != nil { - t.Fatal(err) - } - if len(changes) > 0 { - t.Fatalf("Tar with special device (block, char, fifo) should keep them (recreate them when untar) : %v", changes) - } -} - -func TestTarWithHardLink(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := os.Link(path.Join(origin, "1"), path.Join(origin, "2")); err != nil { - t.Fatal(err) - } - - var i1, i2 uint64 - if i1, err = getNlink(path.Join(origin, "1")); err != nil { - t.Fatal(err) - } - // sanity check that we can hardlink - if i1 != 2 { - t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1) - } - - dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dest) - - // we'll do this in two steps to separate failure - fh, err := Tar(origin, Uncompressed) - if err != nil { - t.Fatal(err) - } - - // ensure we can read the whole thing with no error, before writing back out - buf, err := ioutil.ReadAll(fh) - if err != nil { - t.Fatal(err) - } - - bRdr := bytes.NewReader(buf) - err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) - if err != nil { - t.Fatal(err) - } - - if i1, err = getInode(path.Join(dest, "1")); err != nil { - t.Fatal(err) - } - if i2, err = getInode(path.Join(dest, "2")); err != nil { - t.Fatal(err) - } - - if i1 != i2 { - t.Errorf("expected matching inodes, but got %d and %d", i1, i2) - } -} - -func getNlink(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - statT, ok := stat.Sys().(*syscall.Stat_t) - if !ok { - return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) - } - // We need this conversion on ARM64 - return uint64(statT.Nlink), nil -} - -func getInode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - statT, ok := stat.Sys().(*syscall.Stat_t) - if !ok { - return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) - } - return statT.Ino, nil -} - -func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) { - fileData := []byte("fooo") - for n := 0; n < numberOfFiles; n++ { - fileName := fmt.Sprintf("file-%d", n) - if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { - return 0, err - } - if makeLinks { - if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil { - return 0, err - } - } - } - totalSize := numberOfFiles * len(fileData) - return totalSize, nil -} - -func BenchmarkTarUntar(b *testing.B) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - b.Fatal(err) - } - tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") - if err != nil { - b.Fatal(err) - } - target := path.Join(tempDir, "dest") - n, err := prepareUntarSourceDirectory(100, origin, false) - if err != nil { - b.Fatal(err) - } - defer os.RemoveAll(origin) - defer os.RemoveAll(tempDir) - - b.ResetTimer() - b.SetBytes(int64(n)) - for n := 0; n < b.N; n++ { - err := TarUntar(origin, target) - if err != nil { - b.Fatal(err) - } - os.RemoveAll(target) - } -} - -func BenchmarkTarUntarWithLinks(b *testing.B) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - b.Fatal(err) - } - tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") - if err != nil { - b.Fatal(err) - } - target := path.Join(tempDir, "dest") - n, err := prepareUntarSourceDirectory(100, origin, true) - if err != nil { - b.Fatal(err) - } - defer os.RemoveAll(origin) - defer os.RemoveAll(tempDir) - - b.ResetTimer() - b.SetBytes(int64(n)) - for n := 0; n < b.N; n++ { - err := TarUntar(origin, target) - if err != nil { - b.Fatal(err) - } - os.RemoveAll(target) - } -} - -func TestUntarInvalidFilenames(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { - { - Name: "../victim/dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { - { - // Note the leading slash - Name: "/../victim/slash-dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestUntarHardlinkToSymlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { - { - Name: "symlink1", - Typeflag: tar.TypeSymlink, - Linkname: "regfile", - Mode: 0644, - }, - { - Name: "symlink2", - Typeflag: tar.TypeLink, - Linkname: "symlink1", - Mode: 0644, - }, - { - Name: "regfile", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestUntarInvalidHardlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeLink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeLink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (hardlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try reading victim/hello (hardlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try removing victim directory (hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestUntarInvalidSymlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeSymlink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeSymlink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try removing victim directory (symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try writing to victim/newdir/newfile with a symlink in the path - { - // this header needs to be before the next one, or else there is an error - Name: "dir/loophole", - Typeflag: tar.TypeSymlink, - Linkname: "../../victim", - Mode: 0755, - }, - { - Name: "dir/loophole/newdir/newfile", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestTempArchiveCloseMultipleTimes(t *testing.T) { - reader := ioutil.NopCloser(strings.NewReader("hello")) - tempArchive, err := NewTempArchive(reader, "") - buf := make([]byte, 10) - n, err := tempArchive.Read(buf) - if n != 5 { - t.Fatalf("Expected to read 5 bytes. Read %d instead", n) - } - for i := 0; i < 3; i++ { - if err = tempArchive.Close(); err != nil { - t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go deleted file mode 100644 index 18f45c480..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build !windows - -package archive - -import ( - "os" - "testing" -) - -func TestCanonicalTarNameForPath(t *testing.T) { - cases := []struct{ in, expected string }{ - {"foo", "foo"}, - {"foo/bar", "foo/bar"}, - {"foo/dir/", "foo/dir/"}, - } - for _, v := range cases { - if out, err := CanonicalTarNameForPath(v.in); err != nil { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestCanonicalTarName(t *testing.T) { - cases := []struct { - in string - isDir bool - expected string - }{ - {"foo", false, "foo"}, - {"foo", true, "foo/"}, - {"foo/bar", false, "foo/bar"}, - {"foo/bar", true, "foo/bar/"}, - } - for _, v := range cases { - if out, err := canonicalTarName(v.in, v.isDir); err != nil { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestChmodTarEntry(t *testing.T) { - cases := []struct { - in, expected os.FileMode - }{ - {0000, 0000}, - {0777, 0777}, - {0644, 0644}, - {0755, 0755}, - {0444, 0444}, - } - for _, v := range cases { - if out := chmodTarEntry(v.in); out != v.expected { - t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go deleted file mode 100644 index b7abc4022..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// +build windows - -package archive - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" -) - -func TestCopyFileWithInvalidDest(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := "c:dest" - srcFolder := filepath.Join(folder, "src") - src := filepath.Join(folder, "src", "src") - err = os.MkdirAll(srcFolder, 0740) - if err != nil { - t.Fatal(err) - } - ioutil.WriteFile(src, []byte("content"), 0777) - err = CopyWithTar(src, dest) - if err == nil { - t.Fatalf("archiver.CopyWithTar should throw an error on invalid dest.") - } -} - -func TestCanonicalTarNameForPath(t *testing.T) { - cases := []struct { - in, expected string - shouldFail bool - }{ - {"foo", "foo", false}, - {"foo/bar", "___", true}, // unix-styled windows path must fail - {`foo\bar`, "foo/bar", false}, - } - for _, v := range cases { - if out, err := CanonicalTarNameForPath(v.in); err != nil && !v.shouldFail { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if v.shouldFail && err == nil { - t.Fatalf("canonical path call should have failed with error. in=%s out=%s", v.in, out) - } else if !v.shouldFail && out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestCanonicalTarName(t *testing.T) { - cases := []struct { - in string - isDir bool - expected string - }{ - {"foo", false, "foo"}, - {"foo", true, "foo/"}, - {`foo\bar`, false, "foo/bar"}, - {`foo\bar`, true, "foo/bar/"}, - } - for _, v := range cases { - if out, err := canonicalTarName(v.in, v.isDir); err != nil { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestChmodTarEntry(t *testing.T) { - cases := []struct { - in, expected os.FileMode - }{ - {0000, 0111}, - {0777, 0755}, - {0644, 0755}, - {0755, 0755}, - {0444, 0555}, - } - for _, v := range cases { - if out := chmodTarEntry(v.in); out != v.expected { - t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go deleted file mode 100644 index 5a3282b5a..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package archive - -import ( - "archive/tar" - "fmt" - "io" - "io/ioutil" - "os" - "path" - "sort" - "testing" -) - -func TestHardLinkOrder(t *testing.T) { - names := []string{"file1.txt", "file2.txt", "file3.txt"} - msg := []byte("Hey y'all") - - // Create dir - src, err := ioutil.TempDir("", "docker-hardlink-test-src-") - if err != nil { - t.Fatal(err) - } - //defer os.RemoveAll(src) - for _, name := range names { - func() { - fh, err := os.Create(path.Join(src, name)) - if err != nil { - t.Fatal(err) - } - defer fh.Close() - if _, err = fh.Write(msg); err != nil { - t.Fatal(err) - } - }() - } - // Create dest, with changes that includes hardlinks - dest, err := ioutil.TempDir("", "docker-hardlink-test-dest-") - if err != nil { - t.Fatal(err) - } - os.RemoveAll(dest) // we just want the name, at first - if err := copyDir(src, dest); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dest) - for _, name := range names { - for i := 0; i < 5; i++ { - if err := os.Link(path.Join(dest, name), path.Join(dest, fmt.Sprintf("%s.link%d", name, i))); err != nil { - t.Fatal(err) - } - } - } - - // get changes - changes, err := ChangesDirs(dest, src) - if err != nil { - t.Fatal(err) - } - - // sort - sort.Sort(changesByPath(changes)) - - // ExportChanges - ar, err := ExportChanges(dest, changes, nil, nil) - if err != nil { - t.Fatal(err) - } - hdrs, err := walkHeaders(ar) - if err != nil { - t.Fatal(err) - } - - // reverse sort - sort.Sort(sort.Reverse(changesByPath(changes))) - // ExportChanges - arRev, err := ExportChanges(dest, changes, nil, nil) - if err != nil { - t.Fatal(err) - } - hdrsRev, err := walkHeaders(arRev) - if err != nil { - t.Fatal(err) - } - - // line up the two sets - sort.Sort(tarHeaders(hdrs)) - sort.Sort(tarHeaders(hdrsRev)) - - // compare Size and LinkName - for i := range hdrs { - if hdrs[i].Name != hdrsRev[i].Name { - t.Errorf("headers - expected name %q; but got %q", hdrs[i].Name, hdrsRev[i].Name) - } - if hdrs[i].Size != hdrsRev[i].Size { - t.Errorf("headers - %q expected size %d; but got %d", hdrs[i].Name, hdrs[i].Size, hdrsRev[i].Size) - } - if hdrs[i].Typeflag != hdrsRev[i].Typeflag { - t.Errorf("headers - %q expected type %d; but got %d", hdrs[i].Name, hdrs[i].Typeflag, hdrsRev[i].Typeflag) - } - if hdrs[i].Linkname != hdrsRev[i].Linkname { - t.Errorf("headers - %q expected linkname %q; but got %q", hdrs[i].Name, hdrs[i].Linkname, hdrsRev[i].Linkname) - } - } - -} - -type tarHeaders []tar.Header - -func (th tarHeaders) Len() int { return len(th) } -func (th tarHeaders) Swap(i, j int) { th[j], th[i] = th[i], th[j] } -func (th tarHeaders) Less(i, j int) bool { return th[i].Name < th[j].Name } - -func walkHeaders(r io.Reader) ([]tar.Header, error) { - t := tar.NewReader(r) - headers := []tar.Header{} - for { - hdr, err := t.Next() - if err != nil { - if err == io.EOF { - break - } - return headers, err - } - headers = append(headers, *hdr) - } - return headers, nil -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go deleted file mode 100644 index f4316ce21..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go +++ /dev/null @@ -1,527 +0,0 @@ -package archive - -import ( - "io/ioutil" - "os" - "os/exec" - "path" - "sort" - "testing" - "time" -) - -func max(x, y int) int { - if x >= y { - return x - } - return y -} - -func copyDir(src, dst string) error { - cmd := exec.Command("cp", "-a", src, dst) - if err := cmd.Run(); err != nil { - return err - } - return nil -} - -type FileType uint32 - -const ( - Regular FileType = iota - Dir - Symlink -) - -type FileData struct { - filetype FileType - path string - contents string - permissions os.FileMode -} - -func createSampleDir(t *testing.T, root string) { - files := []FileData{ - {Regular, "file1", "file1\n", 0600}, - {Regular, "file2", "file2\n", 0666}, - {Regular, "file3", "file3\n", 0404}, - {Regular, "file4", "file4\n", 0600}, - {Regular, "file5", "file5\n", 0600}, - {Regular, "file6", "file6\n", 0600}, - {Regular, "file7", "file7\n", 0600}, - {Dir, "dir1", "", 0740}, - {Regular, "dir1/file1-1", "file1-1\n", 01444}, - {Regular, "dir1/file1-2", "file1-2\n", 0666}, - {Dir, "dir2", "", 0700}, - {Regular, "dir2/file2-1", "file2-1\n", 0666}, - {Regular, "dir2/file2-2", "file2-2\n", 0666}, - {Dir, "dir3", "", 0700}, - {Regular, "dir3/file3-1", "file3-1\n", 0666}, - {Regular, "dir3/file3-2", "file3-2\n", 0666}, - {Dir, "dir4", "", 0700}, - {Regular, "dir4/file3-1", "file4-1\n", 0666}, - {Regular, "dir4/file3-2", "file4-2\n", 0666}, - {Symlink, "symlink1", "target1", 0666}, - {Symlink, "symlink2", "target2", 0666}, - {Symlink, "symlink3", root + "/file1", 0666}, - {Symlink, "symlink4", root + "/symlink3", 0666}, - {Symlink, "dirSymlink", root + "/dir1", 0740}, - } - - now := time.Now() - for _, info := range files { - p := path.Join(root, info.path) - if info.filetype == Dir { - if err := os.MkdirAll(p, info.permissions); err != nil { - t.Fatal(err) - } - } else if info.filetype == Regular { - if err := ioutil.WriteFile(p, []byte(info.contents), info.permissions); err != nil { - t.Fatal(err) - } - } else if info.filetype == Symlink { - if err := os.Symlink(info.contents, p); err != nil { - t.Fatal(err) - } - } - - if info.filetype != Symlink { - // Set a consistent ctime, atime for all files and dirs - if err := os.Chtimes(p, now, now); err != nil { - t.Fatal(err) - } - } - } -} - -func TestChangeString(t *testing.T) { - modifiyChange := Change{"change", ChangeModify} - toString := modifiyChange.String() - if toString != "C change" { - t.Fatalf("String() of a change with ChangeModifiy Kind should have been %s but was %s", "C change", toString) - } - addChange := Change{"change", ChangeAdd} - toString = addChange.String() - if toString != "A change" { - t.Fatalf("String() of a change with ChangeAdd Kind should have been %s but was %s", "A change", toString) - } - deleteChange := Change{"change", ChangeDelete} - toString = deleteChange.String() - if toString != "D change" { - t.Fatalf("String() of a change with ChangeDelete Kind should have been %s but was %s", "D change", toString) - } -} - -func TestChangesWithNoChanges(t *testing.T) { - rwLayer, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(rwLayer) - layer, err := ioutil.TempDir("", "docker-changes-test-layer") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(layer) - createSampleDir(t, layer) - changes, err := Changes([]string{layer}, rwLayer) - if err != nil { - t.Fatal(err) - } - if len(changes) != 0 { - t.Fatalf("Changes with no difference should have detect no changes, but detected %d", len(changes)) - } -} - -func TestChangesWithChanges(t *testing.T) { - // Mock the readonly layer - layer, err := ioutil.TempDir("", "docker-changes-test-layer") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(layer) - createSampleDir(t, layer) - os.MkdirAll(path.Join(layer, "dir1/subfolder"), 0740) - - // Mock the RW layer - rwLayer, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(rwLayer) - - // Create a folder in RW layer - dir1 := path.Join(rwLayer, "dir1") - os.MkdirAll(dir1, 0740) - deletedFile := path.Join(dir1, ".wh.file1-2") - ioutil.WriteFile(deletedFile, []byte{}, 0600) - modifiedFile := path.Join(dir1, "file1-1") - ioutil.WriteFile(modifiedFile, []byte{0x00}, 01444) - // Let's add a subfolder for a newFile - subfolder := path.Join(dir1, "subfolder") - os.MkdirAll(subfolder, 0740) - newFile := path.Join(subfolder, "newFile") - ioutil.WriteFile(newFile, []byte{}, 0740) - - changes, err := Changes([]string{layer}, rwLayer) - if err != nil { - t.Fatal(err) - } - - expectedChanges := []Change{ - {"/dir1", ChangeModify}, - {"/dir1/file1-1", ChangeModify}, - {"/dir1/file1-2", ChangeDelete}, - {"/dir1/subfolder", ChangeModify}, - {"/dir1/subfolder/newFile", ChangeAdd}, - } - checkChanges(expectedChanges, changes, t) -} - -// See https://github.com/docker/docker/pull/13590 -func TestChangesWithChangesGH13590(t *testing.T) { - baseLayer, err := ioutil.TempDir("", "docker-changes-test.") - defer os.RemoveAll(baseLayer) - - dir3 := path.Join(baseLayer, "dir1/dir2/dir3") - os.MkdirAll(dir3, 07400) - - file := path.Join(dir3, "file.txt") - ioutil.WriteFile(file, []byte("hello"), 0666) - - layer, err := ioutil.TempDir("", "docker-changes-test2.") - defer os.RemoveAll(layer) - - // Test creating a new file - if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { - t.Fatalf("Cmd failed: %q", err) - } - - os.Remove(path.Join(layer, "dir1/dir2/dir3/file.txt")) - file = path.Join(layer, "dir1/dir2/dir3/file1.txt") - ioutil.WriteFile(file, []byte("bye"), 0666) - - changes, err := Changes([]string{baseLayer}, layer) - if err != nil { - t.Fatal(err) - } - - expectedChanges := []Change{ - {"/dir1/dir2/dir3", ChangeModify}, - {"/dir1/dir2/dir3/file1.txt", ChangeAdd}, - } - checkChanges(expectedChanges, changes, t) - - // Now test changing a file - layer, err = ioutil.TempDir("", "docker-changes-test3.") - defer os.RemoveAll(layer) - - if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { - t.Fatalf("Cmd failed: %q", err) - } - - file = path.Join(layer, "dir1/dir2/dir3/file.txt") - ioutil.WriteFile(file, []byte("bye"), 0666) - - changes, err = Changes([]string{baseLayer}, layer) - if err != nil { - t.Fatal(err) - } - - expectedChanges = []Change{ - {"/dir1/dir2/dir3/file.txt", ChangeModify}, - } - checkChanges(expectedChanges, changes, t) -} - -// Create an directory, copy it, make sure we report no changes between the two -func TestChangesDirsEmpty(t *testing.T) { - src, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(src) - createSampleDir(t, src) - dst := src + "-copy" - if err := copyDir(src, dst); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dst) - changes, err := ChangesDirs(dst, src) - if err != nil { - t.Fatal(err) - } - - if len(changes) != 0 { - t.Fatalf("Reported changes for identical dirs: %v", changes) - } - os.RemoveAll(src) - os.RemoveAll(dst) -} - -func mutateSampleDir(t *testing.T, root string) { - // Remove a regular file - if err := os.RemoveAll(path.Join(root, "file1")); err != nil { - t.Fatal(err) - } - - // Remove a directory - if err := os.RemoveAll(path.Join(root, "dir1")); err != nil { - t.Fatal(err) - } - - // Remove a symlink - if err := os.RemoveAll(path.Join(root, "symlink1")); err != nil { - t.Fatal(err) - } - - // Rewrite a file - if err := ioutil.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0777); err != nil { - t.Fatal(err) - } - - // Replace a file - if err := os.RemoveAll(path.Join(root, "file3")); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0404); err != nil { - t.Fatal(err) - } - - // Touch file - if err := os.Chtimes(path.Join(root, "file4"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { - t.Fatal(err) - } - - // Replace file with dir - if err := os.RemoveAll(path.Join(root, "file5")); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(path.Join(root, "file5"), 0666); err != nil { - t.Fatal(err) - } - - // Create new file - if err := ioutil.WriteFile(path.Join(root, "filenew"), []byte("filenew\n"), 0777); err != nil { - t.Fatal(err) - } - - // Create new dir - if err := os.MkdirAll(path.Join(root, "dirnew"), 0766); err != nil { - t.Fatal(err) - } - - // Create a new symlink - if err := os.Symlink("targetnew", path.Join(root, "symlinknew")); err != nil { - t.Fatal(err) - } - - // Change a symlink - if err := os.RemoveAll(path.Join(root, "symlink2")); err != nil { - t.Fatal(err) - } - if err := os.Symlink("target2change", path.Join(root, "symlink2")); err != nil { - t.Fatal(err) - } - - // Replace dir with file - if err := os.RemoveAll(path.Join(root, "dir2")); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(root, "dir2"), []byte("dir2\n"), 0777); err != nil { - t.Fatal(err) - } - - // Touch dir - if err := os.Chtimes(path.Join(root, "dir3"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { - t.Fatal(err) - } -} - -func TestChangesDirsMutated(t *testing.T) { - src, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - createSampleDir(t, src) - dst := src + "-copy" - if err := copyDir(src, dst); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(src) - defer os.RemoveAll(dst) - - mutateSampleDir(t, dst) - - changes, err := ChangesDirs(dst, src) - if err != nil { - t.Fatal(err) - } - - sort.Sort(changesByPath(changes)) - - expectedChanges := []Change{ - {"/dir1", ChangeDelete}, - {"/dir2", ChangeModify}, - {"/dirnew", ChangeAdd}, - {"/file1", ChangeDelete}, - {"/file2", ChangeModify}, - {"/file3", ChangeModify}, - {"/file4", ChangeModify}, - {"/file5", ChangeModify}, - {"/filenew", ChangeAdd}, - {"/symlink1", ChangeDelete}, - {"/symlink2", ChangeModify}, - {"/symlinknew", ChangeAdd}, - } - - for i := 0; i < max(len(changes), len(expectedChanges)); i++ { - if i >= len(expectedChanges) { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } - if i >= len(changes) { - t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) - } - if changes[i].Path == expectedChanges[i].Path { - if changes[i] != expectedChanges[i] { - t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) - } - } else if changes[i].Path < expectedChanges[i].Path { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } else { - t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) - } - } -} - -func TestApplyLayer(t *testing.T) { - src, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - createSampleDir(t, src) - defer os.RemoveAll(src) - dst := src + "-copy" - if err := copyDir(src, dst); err != nil { - t.Fatal(err) - } - mutateSampleDir(t, dst) - defer os.RemoveAll(dst) - - changes, err := ChangesDirs(dst, src) - if err != nil { - t.Fatal(err) - } - - layer, err := ExportChanges(dst, changes, nil, nil) - if err != nil { - t.Fatal(err) - } - - layerCopy, err := NewTempArchive(layer, "") - if err != nil { - t.Fatal(err) - } - - if _, err := ApplyLayer(src, layerCopy); err != nil { - t.Fatal(err) - } - - changes2, err := ChangesDirs(src, dst) - if err != nil { - t.Fatal(err) - } - - if len(changes2) != 0 { - t.Fatalf("Unexpected differences after reapplying mutation: %v", changes2) - } -} - -func TestChangesSizeWithHardlinks(t *testing.T) { - srcDir, err := ioutil.TempDir("", "docker-test-srcDir") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(srcDir) - - destDir, err := ioutil.TempDir("", "docker-test-destDir") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(destDir) - - creationSize, err := prepareUntarSourceDirectory(100, destDir, true) - if err != nil { - t.Fatal(err) - } - - changes, err := ChangesDirs(destDir, srcDir) - if err != nil { - t.Fatal(err) - } - - got := ChangesSize(destDir, changes) - if got != int64(creationSize) { - t.Errorf("Expected %d bytes of changes, got %d", creationSize, got) - } -} - -func TestChangesSizeWithNoChanges(t *testing.T) { - size := ChangesSize("/tmp", nil) - if size != 0 { - t.Fatalf("ChangesSizes with no changes should be 0, was %d", size) - } -} - -func TestChangesSizeWithOnlyDeleteChanges(t *testing.T) { - changes := []Change{ - {Path: "deletedPath", Kind: ChangeDelete}, - } - size := ChangesSize("/tmp", changes) - if size != 0 { - t.Fatalf("ChangesSizes with only delete changes should be 0, was %d", size) - } -} - -func TestChangesSize(t *testing.T) { - parentPath, err := ioutil.TempDir("", "docker-changes-test") - defer os.RemoveAll(parentPath) - addition := path.Join(parentPath, "addition") - if err := ioutil.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0744); err != nil { - t.Fatal(err) - } - modification := path.Join(parentPath, "modification") - if err = ioutil.WriteFile(modification, []byte{0x01, 0x01, 0x01}, 0744); err != nil { - t.Fatal(err) - } - changes := []Change{ - {Path: "addition", Kind: ChangeAdd}, - {Path: "modification", Kind: ChangeModify}, - } - size := ChangesSize(parentPath, changes) - if size != 6 { - t.Fatalf("Expected 6 bytes of changes, got %d", size) - } -} - -func checkChanges(expectedChanges, changes []Change, t *testing.T) { - sort.Sort(changesByPath(expectedChanges)) - sort.Sort(changesByPath(changes)) - for i := 0; i < max(len(changes), len(expectedChanges)); i++ { - if i >= len(expectedChanges) { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } - if i >= len(changes) { - t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) - } - if changes[i].Path == expectedChanges[i].Path { - if changes[i] != expectedChanges[i] { - t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) - } - } else if changes[i].Path < expectedChanges[i].Path { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } else { - t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go deleted file mode 100644 index f1dc23824..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go +++ /dev/null @@ -1,974 +0,0 @@ -package archive - -import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" -) - -func removeAllPaths(paths ...string) { - for _, path := range paths { - os.RemoveAll(path) - } -} - -func getTestTempDirs(t *testing.T) (tmpDirA, tmpDirB string) { - var err error - - if tmpDirA, err = ioutil.TempDir("", "archive-copy-test"); err != nil { - t.Fatal(err) - } - - if tmpDirB, err = ioutil.TempDir("", "archive-copy-test"); err != nil { - t.Fatal(err) - } - - return -} - -func isNotDir(err error) bool { - return strings.Contains(err.Error(), "not a directory") -} - -func joinTrailingSep(pathElements ...string) string { - joined := filepath.Join(pathElements...) - - return fmt.Sprintf("%s%c", joined, filepath.Separator) -} - -func fileContentsEqual(t *testing.T, filenameA, filenameB string) (err error) { - t.Logf("checking for equal file contents: %q and %q\n", filenameA, filenameB) - - fileA, err := os.Open(filenameA) - if err != nil { - return - } - defer fileA.Close() - - fileB, err := os.Open(filenameB) - if err != nil { - return - } - defer fileB.Close() - - hasher := sha256.New() - - if _, err = io.Copy(hasher, fileA); err != nil { - return - } - - hashA := hasher.Sum(nil) - hasher.Reset() - - if _, err = io.Copy(hasher, fileB); err != nil { - return - } - - hashB := hasher.Sum(nil) - - if !bytes.Equal(hashA, hashB) { - err = fmt.Errorf("file content hashes not equal - expected %s, got %s", hex.EncodeToString(hashA), hex.EncodeToString(hashB)) - } - - return -} - -func dirContentsEqual(t *testing.T, newDir, oldDir string) (err error) { - t.Logf("checking for equal directory contents: %q and %q\n", newDir, oldDir) - - var changes []Change - - if changes, err = ChangesDirs(newDir, oldDir); err != nil { - return - } - - if len(changes) != 0 { - err = fmt.Errorf("expected no changes between directories, but got: %v", changes) - } - - return -} - -func logDirContents(t *testing.T, dirPath string) { - logWalkedPaths := filepath.WalkFunc(func(path string, info os.FileInfo, err error) error { - if err != nil { - t.Errorf("stat error for path %q: %s", path, err) - return nil - } - - if info.IsDir() { - path = joinTrailingSep(path) - } - - t.Logf("\t%s", path) - - return nil - }) - - t.Logf("logging directory contents: %q", dirPath) - - if err := filepath.Walk(dirPath, logWalkedPaths); err != nil { - t.Fatal(err) - } -} - -func testCopyHelper(t *testing.T, srcPath, dstPath string) (err error) { - t.Logf("copying from %q to %q (not follow symbol link)", srcPath, dstPath) - - return CopyResource(srcPath, dstPath, false) -} - -func testCopyHelperFSym(t *testing.T, srcPath, dstPath string) (err error) { - t.Logf("copying from %q to %q (follow symbol link)", srcPath, dstPath) - - return CopyResource(srcPath, dstPath, true) -} - -// Basic assumptions about SRC and DST: -// 1. SRC must exist. -// 2. If SRC ends with a trailing separator, it must be a directory. -// 3. DST parent directory must exist. -// 4. If DST exists as a file, it must not end with a trailing separator. - -// First get these easy error cases out of the way. - -// Test for error when SRC does not exist. -func TestCopyErrSrcNotExists(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - if _, err := CopyInfoSourcePath(filepath.Join(tmpDirA, "file1"), false); !os.IsNotExist(err) { - t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) - } -} - -// Test for error when SRC ends in a trailing -// path separator but it exists as a file. -func TestCopyErrSrcNotDir(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - if _, err := CopyInfoSourcePath(joinTrailingSep(tmpDirA, "file1"), false); !isNotDir(err) { - t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) - } -} - -// Test for error when SRC is a valid file or directory, -// but the DST parent directory does not exist. -func TestCopyErrDstParentNotExists(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} - - // Try with a file source. - content, err := TarResource(srcInfo) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - // Copy to a file whose parent does not exist. - if err = CopyTo(content, srcInfo, filepath.Join(tmpDirB, "fakeParentDir", "file1")); err == nil { - t.Fatal("expected IsNotExist error, but got nil instead") - } - - if !os.IsNotExist(err) { - t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) - } - - // Try with a directory source. - srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} - - content, err = TarResource(srcInfo) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - // Copy to a directory whose parent does not exist. - if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "fakeParentDir", "fakeDstDir")); err == nil { - t.Fatal("expected IsNotExist error, but got nil instead") - } - - if !os.IsNotExist(err) { - t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) - } -} - -// Test for error when DST ends in a trailing -// path separator but exists as a file. -func TestCopyErrDstNotDir(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - // Try with a file source. - srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} - - content, err := TarResource(srcInfo) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { - t.Fatal("expected IsNotDir error, but got nil instead") - } - - if !isNotDir(err) { - t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) - } - - // Try with a directory source. - srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} - - content, err = TarResource(srcInfo) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { - t.Fatal("expected IsNotDir error, but got nil instead") - } - - if !isNotDir(err) { - t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) - } -} - -// Possibilities are reduced to the remaining 10 cases: -// -// case | srcIsDir | onlyDirContents | dstExists | dstIsDir | dstTrSep | action -// =================================================================================================== -// A | no | - | no | - | no | create file -// B | no | - | no | - | yes | error -// C | no | - | yes | no | - | overwrite file -// D | no | - | yes | yes | - | create file in dst dir -// E | yes | no | no | - | - | create dir, copy contents -// F | yes | no | yes | no | - | error -// G | yes | no | yes | yes | - | copy dir and contents -// H | yes | yes | no | - | - | create dir, copy contents -// I | yes | yes | yes | no | - | error -// J | yes | yes | yes | yes | - | copy dir contents -// - -// A. SRC specifies a file and DST (no trailing path separator) doesn't -// exist. This should create a file with the name DST and copy the -// contents of the source file into it. -func TestCopyCaseA(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcPath := filepath.Join(tmpDirA, "file1") - dstPath := filepath.Join(tmpDirB, "itWorks.txt") - - var err error - - if err = testCopyHelper(t, srcPath, dstPath); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } - os.Remove(dstPath) - - symlinkPath := filepath.Join(tmpDirA, "symlink3") - symlinkPath1 := filepath.Join(tmpDirA, "symlink4") - linkTarget := filepath.Join(tmpDirA, "file1") - - if err = testCopyHelperFSym(t, symlinkPath, dstPath); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { - t.Fatal(err) - } - os.Remove(dstPath) - if err = testCopyHelperFSym(t, symlinkPath1, dstPath); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { - t.Fatal(err) - } -} - -// B. SRC specifies a file and DST (with trailing path separator) doesn't -// exist. This should cause an error because the copy operation cannot -// create a directory when copying a single file. -func TestCopyCaseB(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcPath := filepath.Join(tmpDirA, "file1") - dstDir := joinTrailingSep(tmpDirB, "testDir") - - var err error - - if err = testCopyHelper(t, srcPath, dstDir); err == nil { - t.Fatal("expected ErrDirNotExists error, but got nil instead") - } - - if err != ErrDirNotExists { - t.Fatalf("expected ErrDirNotExists error, but got %T: %s", err, err) - } - - symlinkPath := filepath.Join(tmpDirA, "symlink3") - - if err = testCopyHelperFSym(t, symlinkPath, dstDir); err == nil { - t.Fatal("expected ErrDirNotExists error, but got nil instead") - } - if err != ErrDirNotExists { - t.Fatalf("expected ErrDirNotExists error, but got %T: %s", err, err) - } - -} - -// C. SRC specifies a file and DST exists as a file. This should overwrite -// the file at DST with the contents of the source file. -func TestCopyCaseC(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcPath := filepath.Join(tmpDirA, "file1") - dstPath := filepath.Join(tmpDirB, "file2") - - var err error - - // Ensure they start out different. - if err = fileContentsEqual(t, srcPath, dstPath); err == nil { - t.Fatal("expected different file contents") - } - - if err = testCopyHelper(t, srcPath, dstPath); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } -} - -// C. Symbol link following version: -// SRC specifies a file and DST exists as a file. This should overwrite -// the file at DST with the contents of the source file. -func TestCopyCaseCFSym(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - symlinkPathBad := filepath.Join(tmpDirA, "symlink1") - symlinkPath := filepath.Join(tmpDirA, "symlink3") - linkTarget := filepath.Join(tmpDirA, "file1") - dstPath := filepath.Join(tmpDirB, "file2") - - var err error - - // first to test broken link - if err = testCopyHelperFSym(t, symlinkPathBad, dstPath); err == nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - // test symbol link -> symbol link -> target - // Ensure they start out different. - if err = fileContentsEqual(t, linkTarget, dstPath); err == nil { - t.Fatal("expected different file contents") - } - - if err = testCopyHelperFSym(t, symlinkPath, dstPath); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { - t.Fatal(err) - } -} - -// D. SRC specifies a file and DST exists as a directory. This should place -// a copy of the source file inside it using the basename from SRC. Ensure -// this works whether DST has a trailing path separator or not. -func TestCopyCaseD(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcPath := filepath.Join(tmpDirA, "file1") - dstDir := filepath.Join(tmpDirB, "dir1") - dstPath := filepath.Join(dstDir, "file1") - - var err error - - // Ensure that dstPath doesn't exist. - if _, err = os.Stat(dstPath); !os.IsNotExist(err) { - t.Fatalf("did not expect dstPath %q to exist", dstPath) - } - - if err = testCopyHelper(t, srcPath, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir1") - - if err = testCopyHelper(t, srcPath, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } -} - -// D. Symbol link following version: -// SRC specifies a file and DST exists as a directory. This should place -// a copy of the source file inside it using the basename from SRC. Ensure -// this works whether DST has a trailing path separator or not. -func TestCopyCaseDFSym(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcPath := filepath.Join(tmpDirA, "symlink4") - linkTarget := filepath.Join(tmpDirA, "file1") - dstDir := filepath.Join(tmpDirB, "dir1") - dstPath := filepath.Join(dstDir, "symlink4") - - var err error - - // Ensure that dstPath doesn't exist. - if _, err = os.Stat(dstPath); !os.IsNotExist(err) { - t.Fatalf("did not expect dstPath %q to exist", dstPath) - } - - if err = testCopyHelperFSym(t, srcPath, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir1") - - if err = testCopyHelperFSym(t, srcPath, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { - t.Fatal(err) - } -} - -// E. SRC specifies a directory and DST does not exist. This should create a -// directory at DST and copy the contents of the SRC directory into the DST -// directory. Ensure this works whether DST has a trailing path separator or -// not. -func TestCopyCaseE(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcDir := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "testDir") - - var err error - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "testDir") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Fatal(err) - } -} - -// E. Symbol link following version: -// SRC specifies a directory and DST does not exist. This should create a -// directory at DST and copy the contents of the SRC directory into the DST -// directory. Ensure this works whether DST has a trailing path separator or -// not. -func TestCopyCaseEFSym(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcDir := filepath.Join(tmpDirA, "dirSymlink") - linkTarget := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "testDir") - - var err error - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "testDir") - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { - t.Fatal(err) - } -} - -// F. SRC specifies a directory and DST exists as a file. This should cause an -// error as it is not possible to overwrite a file with a directory. -func TestCopyCaseF(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := filepath.Join(tmpDirA, "dir1") - symSrcDir := filepath.Join(tmpDirA, "dirSymlink") - dstFile := filepath.Join(tmpDirB, "file1") - - var err error - - if err = testCopyHelper(t, srcDir, dstFile); err == nil { - t.Fatal("expected ErrCannotCopyDir error, but got nil instead") - } - - if err != ErrCannotCopyDir { - t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) - } - - // now test with symbol link - if err = testCopyHelperFSym(t, symSrcDir, dstFile); err == nil { - t.Fatal("expected ErrCannotCopyDir error, but got nil instead") - } - - if err != ErrCannotCopyDir { - t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) - } -} - -// G. SRC specifies a directory and DST exists as a directory. This should copy -// the SRC directory and all its contents to the DST directory. Ensure this -// works whether DST has a trailing path separator or not. -func TestCopyCaseG(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "dir2") - resultDir := filepath.Join(dstDir, "dir1") - - var err error - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, resultDir, srcDir); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir2") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, resultDir, srcDir); err != nil { - t.Fatal(err) - } -} - -// G. Symbol link version: -// SRC specifies a directory and DST exists as a directory. This should copy -// the SRC directory and all its contents to the DST directory. Ensure this -// works whether DST has a trailing path separator or not. -func TestCopyCaseGFSym(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := filepath.Join(tmpDirA, "dirSymlink") - linkTarget := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "dir2") - resultDir := filepath.Join(dstDir, "dirSymlink") - - var err error - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, resultDir, linkTarget); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir2") - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, resultDir, linkTarget); err != nil { - t.Fatal(err) - } -} - -// H. SRC specifies a directory's contents only and DST does not exist. This -// should create a directory at DST and copy the contents of the SRC -// directory (but not the directory itself) into the DST directory. Ensure -// this works whether DST has a trailing path separator or not. -func TestCopyCaseH(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcDir := joinTrailingSep(tmpDirA, "dir1") + "." - dstDir := filepath.Join(tmpDirB, "testDir") - - var err error - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "testDir") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } -} - -// H. Symbol link following version: -// SRC specifies a directory's contents only and DST does not exist. This -// should create a directory at DST and copy the contents of the SRC -// directory (but not the directory itself) into the DST directory. Ensure -// this works whether DST has a trailing path separator or not. -func TestCopyCaseHFSym(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcDir := joinTrailingSep(tmpDirA, "dirSymlink") + "." - linkTarget := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "testDir") - - var err error - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "testDir") - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } -} - -// I. SRC specifies a directory's contents only and DST exists as a file. This -// should cause an error as it is not possible to overwrite a file with a -// directory. -func TestCopyCaseI(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := joinTrailingSep(tmpDirA, "dir1") + "." - symSrcDir := filepath.Join(tmpDirB, "dirSymlink") - dstFile := filepath.Join(tmpDirB, "file1") - - var err error - - if err = testCopyHelper(t, srcDir, dstFile); err == nil { - t.Fatal("expected ErrCannotCopyDir error, but got nil instead") - } - - if err != ErrCannotCopyDir { - t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) - } - - // now try with symbol link of dir - if err = testCopyHelperFSym(t, symSrcDir, dstFile); err == nil { - t.Fatal("expected ErrCannotCopyDir error, but got nil instead") - } - - if err != ErrCannotCopyDir { - t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) - } -} - -// J. SRC specifies a directory's contents only and DST exists as a directory. -// This should copy the contents of the SRC directory (but not the directory -// itself) into the DST directory. Ensure this works whether DST has a -// trailing path separator or not. -func TestCopyCaseJ(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := joinTrailingSep(tmpDirA, "dir1") + "." - dstDir := filepath.Join(tmpDirB, "dir5") - - var err error - - // first to create an empty dir - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir5") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Fatal(err) - } -} - -// J. Symbol link following version: -// SRC specifies a directory's contents only and DST exists as a directory. -// This should copy the contents of the SRC directory (but not the directory -// itself) into the DST directory. Ensure this works whether DST has a -// trailing path separator or not. -func TestCopyCaseJFSym(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := joinTrailingSep(tmpDirA, "dirSymlink") + "." - linkTarget := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "dir5") - - var err error - - // first to create an empty dir - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir5") - - if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go deleted file mode 100644 index 4388d69c7..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go +++ /dev/null @@ -1,370 +0,0 @@ -package archive - -import ( - "archive/tar" - "io" - "io/ioutil" - "os" - "path/filepath" - "reflect" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils" -) - -func TestApplyLayerInvalidFilenames(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { - { - Name: "../victim/dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { - { - // Note the leading slash - Name: "/../victim/slash-dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidFilenames", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestApplyLayerInvalidHardlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeLink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeLink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (hardlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try reading victim/hello (hardlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try removing victim directory (hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidHardlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestApplyLayerInvalidSymlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeSymlink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeSymlink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try removing victim directory (symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidSymlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestApplyLayerWhiteouts(t *testing.T) { - wd, err := ioutil.TempDir("", "graphdriver-test-whiteouts") - if err != nil { - return - } - defer os.RemoveAll(wd) - - base := []string{ - ".baz", - "bar/", - "bar/bax", - "bar/bay/", - "baz", - "foo/", - "foo/.abc", - "foo/.bcd/", - "foo/.bcd/a", - "foo/cde/", - "foo/cde/def", - "foo/cde/efg", - "foo/fgh", - "foobar", - } - - type tcase struct { - change, expected []string - } - - tcases := []tcase{ - { - base, - base, - }, - { - []string{ - ".bay", - ".wh.baz", - "foo/", - "foo/.bce", - "foo/.wh..wh..opq", - "foo/cde/", - "foo/cde/efg", - }, - []string{ - ".bay", - ".baz", - "bar/", - "bar/bax", - "bar/bay/", - "foo/", - "foo/.bce", - "foo/cde/", - "foo/cde/efg", - "foobar", - }, - }, - { - []string{ - ".bay", - ".wh..baz", - ".wh.foobar", - "foo/", - "foo/.abc", - "foo/.wh.cde", - "bar/", - }, - []string{ - ".bay", - "bar/", - "bar/bax", - "bar/bay/", - "foo/", - "foo/.abc", - "foo/.bce", - }, - }, - { - []string{ - ".abc", - ".wh..wh..opq", - "foobar", - }, - []string{ - ".abc", - "foobar", - }, - }, - } - - for i, tc := range tcases { - l, err := makeTestLayer(tc.change) - if err != nil { - t.Fatal(err) - } - - _, err = UnpackLayer(wd, l, nil) - if err != nil { - t.Fatal(err) - } - err = l.Close() - if err != nil { - t.Fatal(err) - } - - paths, err := readDirContents(wd) - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(tc.expected, paths) { - t.Fatalf("invalid files for layer %d: expected %q, got %q", i, tc.expected, paths) - } - } - -} - -func makeTestLayer(paths []string) (rc io.ReadCloser, err error) { - tmpDir, err := ioutil.TempDir("", "graphdriver-test-mklayer") - if err != nil { - return - } - defer func() { - if err != nil { - os.RemoveAll(tmpDir) - } - }() - for _, p := range paths { - if p[len(p)-1] == filepath.Separator { - if err = os.MkdirAll(filepath.Join(tmpDir, p), 0700); err != nil { - return - } - } else { - if err = ioutil.WriteFile(filepath.Join(tmpDir, p), nil, 0600); err != nil { - return - } - } - } - archive, err := Tar(tmpDir, Uncompressed) - if err != nil { - return - } - return ioutils.NewReadCloserWrapper(archive, func() error { - err := archive.Close() - os.RemoveAll(tmpDir) - return err - }), nil -} - -func readDirContents(root string) ([]string, error) { - var files []string - err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if path == root { - return nil - } - rel, err := filepath.Rel(root, path) - if err != nil { - return err - } - if info.IsDir() { - rel = rel + "/" - } - files = append(files, rel) - return nil - }) - if err != nil { - return nil, err - } - return files, nil -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go deleted file mode 100644 index 98719032f..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "time" -) - -var testUntarFns = map[string]func(string, io.Reader) error{ - "untar": func(dest string, r io.Reader) error { - return Untar(r, dest, nil) - }, - "applylayer": func(dest string, r io.Reader) error { - _, err := ApplyLayer(dest, Reader(r)) - return err - }, -} - -// testBreakout is a helper function that, within the provided `tmpdir` directory, -// creates a `victim` folder with a generated `hello` file in it. -// `untar` extracts to a directory named `dest`, the tar file created from `headers`. -// -// Here are the tested scenarios: -// - removed `victim` folder (write) -// - removed files from `victim` folder (write) -// - new files in `victim` folder (write) -// - modified files in `victim` folder (write) -// - file in `dest` with same content as `victim/hello` (read) -// -// When using testBreakout make sure you cover one of the scenarios listed above. -func testBreakout(untarFn string, tmpdir string, headers []*tar.Header) error { - tmpdir, err := ioutil.TempDir("", tmpdir) - if err != nil { - return err - } - defer os.RemoveAll(tmpdir) - - dest := filepath.Join(tmpdir, "dest") - if err := os.Mkdir(dest, 0755); err != nil { - return err - } - - victim := filepath.Join(tmpdir, "victim") - if err := os.Mkdir(victim, 0755); err != nil { - return err - } - hello := filepath.Join(victim, "hello") - helloData, err := time.Now().MarshalText() - if err != nil { - return err - } - if err := ioutil.WriteFile(hello, helloData, 0644); err != nil { - return err - } - helloStat, err := os.Stat(hello) - if err != nil { - return err - } - - reader, writer := io.Pipe() - go func() { - t := tar.NewWriter(writer) - for _, hdr := range headers { - t.WriteHeader(hdr) - } - t.Close() - }() - - untar := testUntarFns[untarFn] - if untar == nil { - return fmt.Errorf("could not find untar function %q in testUntarFns", untarFn) - } - if err := untar(dest, reader); err != nil { - if _, ok := err.(breakoutError); !ok { - // If untar returns an error unrelated to an archive breakout, - // then consider this an unexpected error and abort. - return err - } - // Here, untar detected the breakout. - // Let's move on verifying that indeed there was no breakout. - fmt.Printf("breakoutError: %v\n", err) - } - - // Check victim folder - f, err := os.Open(victim) - if err != nil { - // codepath taken if victim folder was removed - return fmt.Errorf("archive breakout: error reading %q: %v", victim, err) - } - defer f.Close() - - // Check contents of victim folder - // - // We are only interested in getting 2 files from the victim folder, because if all is well - // we expect only one result, the `hello` file. If there is a second result, it cannot - // hold the same name `hello` and we assume that a new file got created in the victim folder. - // That is enough to detect an archive breakout. - names, err := f.Readdirnames(2) - if err != nil { - // codepath taken if victim is not a folder - return fmt.Errorf("archive breakout: error reading directory content of %q: %v", victim, err) - } - for _, name := range names { - if name != "hello" { - // codepath taken if new file was created in victim folder - return fmt.Errorf("archive breakout: new file %q", name) - } - } - - // Check victim/hello - f, err = os.Open(hello) - if err != nil { - // codepath taken if read permissions were removed - return fmt.Errorf("archive breakout: could not lstat %q: %v", hello, err) - } - defer f.Close() - b, err := ioutil.ReadAll(f) - if err != nil { - return err - } - fi, err := f.Stat() - if err != nil { - return err - } - if helloStat.IsDir() != fi.IsDir() || - // TODO: cannot check for fi.ModTime() change - helloStat.Mode() != fi.Mode() || - helloStat.Size() != fi.Size() || - !bytes.Equal(helloData, b) { - // codepath taken if hello has been modified - return fmt.Errorf("archive breakout: file %q has been modified. Contents: expected=%q, got=%q. FileInfo: expected=%#v, got=%#v", hello, helloData, b, helloStat, fi) - } - - // Check that nothing in dest/ has the same content as victim/hello. - // Since victim/hello was generated with time.Now(), it is safe to assume - // that any file whose content matches exactly victim/hello, managed somehow - // to access victim/hello. - return filepath.Walk(dest, func(path string, info os.FileInfo, err error) error { - if info.IsDir() { - if err != nil { - // skip directory if error - return filepath.SkipDir - } - // enter directory - return nil - } - if err != nil { - // skip file if error - return nil - } - b, err := ioutil.ReadFile(path) - if err != nil { - // Houston, we have a problem. Aborting (space)walk. - return err - } - if bytes.Equal(helloData, b) { - return fmt.Errorf("archive breakout: file %q has been accessed via %q", hello, path) - } - return nil - }) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go deleted file mode 100644 index 46ab36697..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "io" - "testing" -) - -func TestGenerateEmptyFile(t *testing.T) { - archive, err := Generate("emptyFile") - if err != nil { - t.Fatal(err) - } - if archive == nil { - t.Fatal("The generated archive should not be nil.") - } - - expectedFiles := [][]string{ - {"emptyFile", ""}, - } - - tr := tar.NewReader(archive) - actualFiles := make([][]string, 0, 10) - i := 0 - for { - hdr, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - buf := new(bytes.Buffer) - buf.ReadFrom(tr) - content := buf.String() - actualFiles = append(actualFiles, []string{hdr.Name, content}) - i++ - } - if len(actualFiles) != len(expectedFiles) { - t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) - } - for i := 0; i < len(expectedFiles); i++ { - actual := actualFiles[i] - expected := expectedFiles[i] - if actual[0] != expected[0] { - t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) - } - if actual[1] != expected[1] { - t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) - } - } -} - -func TestGenerateWithContent(t *testing.T) { - archive, err := Generate("file", "content") - if err != nil { - t.Fatal(err) - } - if archive == nil { - t.Fatal("The generated archive should not be nil.") - } - - expectedFiles := [][]string{ - {"file", "content"}, - } - - tr := tar.NewReader(archive) - actualFiles := make([][]string, 0, 10) - i := 0 - for { - hdr, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - buf := new(bytes.Buffer) - buf.ReadFrom(tr) - content := buf.String() - actualFiles = append(actualFiles, []string{hdr.Name, content}) - i++ - } - if len(actualFiles) != len(expectedFiles) { - t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) - } - for i := 0; i < len(expectedFiles); i++ { - actual := actualFiles[i] - expected := expectedFiles[i] - if actual[0] != expected[0] { - t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) - } - if actual[1] != expected[1] { - t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go deleted file mode 100644 index 2d584c667..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go +++ /dev/null @@ -1,573 +0,0 @@ -package fileutils - -import ( - "io/ioutil" - "os" - "path" - "path/filepath" - "runtime" - "strings" - "testing" -) - -// CopyFile with invalid src -func TestCopyFileWithInvalidSrc(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest")) - if err == nil { - t.Fatal("Should have fail to copy an invalid src file") - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes") - } - -} - -// CopyFile with invalid dest -func TestCopyFileWithInvalidDest(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - src := path.Join(tempFolder, "file") - err = ioutil.WriteFile(src, []byte("content"), 0740) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path")) - if err == nil { - t.Fatal("Should have fail to copy an invalid src file") - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes") - } - -} - -// CopyFile with same src and dest -func TestCopyFileWithSameSrcAndDest(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - file := path.Join(tempFolder, "file") - err = ioutil.WriteFile(file, []byte("content"), 0740) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile(file, file) - if err != nil { - t.Fatal(err) - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes as it is the same file.") - } -} - -// CopyFile with same src and dest but path is different and not clean -func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - testFolder := path.Join(tempFolder, "test") - err = os.MkdirAll(testFolder, 0740) - if err != nil { - t.Fatal(err) - } - file := path.Join(testFolder, "file") - sameFile := testFolder + "/../test/file" - err = ioutil.WriteFile(file, []byte("content"), 0740) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile(file, sameFile) - if err != nil { - t.Fatal(err) - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes as it is the same file.") - } -} - -func TestCopyFile(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - src := path.Join(tempFolder, "src") - dest := path.Join(tempFolder, "dest") - ioutil.WriteFile(src, []byte("content"), 0777) - ioutil.WriteFile(dest, []byte("destContent"), 0777) - bytes, err := CopyFile(src, dest) - if err != nil { - t.Fatal(err) - } - if bytes != 7 { - t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes) - } - actual, err := ioutil.ReadFile(dest) - if err != nil { - t.Fatal(err) - } - if string(actual) != "content" { - t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content") - } -} - -// Reading a symlink to a directory must return the directory -func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) { - var err error - if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil { - t.Errorf("failed to create directory: %s", err) - } - - if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil { - t.Errorf("failed to create symlink: %s", err) - } - - var path string - if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil { - t.Fatalf("failed to read symlink to directory: %s", err) - } - - if path != "/tmp/testReadSymlinkToExistingDirectory" { - t.Fatalf("symlink returned unexpected directory: %s", path) - } - - if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil { - t.Errorf("failed to remove temporary directory: %s", err) - } - - if err = os.Remove("/tmp/dirLinkTest"); err != nil { - t.Errorf("failed to remove symlink: %s", err) - } -} - -// Reading a non-existing symlink must fail -func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) { - var path string - var err error - if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil { - t.Fatalf("error expected for non-existing symlink") - } - - if path != "" { - t.Fatalf("expected empty path, but '%s' was returned", path) - } -} - -// Reading a symlink to a file must fail -func TestReadSymlinkedDirectoryToFile(t *testing.T) { - var err error - var file *os.File - - if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil { - t.Fatalf("failed to create file: %s", err) - } - - file.Close() - - if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil { - t.Errorf("failed to create symlink: %s", err) - } - - var path string - if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil { - t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed") - } - - if path != "" { - t.Fatalf("path should've been empty: %s", path) - } - - if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil { - t.Errorf("failed to remove file: %s", err) - } - - if err = os.Remove("/tmp/fileLinkTest"); err != nil { - t.Errorf("failed to remove symlink: %s", err) - } -} - -func TestWildcardMatches(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"*"}) - if match != true { - t.Errorf("failed to get a wildcard match, got %v", match) - } -} - -// A simple pattern match should return true. -func TestPatternMatches(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"*.go"}) - if match != true { - t.Errorf("failed to get a match, got %v", match) - } -} - -// An exclusion followed by an inclusion should return true. -func TestExclusionPatternMatchesPatternBefore(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"}) - if match != true { - t.Errorf("failed to get true match on exclusion pattern, got %v", match) - } -} - -// A folder pattern followed by an exception should return false. -func TestPatternMatchesFolderExclusions(t *testing.T) { - match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"}) - if match != false { - t.Errorf("failed to get a false match on exclusion pattern, got %v", match) - } -} - -// A folder pattern followed by an exception should return false. -func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) { - match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"}) - if match != false { - t.Errorf("failed to get a false match on exclusion pattern, got %v", match) - } -} - -// A folder pattern followed by an exception should return false. -func TestPatternMatchesFolderWildcardExclusions(t *testing.T) { - match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"}) - if match != false { - t.Errorf("failed to get a false match on exclusion pattern, got %v", match) - } -} - -// A pattern followed by an exclusion should return false. -func TestExclusionPatternMatchesPatternAfter(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"}) - if match != false { - t.Errorf("failed to get false match on exclusion pattern, got %v", match) - } -} - -// A filename evaluating to . should return false. -func TestExclusionPatternMatchesWholeDirectory(t *testing.T) { - match, _ := Matches(".", []string{"*.go"}) - if match != false { - t.Errorf("failed to get false match on ., got %v", match) - } -} - -// A single ! pattern should return an error. -func TestSingleExclamationError(t *testing.T) { - _, err := Matches("fileutils.go", []string{"!"}) - if err == nil { - t.Errorf("failed to get an error for a single exclamation point, got %v", err) - } -} - -// A string preceded with a ! should return true from Exclusion. -func TestExclusion(t *testing.T) { - exclusion := exclusion("!") - if !exclusion { - t.Errorf("failed to get true for a single !, got %v", exclusion) - } -} - -// Matches with no patterns -func TestMatchesWithNoPatterns(t *testing.T) { - matches, err := Matches("/any/path/there", []string{}) - if err != nil { - t.Fatal(err) - } - if matches { - t.Fatalf("Should not have match anything") - } -} - -// Matches with malformed patterns -func TestMatchesWithMalformedPatterns(t *testing.T) { - matches, err := Matches("/any/path/there", []string{"["}) - if err == nil { - t.Fatal("Should have failed because of a malformed syntax in the pattern") - } - if matches { - t.Fatalf("Should not have match anything") - } -} - -// Test lots of variants of patterns & strings -func TestMatches(t *testing.T) { - tests := []struct { - pattern string - text string - pass bool - }{ - {"**", "file", true}, - {"**", "file/", true}, - {"**/", "file", true}, // weird one - {"**/", "file/", true}, - {"**", "/", true}, - {"**/", "/", true}, - {"**", "dir/file", true}, - {"**/", "dir/file", false}, - {"**", "dir/file/", true}, - {"**/", "dir/file/", true}, - {"**/**", "dir/file", true}, - {"**/**", "dir/file/", true}, - {"dir/**", "dir/file", true}, - {"dir/**", "dir/file/", true}, - {"dir/**", "dir/dir2/file", true}, - {"dir/**", "dir/dir2/file/", true}, - {"**/dir2/*", "dir/dir2/file", true}, - {"**/dir2/*", "dir/dir2/file/", false}, - {"**/dir2/**", "dir/dir2/dir3/file", true}, - {"**/dir2/**", "dir/dir2/dir3/file/", true}, - {"**file", "file", true}, - {"**file", "dir/file", true}, - {"**/file", "dir/file", true}, - {"**file", "dir/dir/file", true}, - {"**/file", "dir/dir/file", true}, - {"**/file*", "dir/dir/file", true}, - {"**/file*", "dir/dir/file.txt", true}, - {"**/file*txt", "dir/dir/file.txt", true}, - {"**/file*.txt", "dir/dir/file.txt", true}, - {"**/file*.txt*", "dir/dir/file.txt", true}, - {"**/**/*.txt", "dir/dir/file.txt", true}, - {"**/**/*.txt2", "dir/dir/file.txt", false}, - {"**/*.txt", "file.txt", true}, - {"**/**/*.txt", "file.txt", true}, - {"a**/*.txt", "a/file.txt", true}, - {"a**/*.txt", "a/dir/file.txt", true}, - {"a**/*.txt", "a/dir/dir/file.txt", true}, - {"a/*.txt", "a/dir/file.txt", false}, - {"a/*.txt", "a/file.txt", true}, - {"a/*.txt**", "a/file.txt", true}, - {"a[b-d]e", "ae", false}, - {"a[b-d]e", "ace", true}, - {"a[b-d]e", "aae", false}, - {"a[^b-d]e", "aze", true}, - {".*", ".foo", true}, - {".*", "foo", false}, - {"abc.def", "abcdef", false}, - {"abc.def", "abc.def", true}, - {"abc.def", "abcZdef", false}, - {"abc?def", "abcZdef", true}, - {"abc?def", "abcdef", false}, - {"a\\*b", "a*b", true}, - {"a\\", "a", false}, - {"a\\", "a\\", false}, - {"a\\\\", "a\\", true}, - {"**/foo/bar", "foo/bar", true}, - {"**/foo/bar", "dir/foo/bar", true}, - {"**/foo/bar", "dir/dir2/foo/bar", true}, - {"abc/**", "abc", false}, - {"abc/**", "abc/def", true}, - {"abc/**", "abc/def/ghi", true}, - } - - for _, test := range tests { - res, _ := regexpMatch(test.pattern, test.text) - if res != test.pass { - t.Fatalf("Failed: %v - res:%v", test, res) - } - } -} - -// An empty string should return true from Empty. -func TestEmpty(t *testing.T) { - empty := empty("") - if !empty { - t.Errorf("failed to get true for an empty string, got %v", empty) - } -} - -func TestCleanPatterns(t *testing.T) { - cleaned, _, _, _ := CleanPatterns([]string{"docs", "config"}) - if len(cleaned) != 2 { - t.Errorf("expected 2 element slice, got %v", len(cleaned)) - } -} - -func TestCleanPatternsStripEmptyPatterns(t *testing.T) { - cleaned, _, _, _ := CleanPatterns([]string{"docs", "config", ""}) - if len(cleaned) != 2 { - t.Errorf("expected 2 element slice, got %v", len(cleaned)) - } -} - -func TestCleanPatternsExceptionFlag(t *testing.T) { - _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md"}) - if !exceptions { - t.Errorf("expected exceptions to be true, got %v", exceptions) - } -} - -func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) { - _, _, exceptions, _ := CleanPatterns([]string{"docs", " !docs/README.md"}) - if !exceptions { - t.Errorf("expected exceptions to be true, got %v", exceptions) - } -} - -func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) { - _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md "}) - if !exceptions { - t.Errorf("expected exceptions to be true, got %v", exceptions) - } -} - -func TestCleanPatternsErrorSingleException(t *testing.T) { - _, _, _, err := CleanPatterns([]string{"!"}) - if err == nil { - t.Errorf("expected error on single exclamation point, got %v", err) - } -} - -func TestCleanPatternsFolderSplit(t *testing.T) { - _, dirs, _, _ := CleanPatterns([]string{"docs/config/CONFIG.md"}) - if dirs[0][0] != "docs" { - t.Errorf("expected first element in dirs slice to be docs, got %v", dirs[0][1]) - } - if dirs[0][1] != "config" { - t.Errorf("expected first element in dirs slice to be config, got %v", dirs[0][1]) - } -} - -func TestCreateIfNotExistsDir(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - - folderToCreate := filepath.Join(tempFolder, "tocreate") - - if err := CreateIfNotExists(folderToCreate, true); err != nil { - t.Fatal(err) - } - fileinfo, err := os.Stat(folderToCreate) - if err != nil { - t.Fatalf("Should have create a folder, got %v", err) - } - - if !fileinfo.IsDir() { - t.Fatalf("Should have been a dir, seems it's not") - } -} - -func TestCreateIfNotExistsFile(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - - fileToCreate := filepath.Join(tempFolder, "file/to/create") - - if err := CreateIfNotExists(fileToCreate, false); err != nil { - t.Fatal(err) - } - fileinfo, err := os.Stat(fileToCreate) - if err != nil { - t.Fatalf("Should have create a file, got %v", err) - } - - if fileinfo.IsDir() { - t.Fatalf("Should have been a file, seems it's not") - } -} - -// These matchTests are stolen from go's filepath Match tests. -type matchTest struct { - pattern, s string - match bool - err error -} - -var matchTests = []matchTest{ - {"abc", "abc", true, nil}, - {"*", "abc", true, nil}, - {"*c", "abc", true, nil}, - {"a*", "a", true, nil}, - {"a*", "abc", true, nil}, - {"a*", "ab/c", false, nil}, - {"a*/b", "abc/b", true, nil}, - {"a*/b", "a/c/b", false, nil}, - {"a*b*c*d*e*/f", "axbxcxdxe/f", true, nil}, - {"a*b*c*d*e*/f", "axbxcxdxexxx/f", true, nil}, - {"a*b*c*d*e*/f", "axbxcxdxe/xxx/f", false, nil}, - {"a*b*c*d*e*/f", "axbxcxdxexxx/fff", false, nil}, - {"a*b?c*x", "abxbbxdbxebxczzx", true, nil}, - {"a*b?c*x", "abxbbxdbxebxczzy", false, nil}, - {"ab[c]", "abc", true, nil}, - {"ab[b-d]", "abc", true, nil}, - {"ab[e-g]", "abc", false, nil}, - {"ab[^c]", "abc", false, nil}, - {"ab[^b-d]", "abc", false, nil}, - {"ab[^e-g]", "abc", true, nil}, - {"a\\*b", "a*b", true, nil}, - {"a\\*b", "ab", false, nil}, - {"a?b", "a☺b", true, nil}, - {"a[^a]b", "a☺b", true, nil}, - {"a???b", "a☺b", false, nil}, - {"a[^a][^a][^a]b", "a☺b", false, nil}, - {"[a-ζ]*", "α", true, nil}, - {"*[a-ζ]", "A", false, nil}, - {"a?b", "a/b", false, nil}, - {"a*b", "a/b", false, nil}, - {"[\\]a]", "]", true, nil}, - {"[\\-]", "-", true, nil}, - {"[x\\-]", "x", true, nil}, - {"[x\\-]", "-", true, nil}, - {"[x\\-]", "z", false, nil}, - {"[\\-x]", "x", true, nil}, - {"[\\-x]", "-", true, nil}, - {"[\\-x]", "a", false, nil}, - {"[]a]", "]", false, filepath.ErrBadPattern}, - {"[-]", "-", false, filepath.ErrBadPattern}, - {"[x-]", "x", false, filepath.ErrBadPattern}, - {"[x-]", "-", false, filepath.ErrBadPattern}, - {"[x-]", "z", false, filepath.ErrBadPattern}, - {"[-x]", "x", false, filepath.ErrBadPattern}, - {"[-x]", "-", false, filepath.ErrBadPattern}, - {"[-x]", "a", false, filepath.ErrBadPattern}, - {"\\", "a", false, filepath.ErrBadPattern}, - {"[a-b-c]", "a", false, filepath.ErrBadPattern}, - {"[", "a", false, filepath.ErrBadPattern}, - {"[^", "a", false, filepath.ErrBadPattern}, - {"[^bc", "a", false, filepath.ErrBadPattern}, - {"a[", "a", false, filepath.ErrBadPattern}, // was nil but IMO its wrong - {"a[", "ab", false, filepath.ErrBadPattern}, - {"*x", "xxx", true, nil}, -} - -func errp(e error) string { - if e == nil { - return "" - } - return e.Error() -} - -// TestMatch test's our version of filepath.Match, called regexpMatch. -func TestMatch(t *testing.T) { - for _, tt := range matchTests { - pattern := tt.pattern - s := tt.s - if runtime.GOOS == "windows" { - if strings.Index(pattern, "\\") >= 0 { - // no escape allowed on windows. - continue - } - pattern = filepath.Clean(pattern) - s = filepath.Clean(s) - } - ok, err := regexpMatch(pattern, s) - if ok != tt.match || err != tt.err { - t.Fatalf("Match(%#q, %#q) = %v, %q want %v, %q", pattern, s, ok, errp(err), tt.match, errp(tt.err)) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go deleted file mode 100644 index 7a95cb2bd..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package homedir - -import ( - "path/filepath" - "testing" -) - -func TestGet(t *testing.T) { - home := Get() - if home == "" { - t.Fatal("returned home directory is empty") - } - - if !filepath.IsAbs(home) { - t.Fatalf("returned path is not absolute: %s", home) - } -} - -func TestGetShortcutString(t *testing.T) { - shortcut := GetShortcutString() - if shortcut == "" { - t.Fatal("returned shortcut string is empty") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix_test.go deleted file mode 100644 index 55b338c96..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix_test.go +++ /dev/null @@ -1,243 +0,0 @@ -// +build !windows - -package idtools - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - "syscall" - "testing" -) - -type node struct { - uid int - gid int -} - -func TestMkdirAllAs(t *testing.T) { - dirName, err := ioutil.TempDir("", "mkdirall") - if err != nil { - t.Fatalf("Couldn't create temp dir: %v", err) - } - defer os.RemoveAll(dirName) - - testTree := map[string]node{ - "usr": {0, 0}, - "usr/bin": {0, 0}, - "lib": {33, 33}, - "lib/x86_64": {45, 45}, - "lib/x86_64/share": {1, 1}, - } - - if err := buildTree(dirName, testTree); err != nil { - t.Fatal(err) - } - - // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid - if err := MkdirAllAs(filepath.Join(dirName, "usr", "share"), 0755, 99, 99); err != nil { - t.Fatal(err) - } - testTree["usr/share"] = node{99, 99} - verifyTree, err := readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } - - // test 2-deep new directories--both should be owned by the uid/gid pair - if err := MkdirAllAs(filepath.Join(dirName, "lib", "some", "other"), 0755, 101, 101); err != nil { - t.Fatal(err) - } - testTree["lib/some"] = node{101, 101} - testTree["lib/some/other"] = node{101, 101} - verifyTree, err = readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } - - // test a directory that already exists; should be chowned, but nothing else - if err := MkdirAllAs(filepath.Join(dirName, "usr"), 0755, 102, 102); err != nil { - t.Fatal(err) - } - testTree["usr"] = node{102, 102} - verifyTree, err = readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } -} - -func TestMkdirAllNewAs(t *testing.T) { - - dirName, err := ioutil.TempDir("", "mkdirnew") - if err != nil { - t.Fatalf("Couldn't create temp dir: %v", err) - } - defer os.RemoveAll(dirName) - - testTree := map[string]node{ - "usr": {0, 0}, - "usr/bin": {0, 0}, - "lib": {33, 33}, - "lib/x86_64": {45, 45}, - "lib/x86_64/share": {1, 1}, - } - - if err := buildTree(dirName, testTree); err != nil { - t.Fatal(err) - } - - // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid - if err := MkdirAllNewAs(filepath.Join(dirName, "usr", "share"), 0755, 99, 99); err != nil { - t.Fatal(err) - } - testTree["usr/share"] = node{99, 99} - verifyTree, err := readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } - - // test 2-deep new directories--both should be owned by the uid/gid pair - if err := MkdirAllNewAs(filepath.Join(dirName, "lib", "some", "other"), 0755, 101, 101); err != nil { - t.Fatal(err) - } - testTree["lib/some"] = node{101, 101} - testTree["lib/some/other"] = node{101, 101} - verifyTree, err = readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } - - // test a directory that already exists; should NOT be chowned - if err := MkdirAllNewAs(filepath.Join(dirName, "usr"), 0755, 102, 102); err != nil { - t.Fatal(err) - } - verifyTree, err = readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } -} - -func TestMkdirAs(t *testing.T) { - - dirName, err := ioutil.TempDir("", "mkdir") - if err != nil { - t.Fatalf("Couldn't create temp dir: %v", err) - } - defer os.RemoveAll(dirName) - - testTree := map[string]node{ - "usr": {0, 0}, - } - if err := buildTree(dirName, testTree); err != nil { - t.Fatal(err) - } - - // test a directory that already exists; should just chown to the requested uid/gid - if err := MkdirAs(filepath.Join(dirName, "usr"), 0755, 99, 99); err != nil { - t.Fatal(err) - } - testTree["usr"] = node{99, 99} - verifyTree, err := readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } - - // create a subdir under a dir which doesn't exist--should fail - if err := MkdirAs(filepath.Join(dirName, "usr", "bin", "subdir"), 0755, 102, 102); err == nil { - t.Fatalf("Trying to create a directory with Mkdir where the parent doesn't exist should have failed") - } - - // create a subdir under an existing dir; should only change the ownership of the new subdir - if err := MkdirAs(filepath.Join(dirName, "usr", "bin"), 0755, 102, 102); err != nil { - t.Fatal(err) - } - testTree["usr/bin"] = node{102, 102} - verifyTree, err = readTree(dirName, "") - if err != nil { - t.Fatal(err) - } - if err := compareTrees(testTree, verifyTree); err != nil { - t.Fatal(err) - } -} - -func buildTree(base string, tree map[string]node) error { - for path, node := range tree { - fullPath := filepath.Join(base, path) - if err := os.MkdirAll(fullPath, 0755); err != nil { - return fmt.Errorf("Couldn't create path: %s; error: %v", fullPath, err) - } - if err := os.Chown(fullPath, node.uid, node.gid); err != nil { - return fmt.Errorf("Couldn't chown path: %s; error: %v", fullPath, err) - } - } - return nil -} - -func readTree(base, root string) (map[string]node, error) { - tree := make(map[string]node) - - dirInfos, err := ioutil.ReadDir(base) - if err != nil { - return nil, fmt.Errorf("Couldn't read directory entries for %q: %v", base, err) - } - - for _, info := range dirInfos { - s := &syscall.Stat_t{} - if err := syscall.Stat(filepath.Join(base, info.Name()), s); err != nil { - return nil, fmt.Errorf("Can't stat file %q: %v", filepath.Join(base, info.Name()), err) - } - tree[filepath.Join(root, info.Name())] = node{int(s.Uid), int(s.Gid)} - if info.IsDir() { - // read the subdirectory - subtree, err := readTree(filepath.Join(base, info.Name()), filepath.Join(root, info.Name())) - if err != nil { - return nil, err - } - for path, nodeinfo := range subtree { - tree[path] = nodeinfo - } - } - } - return tree, nil -} - -func compareTrees(left, right map[string]node) error { - if len(left) != len(right) { - return fmt.Errorf("Trees aren't the same size") - } - for path, nodeLeft := range left { - if nodeRight, ok := right[path]; ok { - if nodeRight.uid != nodeLeft.uid || nodeRight.gid != nodeLeft.gid { - // mismatch - return fmt.Errorf("mismatched ownership for %q: expected: %d:%d, got: %d:%d", path, - nodeLeft.uid, nodeLeft.gid, nodeRight.uid, nodeRight.gid) - } - continue - } - return fmt.Errorf("right tree didn't contain path %q", path) - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe_test.go deleted file mode 100644 index b051139ad..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package ioutils - -import ( - "crypto/sha1" - "encoding/hex" - "math/rand" - "testing" - "time" -) - -func TestBytesPipeRead(t *testing.T) { - buf := NewBytesPipe(nil) - buf.Write([]byte("12")) - buf.Write([]byte("34")) - buf.Write([]byte("56")) - buf.Write([]byte("78")) - buf.Write([]byte("90")) - rd := make([]byte, 4) - n, err := buf.Read(rd) - if err != nil { - t.Fatal(err) - } - if n != 4 { - t.Fatalf("Wrong number of bytes read: %d, should be %d", n, 4) - } - if string(rd) != "1234" { - t.Fatalf("Read %s, but must be %s", rd, "1234") - } - n, err = buf.Read(rd) - if err != nil { - t.Fatal(err) - } - if n != 4 { - t.Fatalf("Wrong number of bytes read: %d, should be %d", n, 4) - } - if string(rd) != "5678" { - t.Fatalf("Read %s, but must be %s", rd, "5679") - } - n, err = buf.Read(rd) - if err != nil { - t.Fatal(err) - } - if n != 2 { - t.Fatalf("Wrong number of bytes read: %d, should be %d", n, 2) - } - if string(rd[:n]) != "90" { - t.Fatalf("Read %s, but must be %s", rd, "90") - } -} - -func TestBytesPipeWrite(t *testing.T) { - buf := NewBytesPipe(nil) - buf.Write([]byte("12")) - buf.Write([]byte("34")) - buf.Write([]byte("56")) - buf.Write([]byte("78")) - buf.Write([]byte("90")) - if string(buf.buf[0]) != "1234567890" { - t.Fatalf("Buffer %s, must be %s", buf.buf, "1234567890") - } -} - -// Write and read in different speeds/chunk sizes and check valid data is read. -func TestBytesPipeWriteRandomChunks(t *testing.T) { - cases := []struct{ iterations, writesPerLoop, readsPerLoop int }{ - {100, 10, 1}, - {1000, 10, 5}, - {1000, 100, 0}, - {1000, 5, 6}, - {10000, 50, 25}, - } - - testMessage := []byte("this is a random string for testing") - // random slice sizes to read and write - writeChunks := []int{25, 35, 15, 20} - readChunks := []int{5, 45, 20, 25} - - for _, c := range cases { - // first pass: write directly to hash - hash := sha1.New() - for i := 0; i < c.iterations*c.writesPerLoop; i++ { - if _, err := hash.Write(testMessage[:writeChunks[i%len(writeChunks)]]); err != nil { - t.Fatal(err) - } - } - expected := hex.EncodeToString(hash.Sum(nil)) - - // write/read through buffer - buf := NewBytesPipe(nil) - hash.Reset() - - done := make(chan struct{}) - - go func() { - // random delay before read starts - <-time.After(time.Duration(rand.Intn(10)) * time.Millisecond) - for i := 0; ; i++ { - p := make([]byte, readChunks[(c.iterations*c.readsPerLoop+i)%len(readChunks)]) - n, _ := buf.Read(p) - if n == 0 { - break - } - hash.Write(p[:n]) - } - - close(done) - }() - - for i := 0; i < c.iterations; i++ { - for w := 0; w < c.writesPerLoop; w++ { - buf.Write(testMessage[:writeChunks[(i*c.writesPerLoop+w)%len(writeChunks)]]) - } - } - buf.Close() - <-done - - actual := hex.EncodeToString(hash.Sum(nil)) - - if expected != actual { - t.Fatalf("BytesPipe returned invalid data. Expected checksum %v, got %v", expected, actual) - } - - } -} - -func BenchmarkBytesPipeWrite(b *testing.B) { - for i := 0; i < b.N; i++ { - readBuf := make([]byte, 1024) - buf := NewBytesPipe(nil) - go func() { - var err error - for err == nil { - _, err = buf.Read(readBuf) - } - }() - for j := 0; j < 1000; j++ { - buf.Write([]byte("pretty short line, because why not?")) - } - buf.Close() - } -} - -func BenchmarkBytesPipeRead(b *testing.B) { - rd := make([]byte, 512) - for i := 0; i < b.N; i++ { - b.StopTimer() - buf := NewBytesPipe(nil) - for j := 0; j < 500; j++ { - buf.Write(make([]byte, 1024)) - } - b.StartTimer() - for j := 0; j < 1000; j++ { - if n, _ := buf.Read(rd); n != 512 { - b.Fatalf("Wrong number of bytes: %d", n) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go deleted file mode 100644 index 896886329..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package ioutils - -import "testing" - -func TestFprintfIfNotEmpty(t *testing.T) { - wc := NewWriteCounter(&NopWriter{}) - n, _ := FprintfIfNotEmpty(wc, "foo%s", "") - - if wc.Count != 0 || n != 0 { - t.Errorf("Wrong count: %v vs. %v vs. 0", wc.Count, n) - } - - n, _ = FprintfIfNotEmpty(wc, "foo%s", "bar") - if wc.Count != 6 || n != 6 { - t.Errorf("Wrong count: %v vs. %v vs. 6", wc.Count, n) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go deleted file mode 100644 index de495b56d..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package ioutils - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "strings" - "testing" -) - -func TestMultiReadSeekerReadAll(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - expectedSize := int64(s1.Len() + s2.Len() + s3.Len()) - - b, err := ioutil.ReadAll(mr) - if err != nil { - t.Fatal(err) - } - - expected := "hello world 1hello world 2hello world 3" - if string(b) != expected { - t.Fatalf("ReadAll failed, got: %q, expected %q", string(b), expected) - } - - size, err := mr.Seek(0, os.SEEK_END) - if err != nil { - t.Fatal(err) - } - if size != expectedSize { - t.Fatalf("reader size does not match, got %d, expected %d", size, expectedSize) - } - - // Reset the position and read again - pos, err := mr.Seek(0, os.SEEK_SET) - if err != nil { - t.Fatal(err) - } - if pos != 0 { - t.Fatalf("expected position to be set to 0, got %d", pos) - } - - b, err = ioutil.ReadAll(mr) - if err != nil { - t.Fatal(err) - } - - if string(b) != expected { - t.Fatalf("ReadAll failed, got: %q, expected %q", string(b), expected) - } -} - -func TestMultiReadSeekerReadEach(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - var totalBytes int64 - for i, s := range []*strings.Reader{s1, s2, s3} { - sLen := int64(s.Len()) - buf := make([]byte, s.Len()) - expected := []byte(fmt.Sprintf("%s %d", str, i+1)) - - if _, err := mr.Read(buf); err != nil && err != io.EOF { - t.Fatal(err) - } - - if !bytes.Equal(buf, expected) { - t.Fatalf("expected %q to be %q", string(buf), string(expected)) - } - - pos, err := mr.Seek(0, os.SEEK_CUR) - if err != nil { - t.Fatalf("iteration: %d, error: %v", i+1, err) - } - - // check that the total bytes read is the current position of the seeker - totalBytes += sLen - if pos != totalBytes { - t.Fatalf("expected current position to be: %d, got: %d, iteration: %d", totalBytes, pos, i+1) - } - - // This tests not only that SEEK_SET and SEEK_CUR give the same values, but that the next iteration is in the expected position as well - newPos, err := mr.Seek(pos, os.SEEK_SET) - if err != nil { - t.Fatal(err) - } - if newPos != pos { - t.Fatalf("expected to get same position when calling SEEK_SET with value from SEEK_CUR, cur: %d, set: %d", pos, newPos) - } - } -} - -func TestMultiReadSeekerReadSpanningChunks(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - buf := make([]byte, s1.Len()+3) - _, err := mr.Read(buf) - if err != nil { - t.Fatal(err) - } - - // expected is the contents of s1 + 3 bytes from s2, ie, the `hel` at the end of this string - expected := "hello world 1hel" - if string(buf) != expected { - t.Fatalf("expected %s to be %s", string(buf), expected) - } -} - -func TestMultiReadSeekerNegativeSeek(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - s1Len := s1.Len() - s2Len := s2.Len() - s3Len := s3.Len() - - s, err := mr.Seek(int64(-1*s3.Len()), os.SEEK_END) - if err != nil { - t.Fatal(err) - } - if s != int64(s1Len+s2Len) { - t.Fatalf("expected %d to be %d", s, s1.Len()+s2.Len()) - } - - buf := make([]byte, s3Len) - if _, err := mr.Read(buf); err != nil && err != io.EOF { - t.Fatal(err) - } - expected := fmt.Sprintf("%s %d", str, 3) - if string(buf) != fmt.Sprintf("%s %d", str, 3) { - t.Fatalf("expected %q to be %q", string(buf), expected) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go deleted file mode 100644 index 8f9e03c31..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package ioutils - -import ( - "fmt" - "io/ioutil" - "strings" - "testing" - "time" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" -) - -// Implement io.Reader -type errorReader struct{} - -func (r *errorReader) Read(p []byte) (int, error) { - return 0, fmt.Errorf("Error reader always fail.") -} - -func TestReadCloserWrapperClose(t *testing.T) { - reader := strings.NewReader("A string reader") - wrapper := NewReadCloserWrapper(reader, func() error { - return fmt.Errorf("This will be called when closing") - }) - err := wrapper.Close() - if err == nil || !strings.Contains(err.Error(), "This will be called when closing") { - t.Fatalf("readCloserWrapper should have call the anonymous func and thus, fail.") - } -} - -func TestReaderErrWrapperReadOnError(t *testing.T) { - called := false - reader := &errorReader{} - wrapper := NewReaderErrWrapper(reader, func() { - called = true - }) - _, err := wrapper.Read([]byte{}) - if err == nil || !strings.Contains(err.Error(), "Error reader always fail.") { - t.Fatalf("readErrWrapper should returned an error") - } - if !called { - t.Fatalf("readErrWrapper should have call the anonymous function on failure") - } -} - -func TestReaderErrWrapperRead(t *testing.T) { - reader := strings.NewReader("a string reader.") - wrapper := NewReaderErrWrapper(reader, func() { - t.Fatalf("readErrWrapper should not have called the anonymous function") - }) - // Read 20 byte (should be ok with the string above) - num, err := wrapper.Read(make([]byte, 20)) - if err != nil { - t.Fatal(err) - } - if num != 16 { - t.Fatalf("readerErrWrapper should have read 16 byte, but read %d", num) - } -} - -func TestHashData(t *testing.T) { - reader := strings.NewReader("hash-me") - actual, err := HashData(reader) - if err != nil { - t.Fatal(err) - } - expected := "sha256:4d11186aed035cc624d553e10db358492c84a7cd6b9670d92123c144930450aa" - if actual != expected { - t.Fatalf("Expecting %s, got %s", expected, actual) - } -} - -type perpetualReader struct{} - -func (p *perpetualReader) Read(buf []byte) (n int, err error) { - for i := 0; i != len(buf); i++ { - buf[i] = 'a' - } - return len(buf), nil -} - -func TestCancelReadCloser(t *testing.T) { - ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) - cancelReadCloser := NewCancelReadCloser(ctx, ioutil.NopCloser(&perpetualReader{})) - for { - var buf [128]byte - _, err := cancelReadCloser.Read(buf[:]) - if err == context.DeadlineExceeded { - break - } else if err != nil { - t.Fatalf("got unexpected error: %v", err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go deleted file mode 100644 index 564b1cd4f..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package ioutils - -import ( - "bytes" - "strings" - "testing" -) - -func TestWriteCloserWrapperClose(t *testing.T) { - called := false - writer := bytes.NewBuffer([]byte{}) - wrapper := NewWriteCloserWrapper(writer, func() error { - called = true - return nil - }) - if err := wrapper.Close(); err != nil { - t.Fatal(err) - } - if !called { - t.Fatalf("writeCloserWrapper should have call the anonymous function.") - } -} - -func TestNopWriteCloser(t *testing.T) { - writer := bytes.NewBuffer([]byte{}) - wrapper := NopWriteCloser(writer) - if err := wrapper.Close(); err != nil { - t.Fatal("NopWriteCloser always return nil on Close.") - } - -} - -func TestNopWriter(t *testing.T) { - nw := &NopWriter{} - l, err := nw.Write([]byte{'c'}) - if err != nil { - t.Fatal(err) - } - if l != 1 { - t.Fatalf("Expected 1 got %d", l) - } -} - -func TestWriteCounter(t *testing.T) { - dummy1 := "This is a dummy string." - dummy2 := "This is another dummy string." - totalLength := int64(len(dummy1) + len(dummy2)) - - reader1 := strings.NewReader(dummy1) - reader2 := strings.NewReader(dummy2) - - var buffer bytes.Buffer - wc := NewWriteCounter(&buffer) - - reader1.WriteTo(wc) - reader2.WriteTo(wc) - - if wc.Count != totalLength { - t.Errorf("Wrong count: %d vs. %d", wc.Count, totalLength) - } - - if buffer.String() != dummy1+dummy2 { - t.Error("Wrong message written") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath_test.go deleted file mode 100644 index 01865eff0..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package longpath - -import ( - "strings" - "testing" -) - -func TestStandardLongPath(t *testing.T) { - c := `C:\simple\path` - longC := AddPrefix(c) - if !strings.EqualFold(longC, `\\?\C:\simple\path`) { - t.Errorf("Wrong long path returned. Original = %s ; Long = %s", c, longC) - } -} - -func TestUNCLongPath(t *testing.T) { - c := `\\server\share\path` - longC := AddPrefix(c) - if !strings.EqualFold(longC, `\\?\UNC\server\share\path`) { - t.Errorf("Wrong UNC long path returned. Original = %s ; Long = %s", c, longC) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go deleted file mode 100644 index 78689800b..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package pools - -import ( - "bufio" - "bytes" - "io" - "strings" - "testing" -) - -func TestBufioReaderPoolGetWithNoReaderShouldCreateOne(t *testing.T) { - reader := BufioReader32KPool.Get(nil) - if reader == nil { - t.Fatalf("BufioReaderPool should have create a bufio.Reader but did not.") - } -} - -func TestBufioReaderPoolPutAndGet(t *testing.T) { - sr := bufio.NewReader(strings.NewReader("foobar")) - reader := BufioReader32KPool.Get(sr) - if reader == nil { - t.Fatalf("BufioReaderPool should not return a nil reader.") - } - // verify the first 3 byte - buf1 := make([]byte, 3) - _, err := reader.Read(buf1) - if err != nil { - t.Fatal(err) - } - if actual := string(buf1); actual != "foo" { - t.Fatalf("The first letter should have been 'foo' but was %v", actual) - } - BufioReader32KPool.Put(reader) - // Try to read the next 3 bytes - _, err = sr.Read(make([]byte, 3)) - if err == nil || err != io.EOF { - t.Fatalf("The buffer should have been empty, issue an EOF error.") - } -} - -type simpleReaderCloser struct { - io.Reader - closed bool -} - -func (r *simpleReaderCloser) Close() error { - r.closed = true - return nil -} - -func TestNewReadCloserWrapperWithAReadCloser(t *testing.T) { - br := bufio.NewReader(strings.NewReader("")) - sr := &simpleReaderCloser{ - Reader: strings.NewReader("foobar"), - closed: false, - } - reader := BufioReader32KPool.NewReadCloserWrapper(br, sr) - if reader == nil { - t.Fatalf("NewReadCloserWrapper should not return a nil reader.") - } - // Verify the content of reader - buf := make([]byte, 3) - _, err := reader.Read(buf) - if err != nil { - t.Fatal(err) - } - if actual := string(buf); actual != "foo" { - t.Fatalf("The first 3 letter should have been 'foo' but were %v", actual) - } - reader.Close() - // Read 3 more bytes "bar" - _, err = reader.Read(buf) - if err != nil { - t.Fatal(err) - } - if actual := string(buf); actual != "bar" { - t.Fatalf("The first 3 letter should have been 'bar' but were %v", actual) - } - if !sr.closed { - t.Fatalf("The ReaderCloser should have been closed, it is not.") - } -} - -func TestBufioWriterPoolGetWithNoReaderShouldCreateOne(t *testing.T) { - writer := BufioWriter32KPool.Get(nil) - if writer == nil { - t.Fatalf("BufioWriterPool should have create a bufio.Writer but did not.") - } -} - -func TestBufioWriterPoolPutAndGet(t *testing.T) { - buf := new(bytes.Buffer) - bw := bufio.NewWriter(buf) - writer := BufioWriter32KPool.Get(bw) - if writer == nil { - t.Fatalf("BufioReaderPool should not return a nil writer.") - } - written, err := writer.Write([]byte("foobar")) - if err != nil { - t.Fatal(err) - } - if written != 6 { - t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) - } - // Make sure we Flush all the way ? - writer.Flush() - bw.Flush() - if len(buf.Bytes()) != 6 { - t.Fatalf("The buffer should contain 6 bytes ('foobar') but contains %v ('%v')", buf.Bytes(), string(buf.Bytes())) - } - // Reset the buffer - buf.Reset() - BufioWriter32KPool.Put(writer) - // Try to write something - written, err = writer.Write([]byte("barfoo")) - if err != nil { - t.Fatal(err) - } - // If we now try to flush it, it should panic (the writer is nil) - // recover it - defer func() { - if r := recover(); r == nil { - t.Fatal("Trying to flush the writter should have 'paniced', did not.") - } - }() - writer.Flush() -} - -type simpleWriterCloser struct { - io.Writer - closed bool -} - -func (r *simpleWriterCloser) Close() error { - r.closed = true - return nil -} - -func TestNewWriteCloserWrapperWithAWriteCloser(t *testing.T) { - buf := new(bytes.Buffer) - bw := bufio.NewWriter(buf) - sw := &simpleWriterCloser{ - Writer: new(bytes.Buffer), - closed: false, - } - bw.Flush() - writer := BufioWriter32KPool.NewWriteCloserWrapper(bw, sw) - if writer == nil { - t.Fatalf("BufioReaderPool should not return a nil writer.") - } - written, err := writer.Write([]byte("foobar")) - if err != nil { - t.Fatal(err) - } - if written != 6 { - t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) - } - writer.Close() - if !sw.closed { - t.Fatalf("The ReaderCloser should have been closed, it is not.") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go deleted file mode 100644 index 88d88d41e..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go +++ /dev/null @@ -1,261 +0,0 @@ -package stdcopy - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "strings" - "testing" -) - -func TestNewStdWriter(t *testing.T) { - writer := NewStdWriter(ioutil.Discard, Stdout) - if writer == nil { - t.Fatalf("NewStdWriter with an invalid StdType should not return nil.") - } -} - -func TestWriteWithUnitializedStdWriter(t *testing.T) { - writer := StdWriter{ - Writer: nil, - prefix: Stdout, - sizeBuf: make([]byte, 4), - } - n, err := writer.Write([]byte("Something here")) - if n != 0 || err == nil { - t.Fatalf("Should fail when given an uncomplete or uninitialized StdWriter") - } -} - -func TestWriteWithNilBytes(t *testing.T) { - writer := NewStdWriter(ioutil.Discard, Stdout) - n, err := writer.Write(nil) - if err != nil { - t.Fatalf("Shouldn't have fail when given no data") - } - if n > 0 { - t.Fatalf("Write should have written 0 byte, but has written %d", n) - } -} - -func TestWrite(t *testing.T) { - writer := NewStdWriter(ioutil.Discard, Stdout) - data := []byte("Test StdWrite.Write") - n, err := writer.Write(data) - if err != nil { - t.Fatalf("Error while writing with StdWrite") - } - if n != len(data) { - t.Fatalf("Write should have written %d byte but wrote %d.", len(data), n) - } -} - -type errWriter struct { - n int - err error -} - -func (f *errWriter) Write(buf []byte) (int, error) { - return f.n, f.err -} - -func TestWriteWithWriterError(t *testing.T) { - expectedError := errors.New("expected") - expectedReturnedBytes := 10 - writer := NewStdWriter(&errWriter{ - n: stdWriterPrefixLen + expectedReturnedBytes, - err: expectedError}, Stdout) - data := []byte("This won't get written, sigh") - n, err := writer.Write(data) - if err != expectedError { - t.Fatalf("Didn't get expected error.") - } - if n != expectedReturnedBytes { - t.Fatalf("Didn't get expected writen bytes %d, got %d.", - expectedReturnedBytes, n) - } -} - -func TestWriteDoesNotReturnNegativeWrittenBytes(t *testing.T) { - writer := NewStdWriter(&errWriter{n: -1}, Stdout) - data := []byte("This won't get written, sigh") - actual, _ := writer.Write(data) - if actual != 0 { - t.Fatalf("Expected returned written bytes equal to 0, got %d", actual) - } -} - -func getSrcBuffer(stdOutBytes, stdErrBytes []byte) (buffer *bytes.Buffer, err error) { - buffer = new(bytes.Buffer) - dstOut := NewStdWriter(buffer, Stdout) - _, err = dstOut.Write(stdOutBytes) - if err != nil { - return - } - dstErr := NewStdWriter(buffer, Stderr) - _, err = dstErr.Write(stdErrBytes) - return -} - -func TestStdCopyWriteAndRead(t *testing.T) { - stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) - stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) - buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) - if err != nil { - t.Fatal(err) - } - written, err := StdCopy(ioutil.Discard, ioutil.Discard, buffer) - if err != nil { - t.Fatal(err) - } - expectedTotalWritten := len(stdOutBytes) + len(stdErrBytes) - if written != int64(expectedTotalWritten) { - t.Fatalf("Expected to have total of %d bytes written, got %d", expectedTotalWritten, written) - } -} - -type customReader struct { - n int - err error - totalCalls int - correctCalls int - src *bytes.Buffer -} - -func (f *customReader) Read(buf []byte) (int, error) { - f.totalCalls++ - if f.totalCalls <= f.correctCalls { - return f.src.Read(buf) - } - return f.n, f.err -} - -func TestStdCopyReturnsErrorReadingHeader(t *testing.T) { - expectedError := errors.New("error") - reader := &customReader{ - err: expectedError} - written, err := StdCopy(ioutil.Discard, ioutil.Discard, reader) - if written != 0 { - t.Fatalf("Expected 0 bytes read, got %d", written) - } - if err != expectedError { - t.Fatalf("Didn't get expected error") - } -} - -func TestStdCopyReturnsErrorReadingFrame(t *testing.T) { - expectedError := errors.New("error") - stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) - stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) - buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) - if err != nil { - t.Fatal(err) - } - reader := &customReader{ - correctCalls: 1, - n: stdWriterPrefixLen + 1, - err: expectedError, - src: buffer} - written, err := StdCopy(ioutil.Discard, ioutil.Discard, reader) - if written != 0 { - t.Fatalf("Expected 0 bytes read, got %d", written) - } - if err != expectedError { - t.Fatalf("Didn't get expected error") - } -} - -func TestStdCopyDetectsCorruptedFrame(t *testing.T) { - stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) - stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) - buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) - if err != nil { - t.Fatal(err) - } - reader := &customReader{ - correctCalls: 1, - n: stdWriterPrefixLen + 1, - err: io.EOF, - src: buffer} - written, err := StdCopy(ioutil.Discard, ioutil.Discard, reader) - if written != startingBufLen { - t.Fatalf("Expected 0 bytes read, got %d", written) - } - if err != nil { - t.Fatal("Didn't get nil error") - } -} - -func TestStdCopyWithInvalidInputHeader(t *testing.T) { - dstOut := NewStdWriter(ioutil.Discard, Stdout) - dstErr := NewStdWriter(ioutil.Discard, Stderr) - src := strings.NewReader("Invalid input") - _, err := StdCopy(dstOut, dstErr, src) - if err == nil { - t.Fatal("StdCopy with invalid input header should fail.") - } -} - -func TestStdCopyWithCorruptedPrefix(t *testing.T) { - data := []byte{0x01, 0x02, 0x03} - src := bytes.NewReader(data) - written, err := StdCopy(nil, nil, src) - if err != nil { - t.Fatalf("StdCopy should not return an error with corrupted prefix.") - } - if written != 0 { - t.Fatalf("StdCopy should have written 0, but has written %d", written) - } -} - -func TestStdCopyReturnsWriteErrors(t *testing.T) { - stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) - stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) - buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) - if err != nil { - t.Fatal(err) - } - expectedError := errors.New("expected") - - dstOut := &errWriter{err: expectedError} - - written, err := StdCopy(dstOut, ioutil.Discard, buffer) - if written != 0 { - t.Fatalf("StdCopy should have written 0, but has written %d", written) - } - if err != expectedError { - t.Fatalf("Didn't get expected error, got %v", err) - } -} - -func TestStdCopyDetectsNotFullyWrittenFrames(t *testing.T) { - stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) - stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) - buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) - if err != nil { - t.Fatal(err) - } - dstOut := &errWriter{n: startingBufLen - 10} - - written, err := StdCopy(dstOut, ioutil.Discard, buffer) - if written != 0 { - t.Fatalf("StdCopy should have return 0 written bytes, but returned %d", written) - } - if err != io.ErrShortWrite { - t.Fatalf("Didn't get expected io.ErrShortWrite error") - } -} - -func BenchmarkWrite(b *testing.B) { - w := NewStdWriter(ioutil.Discard, Stdout) - data := []byte("Test line for testing stdwriter performance\n") - data = bytes.Repeat(data, 100) - b.SetBytes(int64(len(data))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := w.Write(data); err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_test.go deleted file mode 100644 index 5c87df32a..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package system - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" - "time" -) - -// prepareTempFile creates a temporary file in a temporary directory. -func prepareTempFile(t *testing.T) (string, string) { - dir, err := ioutil.TempDir("", "docker-system-test") - if err != nil { - t.Fatal(err) - } - - file := filepath.Join(dir, "exist") - if err := ioutil.WriteFile(file, []byte("hello"), 0644); err != nil { - t.Fatal(err) - } - return file, dir -} - -// TestChtimes tests Chtimes on a tempfile. Test only mTime, because aTime is OS dependent -func TestChtimes(t *testing.T) { - file, dir := prepareTempFile(t) - defer os.RemoveAll(dir) - - beforeUnixEpochTime := time.Unix(0, 0).Add(-100 * time.Second) - unixEpochTime := time.Unix(0, 0) - afterUnixEpochTime := time.Unix(100, 0) - unixMaxTime := maxTime - - // Test both aTime and mTime set to Unix Epoch - Chtimes(file, unixEpochTime, unixEpochTime) - - f, err := os.Stat(file) - if err != nil { - t.Fatal(err) - } - - if f.ModTime() != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, f.ModTime()) - } - - // Test aTime before Unix Epoch and mTime set to Unix Epoch - Chtimes(file, beforeUnixEpochTime, unixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - if f.ModTime() != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, f.ModTime()) - } - - // Test aTime set to Unix Epoch and mTime before Unix Epoch - Chtimes(file, unixEpochTime, beforeUnixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - if f.ModTime() != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, f.ModTime()) - } - - // Test both aTime and mTime set to after Unix Epoch (valid time) - Chtimes(file, afterUnixEpochTime, afterUnixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - if f.ModTime() != afterUnixEpochTime { - t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, f.ModTime()) - } - - // Test both aTime and mTime set to Unix max time - Chtimes(file, unixMaxTime, unixMaxTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - if f.ModTime().Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { - t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), f.ModTime().Truncate(time.Second)) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix_test.go deleted file mode 100644 index fcd594023..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// +build linux freebsd - -package system - -import ( - "os" - "syscall" - "testing" - "time" -) - -// TestChtimes tests Chtimes access time on a tempfile on Linux -func TestChtimesLinux(t *testing.T) { - file, dir := prepareTempFile(t) - defer os.RemoveAll(dir) - - beforeUnixEpochTime := time.Unix(0, 0).Add(-100 * time.Second) - unixEpochTime := time.Unix(0, 0) - afterUnixEpochTime := time.Unix(100, 0) - unixMaxTime := maxTime - - // Test both aTime and mTime set to Unix Epoch - Chtimes(file, unixEpochTime, unixEpochTime) - - f, err := os.Stat(file) - if err != nil { - t.Fatal(err) - } - - stat := f.Sys().(*syscall.Stat_t) - aTime := time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) - if aTime != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) - } - - // Test aTime before Unix Epoch and mTime set to Unix Epoch - Chtimes(file, beforeUnixEpochTime, unixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) - if aTime != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) - } - - // Test aTime set to Unix Epoch and mTime before Unix Epoch - Chtimes(file, unixEpochTime, beforeUnixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) - if aTime != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) - } - - // Test both aTime and mTime set to after Unix Epoch (valid time) - Chtimes(file, afterUnixEpochTime, afterUnixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) - if aTime != afterUnixEpochTime { - t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, aTime) - } - - // Test both aTime and mTime set to Unix max time - Chtimes(file, unixMaxTime, unixMaxTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) - if aTime.Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { - t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), aTime.Truncate(time.Second)) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows_test.go deleted file mode 100644 index be57558e1..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// +build windows - -package system - -import ( - "os" - "syscall" - "testing" - "time" -) - -// TestChtimes tests Chtimes access time on a tempfile on Windows -func TestChtimesWindows(t *testing.T) { - file, dir := prepareTempFile(t) - defer os.RemoveAll(dir) - - beforeUnixEpochTime := time.Unix(0, 0).Add(-100 * time.Second) - unixEpochTime := time.Unix(0, 0) - afterUnixEpochTime := time.Unix(100, 0) - unixMaxTime := maxTime - - // Test both aTime and mTime set to Unix Epoch - Chtimes(file, unixEpochTime, unixEpochTime) - - f, err := os.Stat(file) - if err != nil { - t.Fatal(err) - } - - aTime := time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) - if aTime != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) - } - - // Test aTime before Unix Epoch and mTime set to Unix Epoch - Chtimes(file, beforeUnixEpochTime, unixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) - if aTime != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) - } - - // Test aTime set to Unix Epoch and mTime before Unix Epoch - Chtimes(file, unixEpochTime, beforeUnixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) - if aTime != unixEpochTime { - t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) - } - - // Test both aTime and mTime set to after Unix Epoch (valid time) - Chtimes(file, afterUnixEpochTime, afterUnixEpochTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) - if aTime != afterUnixEpochTime { - t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, aTime) - } - - // Test both aTime and mTime set to Unix max time - Chtimes(file, unixMaxTime, unixMaxTime) - - f, err = os.Stat(file) - if err != nil { - t.Fatal(err) - } - - aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) - if aTime.Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { - t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), aTime.Truncate(time.Second)) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_unix_test.go deleted file mode 100644 index 062cf53bf..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_unix_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build linux freebsd - -package system - -import ( - "os" - "testing" -) - -// TestLstat tests Lstat for existing and non existing files -func TestLstat(t *testing.T) { - file, invalid, _, dir := prepareFiles(t) - defer os.RemoveAll(dir) - - statFile, err := Lstat(file) - if err != nil { - t.Fatal(err) - } - if statFile == nil { - t.Fatal("returned empty stat for existing file") - } - - statInvalid, err := Lstat(invalid) - if err == nil { - t.Fatal("did not return error for non-existing file") - } - if statInvalid != nil { - t.Fatal("returned non-nil stat for non-existing file") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unix_test.go deleted file mode 100644 index dda048379..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unix_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build linux freebsd - -package system - -import ( - "strings" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/go-units" -) - -// TestMemInfo tests parseMemInfo with a static meminfo string -func TestMemInfo(t *testing.T) { - const input = ` - MemTotal: 1 kB - MemFree: 2 kB - SwapTotal: 3 kB - SwapFree: 4 kB - Malformed1: - Malformed2: 1 - Malformed3: 2 MB - Malformed4: X kB - ` - meminfo, err := parseMemInfo(strings.NewReader(input)) - if err != nil { - t.Fatal(err) - } - if meminfo.MemTotal != 1*units.KiB { - t.Fatalf("Unexpected MemTotal: %d", meminfo.MemTotal) - } - if meminfo.MemFree != 2*units.KiB { - t.Fatalf("Unexpected MemFree: %d", meminfo.MemFree) - } - if meminfo.SwapTotal != 3*units.KiB { - t.Fatalf("Unexpected SwapTotal: %d", meminfo.SwapTotal) - } - if meminfo.SwapFree != 4*units.KiB { - t.Fatalf("Unexpected SwapFree: %d", meminfo.SwapFree) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unix_test.go deleted file mode 100644 index dee8d30a1..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unix_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// +build linux freebsd - -package system - -import ( - "os" - "syscall" - "testing" -) - -// TestFromStatT tests fromStatT for a tempfile -func TestFromStatT(t *testing.T) { - file, _, _, dir := prepareFiles(t) - defer os.RemoveAll(dir) - - stat := &syscall.Stat_t{} - err := syscall.Lstat(file, stat) - - s, err := fromStatT(stat) - if err != nil { - t.Fatal(err) - } - - if stat.Mode != s.Mode() { - t.Fatal("got invalid mode") - } - if stat.Uid != s.UID() { - t.Fatal("got invalid uid") - } - if stat.Gid != s.GID() { - t.Fatal("got invalid gid") - } - if stat.Rdev != s.Rdev() { - t.Fatal("got invalid rdev") - } - if stat.Mtim != s.Mtim() { - t.Fatal("got invalid mtim") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unix_test.go deleted file mode 100644 index 1ee0d099f..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unix_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// +build linux freebsd - -package system - -import ( - "io/ioutil" - "os" - "path/filepath" - "syscall" - "testing" -) - -// prepareFiles creates files for testing in the temp directory -func prepareFiles(t *testing.T) (string, string, string, string) { - dir, err := ioutil.TempDir("", "docker-system-test") - if err != nil { - t.Fatal(err) - } - - file := filepath.Join(dir, "exist") - if err := ioutil.WriteFile(file, []byte("hello"), 0644); err != nil { - t.Fatal(err) - } - - invalid := filepath.Join(dir, "doesnt-exist") - - symlink := filepath.Join(dir, "symlink") - if err := os.Symlink(file, symlink); err != nil { - t.Fatal(err) - } - - return file, invalid, symlink, dir -} - -func TestLUtimesNano(t *testing.T) { - file, invalid, symlink, dir := prepareFiles(t) - defer os.RemoveAll(dir) - - before, err := os.Stat(file) - if err != nil { - t.Fatal(err) - } - - ts := []syscall.Timespec{{0, 0}, {0, 0}} - if err := LUtimesNano(symlink, ts); err != nil { - t.Fatal(err) - } - - symlinkInfo, err := os.Lstat(symlink) - if err != nil { - t.Fatal(err) - } - if before.ModTime().Unix() == symlinkInfo.ModTime().Unix() { - t.Fatal("The modification time of the symlink should be different") - } - - fileInfo, err := os.Stat(file) - if err != nil { - t.Fatal(err) - } - if before.ModTime().Unix() != fileInfo.ModTime().Unix() { - t.Fatal("The modification time of the file should be same") - } - - if err := LUtimesNano(invalid, ts); err == nil { - t.Fatal("Doesn't return an error on a non-existing file") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration_test.go deleted file mode 100644 index 63baa515b..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package units - -import ( - "fmt" - "testing" - "time" -) - -func ExampleHumanDuration() { - fmt.Println(HumanDuration(450 * time.Millisecond)) - fmt.Println(HumanDuration(47 * time.Second)) - fmt.Println(HumanDuration(1 * time.Minute)) - fmt.Println(HumanDuration(3 * time.Minute)) - fmt.Println(HumanDuration(35 * time.Minute)) - fmt.Println(HumanDuration(35*time.Minute + 40*time.Second)) - fmt.Println(HumanDuration(1 * time.Hour)) - fmt.Println(HumanDuration(1*time.Hour + 45*time.Minute)) - fmt.Println(HumanDuration(3 * time.Hour)) - fmt.Println(HumanDuration(3*time.Hour + 59*time.Minute)) - fmt.Println(HumanDuration(3*time.Hour + 60*time.Minute)) - fmt.Println(HumanDuration(24 * time.Hour)) - fmt.Println(HumanDuration(24*time.Hour + 12*time.Hour)) - fmt.Println(HumanDuration(2 * 24 * time.Hour)) - fmt.Println(HumanDuration(7 * 24 * time.Hour)) - fmt.Println(HumanDuration(13*24*time.Hour + 5*time.Hour)) - fmt.Println(HumanDuration(2 * 7 * 24 * time.Hour)) - fmt.Println(HumanDuration(2*7*24*time.Hour + 4*24*time.Hour)) - fmt.Println(HumanDuration(3 * 7 * 24 * time.Hour)) - fmt.Println(HumanDuration(4 * 7 * 24 * time.Hour)) - fmt.Println(HumanDuration(4*7*24*time.Hour + 3*24*time.Hour)) - fmt.Println(HumanDuration(1 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(1*30*24*time.Hour + 2*7*24*time.Hour)) - fmt.Println(HumanDuration(2 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(3*30*24*time.Hour + 1*7*24*time.Hour)) - fmt.Println(HumanDuration(5*30*24*time.Hour + 2*7*24*time.Hour)) - fmt.Println(HumanDuration(13 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(23 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(24 * 30 * 24 * time.Hour)) - fmt.Println(HumanDuration(24*30*24*time.Hour + 2*7*24*time.Hour)) - fmt.Println(HumanDuration(3*365*24*time.Hour + 2*30*24*time.Hour)) -} - -func TestHumanDuration(t *testing.T) { - // Useful duration abstractions - day := 24 * time.Hour - week := 7 * day - month := 30 * day - year := 365 * day - - assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond)) - assertEquals(t, "47 seconds", HumanDuration(47*time.Second)) - assertEquals(t, "About a minute", HumanDuration(1*time.Minute)) - assertEquals(t, "3 minutes", HumanDuration(3*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute)) - assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute)) - assertEquals(t, "24 hours", HumanDuration(24*time.Hour)) - assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour)) - assertEquals(t, "2 days", HumanDuration(2*day)) - assertEquals(t, "7 days", HumanDuration(7*day)) - assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour)) - assertEquals(t, "2 weeks", HumanDuration(2*week)) - assertEquals(t, "2 weeks", HumanDuration(2*week+4*day)) - assertEquals(t, "3 weeks", HumanDuration(3*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week+3*day)) - assertEquals(t, "4 weeks", HumanDuration(1*month)) - assertEquals(t, "6 weeks", HumanDuration(1*month+2*week)) - assertEquals(t, "8 weeks", HumanDuration(2*month)) - assertEquals(t, "3 months", HumanDuration(3*month+1*week)) - assertEquals(t, "5 months", HumanDuration(5*month+2*week)) - assertEquals(t, "13 months", HumanDuration(13*month)) - assertEquals(t, "23 months", HumanDuration(23*month)) - assertEquals(t, "24 months", HumanDuration(24*month)) - assertEquals(t, "2 years", HumanDuration(24*month+2*week)) - assertEquals(t, "3 years", HumanDuration(3*year+2*month)) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size_test.go deleted file mode 100644 index a968f5c0d..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package units - -import ( - "fmt" - "reflect" - "runtime" - "strings" - "testing" -) - -func ExampleBytesSize() { - fmt.Println(BytesSize(1024)) - fmt.Println(BytesSize(1024 * 1024)) - fmt.Println(BytesSize(1048576)) - fmt.Println(BytesSize(2 * MiB)) - fmt.Println(BytesSize(3.42 * GiB)) - fmt.Println(BytesSize(5.372 * TiB)) - fmt.Println(BytesSize(2.22 * PiB)) -} - -func ExampleHumanSize() { - fmt.Println(HumanSize(1000)) - fmt.Println(HumanSize(1024)) - fmt.Println(HumanSize(1000000)) - fmt.Println(HumanSize(1048576)) - fmt.Println(HumanSize(2 * MB)) - fmt.Println(HumanSize(float64(3.42 * GB))) - fmt.Println(HumanSize(float64(5.372 * TB))) - fmt.Println(HumanSize(float64(2.22 * PB))) -} - -func ExampleFromHumanSize() { - fmt.Println(FromHumanSize("32")) - fmt.Println(FromHumanSize("32b")) - fmt.Println(FromHumanSize("32B")) - fmt.Println(FromHumanSize("32k")) - fmt.Println(FromHumanSize("32K")) - fmt.Println(FromHumanSize("32kb")) - fmt.Println(FromHumanSize("32Kb")) - fmt.Println(FromHumanSize("32Mb")) - fmt.Println(FromHumanSize("32Gb")) - fmt.Println(FromHumanSize("32Tb")) - fmt.Println(FromHumanSize("32Pb")) -} - -func ExampleRAMInBytes() { - fmt.Println(RAMInBytes("32")) - fmt.Println(RAMInBytes("32b")) - fmt.Println(RAMInBytes("32B")) - fmt.Println(RAMInBytes("32k")) - fmt.Println(RAMInBytes("32K")) - fmt.Println(RAMInBytes("32kb")) - fmt.Println(RAMInBytes("32Kb")) - fmt.Println(RAMInBytes("32Mb")) - fmt.Println(RAMInBytes("32Gb")) - fmt.Println(RAMInBytes("32Tb")) - fmt.Println(RAMInBytes("32Pb")) - fmt.Println(RAMInBytes("32PB")) - fmt.Println(RAMInBytes("32P")) -} - -func TestBytesSize(t *testing.T) { - assertEquals(t, "1 KiB", BytesSize(1024)) - assertEquals(t, "1 MiB", BytesSize(1024*1024)) - assertEquals(t, "1 MiB", BytesSize(1048576)) - assertEquals(t, "2 MiB", BytesSize(2*MiB)) - assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) - assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) - assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) -} - -func TestHumanSize(t *testing.T) { - assertEquals(t, "1 kB", HumanSize(1000)) - assertEquals(t, "1.024 kB", HumanSize(1024)) - assertEquals(t, "1 MB", HumanSize(1000000)) - assertEquals(t, "1.049 MB", HumanSize(1048576)) - assertEquals(t, "2 MB", HumanSize(2*MB)) - assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB))) - assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB))) - assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB))) -} - -func TestFromHumanSize(t *testing.T) { - assertSuccessEquals(t, 32, FromHumanSize, "32") - assertSuccessEquals(t, 32, FromHumanSize, "32b") - assertSuccessEquals(t, 32, FromHumanSize, "32B") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32k") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32K") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb") - assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb") - assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb") - assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb") - assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb") - - assertError(t, FromHumanSize, "") - assertError(t, FromHumanSize, "hello") - assertError(t, FromHumanSize, "-32") - assertError(t, FromHumanSize, "32.3") - assertError(t, FromHumanSize, " 32 ") - assertError(t, FromHumanSize, "32.3Kb") - assertError(t, FromHumanSize, "32 mb") - assertError(t, FromHumanSize, "32m b") - assertError(t, FromHumanSize, "32bm") -} - -func TestRAMInBytes(t *testing.T) { - assertSuccessEquals(t, 32, RAMInBytes, "32") - assertSuccessEquals(t, 32, RAMInBytes, "32b") - assertSuccessEquals(t, 32, RAMInBytes, "32B") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") - assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") - assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") - assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P") - - assertError(t, RAMInBytes, "") - assertError(t, RAMInBytes, "hello") - assertError(t, RAMInBytes, "-32") - assertError(t, RAMInBytes, "32.3") - assertError(t, RAMInBytes, " 32 ") - assertError(t, RAMInBytes, "32.3Kb") - assertError(t, RAMInBytes, "32 mb") - assertError(t, RAMInBytes, "32m b") - assertError(t, RAMInBytes, "32bm") -} - -func assertEquals(t *testing.T, expected, actual interface{}) { - if expected != actual { - t.Errorf("Expected '%v' but got '%v'", expected, actual) - } -} - -// func that maps to the parse function signatures as testing abstraction -type parseFn func(string) (int64, error) - -// Define 'String()' for pretty-print -func (fn parseFn) String() string { - fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() - return fnName[strings.LastIndex(fnName, ".")+1:] -} - -func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) { - res, err := fn(arg) - if err != nil || res != expected { - t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err) - } -} - -func assertError(t *testing.T, fn parseFn, arg string) { - res, err := fn(arg) - if err == nil && res != -1 { - t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit_test.go deleted file mode 100644 index 3e7f10fc2..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package units - -import ( - "fmt" - "strconv" - "testing" -) - -func ExampleParseUlimit() { - fmt.Println(ParseUlimit("nofile=512:1024")) - fmt.Println(ParseUlimit("nofile=1024")) - fmt.Println(ParseUlimit("cpu=2:4")) - fmt.Println(ParseUlimit("cpu=6")) -} - -func TestParseUlimitValid(t *testing.T) { - u1 := &Ulimit{"nofile", 1024, 512} - if u2, _ := ParseUlimit("nofile=512:1024"); *u1 != *u2 { - t.Fatalf("expected %q, but got %q", u1, u2) - } -} - -func TestParseUlimitInvalidLimitType(t *testing.T) { - if _, err := ParseUlimit("notarealtype=1024:1024"); err == nil { - t.Fatalf("expected error on invalid ulimit type") - } -} - -func TestParseUlimitBadFormat(t *testing.T) { - if _, err := ParseUlimit("nofile:1024:1024"); err == nil { - t.Fatal("expected error on bad syntax") - } - - if _, err := ParseUlimit("nofile"); err == nil { - t.Fatal("expected error on bad syntax") - } - - if _, err := ParseUlimit("nofile="); err == nil { - t.Fatal("expected error on bad syntax") - } - if _, err := ParseUlimit("nofile=:"); err == nil { - t.Fatal("expected error on bad syntax") - } - if _, err := ParseUlimit("nofile=:1024"); err == nil { - t.Fatal("expected error on bad syntax") - } -} - -func TestParseUlimitHardLessThanSoft(t *testing.T) { - if _, err := ParseUlimit("nofile=1024:1"); err == nil { - t.Fatal("expected error on hard limit less than soft limit") - } -} - -func TestParseUlimitInvalidValueType(t *testing.T) { - if _, err := ParseUlimit("nofile=asdf"); err == nil { - t.Fatal("expected error on bad value type, but got no error") - } else if _, ok := err.(*strconv.NumError); !ok { - t.Fatalf("expected error on bad value type, but got `%s`", err) - } - - if _, err := ParseUlimit("nofile=1024:asdf"); err == nil { - t.Fatal("expected error on bad value type, but got no error") - } else if _, ok := err.(*strconv.NumError); !ok { - t.Fatalf("expected error on bad value type, but got `%s`", err) - } -} - -func TestUlimitStringOutput(t *testing.T) { - u := &Ulimit{"nofile", 1024, 512} - if s := u.String(); s != "nofile=512:1024" { - t.Fatal("expected String to return nofile=512:1024, but got", s) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md deleted file mode 100644 index c60a31b05..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md +++ /dev/null @@ -1,7 +0,0 @@ -context -======= -[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) - -gorilla/context is a general purpose registry for global request variables. - -Read the full documentation here: http://www.gorillatoolkit.org/pkg/context diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go deleted file mode 100644 index 81cb128b1..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 The Gorilla 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 context - -import ( - "net/http" - "sync" - "time" -) - -var ( - mutex sync.RWMutex - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) -) - -// Set stores a value for a given key in a given request. -func Set(r *http.Request, key, val interface{}) { - mutex.Lock() - if data[r] == nil { - data[r] = make(map[interface{}]interface{}) - datat[r] = time.Now().Unix() - } - data[r][key] = val - mutex.Unlock() -} - -// Get returns a value stored for a given key in a given request. -func Get(r *http.Request, key interface{}) interface{} { - mutex.RLock() - if ctx := data[r]; ctx != nil { - value := ctx[key] - mutex.RUnlock() - return value - } - mutex.RUnlock() - return nil -} - -// GetOk returns stored value and presence state like multi-value return of map access. -func GetOk(r *http.Request, key interface{}) (interface{}, bool) { - mutex.RLock() - if _, ok := data[r]; ok { - value, ok := data[r][key] - mutex.RUnlock() - return value, ok - } - mutex.RUnlock() - return nil, false -} - -// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. -func GetAll(r *http.Request) map[interface{}]interface{} { - mutex.RLock() - if context, ok := data[r]; ok { - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result - } - mutex.RUnlock() - return nil -} - -// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if -// the request was registered. -func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { - mutex.RLock() - context, ok := data[r] - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result, ok -} - -// Delete removes a value stored for a given key in a given request. -func Delete(r *http.Request, key interface{}) { - mutex.Lock() - if data[r] != nil { - delete(data[r], key) - } - mutex.Unlock() -} - -// Clear removes all values stored for a given request. -// -// This is usually called by a handler wrapper to clean up request -// variables at the end of a request lifetime. See ClearHandler(). -func Clear(r *http.Request) { - mutex.Lock() - clear(r) - mutex.Unlock() -} - -// clear is Clear without the lock. -func clear(r *http.Request) { - delete(data, r) - delete(datat, r) -} - -// Purge removes request data stored for longer than maxAge, in seconds. -// It returns the amount of requests removed. -// -// If maxAge <= 0, all request data is removed. -// -// This is only used for sanity check: in case context cleaning was not -// properly set some request data can be kept forever, consuming an increasing -// amount of memory. In case this is detected, Purge() must be called -// periodically until the problem is fixed. -func Purge(maxAge int) int { - mutex.Lock() - count := 0 - if maxAge <= 0 { - count = len(data) - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) - } else { - min := time.Now().Unix() - int64(maxAge) - for r := range data { - if datat[r] < min { - clear(r) - count++ - } - } - } - mutex.Unlock() - return count -} - -// ClearHandler wraps an http.Handler and clears request values at the end -// of a request lifetime. -func ClearHandler(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer Clear(r) - h.ServeHTTP(w, r) - }) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go deleted file mode 100644 index 9814c501e..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2012 The Gorilla 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 context - -import ( - "net/http" - "testing" -) - -type keyType int - -const ( - key1 keyType = iota - key2 -) - -func TestContext(t *testing.T) { - assertEqual := func(val interface{}, exp interface{}) { - if val != exp { - t.Errorf("Expected %v, got %v.", exp, val) - } - } - - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - - // Get() - assertEqual(Get(r, key1), nil) - - // Set() - Set(r, key1, "1") - assertEqual(Get(r, key1), "1") - assertEqual(len(data[r]), 1) - - Set(r, key2, "2") - assertEqual(Get(r, key2), "2") - assertEqual(len(data[r]), 2) - - //GetOk - value, ok := GetOk(r, key1) - assertEqual(value, "1") - assertEqual(ok, true) - - value, ok = GetOk(r, "not exists") - assertEqual(value, nil) - assertEqual(ok, false) - - Set(r, "nil value", nil) - value, ok = GetOk(r, "nil value") - assertEqual(value, nil) - assertEqual(ok, true) - - // GetAll() - values := GetAll(r) - assertEqual(len(values), 3) - - // GetAll() for empty request - values = GetAll(emptyR) - if values != nil { - t.Error("GetAll didn't return nil value for invalid request") - } - - // GetAllOk() - values, ok = GetAllOk(r) - assertEqual(len(values), 3) - assertEqual(ok, true) - - // GetAllOk() for empty request - values, ok = GetAllOk(emptyR) - assertEqual(value, nil) - assertEqual(ok, false) - - // Delete() - Delete(r, key1) - assertEqual(Get(r, key1), nil) - assertEqual(len(data[r]), 2) - - Delete(r, key2) - assertEqual(Get(r, key2), nil) - assertEqual(len(data[r]), 1) - - // Clear() - Clear(r) - assertEqual(len(data), 0) -} - -func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Get(r, key) - } - done <- struct{}{} - -} - -func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Set(r, key, value) - } - done <- struct{}{} - -} - -func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { - - b.StopTimer() - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - done := make(chan struct{}) - b.StartTimer() - - for i := 0; i < b.N; i++ { - wait := make(chan struct{}) - - for i := 0; i < numReaders; i++ { - go parallelReader(r, "test", iterations, wait, done) - } - - for i := 0; i < numWriters; i++ { - go parallelWriter(r, "test", "123", iterations, wait, done) - } - - close(wait) - - for i := 0; i < numReaders+numWriters; i++ { - <-done - } - - } - -} - -func BenchmarkMutexSameReadWrite1(b *testing.B) { - benchmarkMutex(b, 1, 1, 32) -} -func BenchmarkMutexSameReadWrite2(b *testing.B) { - benchmarkMutex(b, 2, 2, 32) -} -func BenchmarkMutexSameReadWrite4(b *testing.B) { - benchmarkMutex(b, 4, 4, 32) -} -func BenchmarkMutex1(b *testing.B) { - benchmarkMutex(b, 2, 8, 32) -} -func BenchmarkMutex2(b *testing.B) { - benchmarkMutex(b, 16, 4, 64) -} -func BenchmarkMutex3(b *testing.B) { - benchmarkMutex(b, 1, 2, 128) -} -func BenchmarkMutex4(b *testing.B) { - benchmarkMutex(b, 128, 32, 256) -} -func BenchmarkMutex5(b *testing.B) { - benchmarkMutex(b, 1024, 2048, 64) -} -func BenchmarkMutex6(b *testing.B) { - benchmarkMutex(b, 2048, 1024, 512) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go deleted file mode 100644 index 73c740031..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2012 The Gorilla 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 context stores values shared during a request lifetime. - -For example, a router can set variables extracted from the URL and later -application handlers can access those values, or it can be used to store -sessions values to be saved at the end of a request. There are several -others common uses. - -The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: - - http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 - -Here's the basic usage: first define the keys that you will need. The key -type is interface{} so a key can be of any type that supports equality. -Here we define a key using a custom int type to avoid name collisions: - - package foo - - import ( - "github.com/gorilla/context" - ) - - type key int - - const MyKey key = 0 - -Then set a variable. Variables are bound to an http.Request object, so you -need a request instance to set a value: - - context.Set(r, MyKey, "bar") - -The application can later access the variable using the same key you provided: - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // val is "bar". - val := context.Get(r, foo.MyKey) - - // returns ("bar", true) - val, ok := context.GetOk(r, foo.MyKey) - // ... - } - -And that's all about the basic usage. We discuss some other ideas below. - -Any type can be stored in the context. To enforce a given type, make the key -private and wrap Get() and Set() to accept and return values of a specific -type: - - type key int - - const mykey key = 0 - - // GetMyKey returns a value for this package from the request values. - func GetMyKey(r *http.Request) SomeType { - if rv := context.Get(r, mykey); rv != nil { - return rv.(SomeType) - } - return nil - } - - // SetMyKey sets a value for this package in the request values. - func SetMyKey(r *http.Request, val SomeType) { - context.Set(r, mykey, val) - } - -Variables must be cleared at the end of a request, to remove all values -that were stored. This can be done in an http.Handler, after a request was -served. Just call Clear() passing the request: - - context.Clear(r) - -...or use ClearHandler(), which conveniently wraps an http.Handler to clear -variables at the end of a request lifetime. - -The Routers from the packages gorilla/mux and gorilla/pat call Clear() -so if you are using either of them you don't need to clear the context manually. -*/ -package context diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md deleted file mode 100644 index b987c9e5d..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md +++ /dev/null @@ -1,240 +0,0 @@ -mux -=== -[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux) -[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux) - -Package `gorilla/mux` implements a request router and dispatcher. - -The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: - -* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. -* URL hosts and paths can have variables with an optional regular expression. -* Registered URLs can be built, or "reversed", which helps maintaining references to resources. -* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. -* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. - -Let's start registering a couple of URL paths and handlers: - -```go -func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) -} -``` - -Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters. - -Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/products/{key}", ProductHandler) -r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) -``` - -The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`: - -```go -vars := mux.Vars(request) -category := vars["category"] -``` - -And this is all you need to know about the basic usage. More advanced options are explained below. - -Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: - -```go -r := mux.NewRouter() -// Only matches if domain is "www.example.com". -r.Host("www.example.com") -// Matches a dynamic subdomain. -r.Host("{subdomain:[a-z]+}.domain.com") -``` - -There are several other matchers that can be added. To match path prefixes: - -```go -r.PathPrefix("/products/") -``` - -...or HTTP methods: - -```go -r.Methods("GET", "POST") -``` - -...or URL schemes: - -```go -r.Schemes("https") -``` - -...or header values: - -```go -r.Headers("X-Requested-With", "XMLHttpRequest") -``` - -...or query values: - -```go -r.Queries("key", "value") -``` - -...or to use a custom matcher function: - -```go -r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 -}) -``` - -...and finally, it is possible to combine several matchers in a single route: - -```go -r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") -``` - -Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". - -For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it: - -```go -r := mux.NewRouter() -s := r.Host("www.example.com").Subrouter() -``` - -Then register routes in the subrouter: - -```go -s.HandleFunc("/products/", ProductsHandler) -s.HandleFunc("/products/{key}", ProductHandler) -s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) -``` - -The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: - -```go -r := mux.NewRouter() -s := r.PathPrefix("/products").Subrouter() -// "/products/" -s.HandleFunc("/", ProductsHandler) -// "/products/{key}/" -s.HandleFunc("/{key}/", ProductHandler) -// "/products/{key}/details" -s.HandleFunc("/{key}/details", ProductDetailsHandler) -``` - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") -``` - -To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: - -```go -url, err := r.Get("article").URL("category", "technology", "id", "42") -``` - -...and the result will be a `url.URL` with the following path: - -``` -"/articles/technology/42" -``` - -This also works for host variables: - -```go -r := mux.NewRouter() -r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - -// url.String() will be "http://news.domain.com/articles/technology/42" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -``` - -All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - -```go -r.HeadersRegexp("Content-Type", "application/(text|json)") -``` - -...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` - -There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do: - -```go -// "http://news.domain.com/" -host, err := r.Get("article").URLHost("subdomain", "news") - -// "/articles/technology/42" -path, err := r.Get("article").URLPath("category", "technology", "id", "42") -``` - -And if you use subrouters, host and path defined separately can be built as well: - -```go -r := mux.NewRouter() -s := r.Host("{subdomain}.domain.com").Subrouter() -s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - -// "http://news.domain.com/articles/technology/42" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -``` - -## Full Example - -Here's a complete, runnable example of a small `mux` based server: - -```go -package main - -import ( - "net/http" - - "github.com/gorilla/mux" -) - -func YourHandler(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Gorilla!\n")) -} - -func main() { - r := mux.NewRouter() - // Routes consist of a path and a handler function. - r.HandleFunc("/", YourHandler) - - // Bind to a port and pass our router in - http.ListenAndServe(":8000", r) -} -``` - -## License - -BSD licensed. See the LICENSE file for details. diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go deleted file mode 100644 index c5f97b2b2..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "net/http" - "testing" -) - -func BenchmarkMux(b *testing.B) { - router := new(Router) - handler := func(w http.ResponseWriter, r *http.Request) {} - router.HandleFunc("/v1/{v1}", handler) - - request, _ := http.NewRequest("GET", "/v1/anything", nil) - for i := 0; i < b.N; i++ { - router.ServeHTTP(nil, request) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go deleted file mode 100644 index 49798cb5c..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright 2012 The Gorilla 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 gorilla/mux implements a request router and dispatcher. - -The name mux stands for "HTTP request multiplexer". Like the standard -http.ServeMux, mux.Router matches incoming requests against a list of -registered routes and calls a handler for the route that matches the URL -or other conditions. The main features are: - - * Requests can be matched based on URL host, path, path prefix, schemes, - header and query values, HTTP methods or using custom matchers. - * URL hosts and paths can have variables with an optional regular - expression. - * Registered URLs can be built, or "reversed", which helps maintaining - references to resources. - * Routes can be used as subrouters: nested routes are only tested if the - parent route matches. This is useful to define groups of routes that - share common conditions like a host, a path prefix or other repeated - attributes. As a bonus, this optimizes request matching. - * It implements the http.Handler interface so it is compatible with the - standard http.ServeMux. - -Let's start registering a couple of URL paths and handlers: - - func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) - } - -Here we register three routes mapping URL paths to handlers. This is -equivalent to how http.HandleFunc() works: if an incoming request URL matches -one of the paths, the corresponding handler is called passing -(http.ResponseWriter, *http.Request) as parameters. - -Paths can have variables. They are defined using the format {name} or -{name:pattern}. If a regular expression pattern is not defined, the matched -variable will be anything until the next slash. For example: - - r := mux.NewRouter() - r.HandleFunc("/products/{key}", ProductHandler) - r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) - -The names are used to create a map of route variables which can be retrieved -calling mux.Vars(): - - vars := mux.Vars(request) - category := vars["category"] - -And this is all you need to know about the basic usage. More advanced options -are explained below. - -Routes can also be restricted to a domain or subdomain. Just define a host -pattern to be matched. They can also have variables: - - r := mux.NewRouter() - // Only matches if domain is "www.example.com". - r.Host("www.example.com") - // Matches a dynamic subdomain. - r.Host("{subdomain:[a-z]+}.domain.com") - -There are several other matchers that can be added. To match path prefixes: - - r.PathPrefix("/products/") - -...or HTTP methods: - - r.Methods("GET", "POST") - -...or URL schemes: - - r.Schemes("https") - -...or header values: - - r.Headers("X-Requested-With", "XMLHttpRequest") - -...or query values: - - r.Queries("key", "value") - -...or to use a custom matcher function: - - r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 - }) - -...and finally, it is possible to combine several matchers in a single route: - - r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") - -Setting the same matching conditions again and again can be boring, so we have -a way to group several routes that share the same requirements. -We call it "subrouting". - -For example, let's say we have several URLs that should only match when the -host is "www.example.com". Create a route for that host and get a "subrouter" -from it: - - r := mux.NewRouter() - s := r.Host("www.example.com").Subrouter() - -Then register routes in the subrouter: - - s.HandleFunc("/products/", ProductsHandler) - s.HandleFunc("/products/{key}", ProductHandler) - s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) - -The three URL paths we registered above will only be tested if the domain is -"www.example.com", because the subrouter is tested first. This is not -only convenient, but also optimizes request matching. You can create -subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define -subrouters in a central place and then parts of the app can register its -paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, -the inner routes use it as base for their paths: - - r := mux.NewRouter() - s := r.PathPrefix("/products").Subrouter() - // "/products/" - s.HandleFunc("/", ProductsHandler) - // "/products/{key}/" - s.HandleFunc("/{key}/", ProductHandler) - // "/products/{key}/details" - s.HandleFunc("/{key}/details", ProductDetailsHandler) - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, -or "reversed". We define a name calling Name() on a route. For example: - - r := mux.NewRouter() - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") - -To build a URL, get the route and call the URL() method, passing a sequence of -key/value pairs for the route variables. For the previous route, we would do: - - url, err := r.Get("article").URL("category", "technology", "id", "42") - -...and the result will be a url.URL with the following path: - - "/articles/technology/42" - -This also works for host variables: - - r := mux.NewRouter() - r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // url.String() will be "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") - -All variables defined in the route are required, and their values must -conform to the corresponding patterns. These requirements guarantee that a -generated URL will always match a registered route -- the only exception is -for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - - r.HeadersRegexp("Content-Type", "application/(text|json)") - -...and the route will match both requests with a Content-Type of `application/json` as well as -`application/text` - -There's also a way to build only the URL host or path for a route: -use the methods URLHost() or URLPath() instead. For the previous route, -we would do: - - // "http://news.domain.com/" - host, err := r.Get("article").URLHost("subdomain", "news") - - // "/articles/technology/42" - path, err := r.Get("article").URLPath("category", "technology", "id", "42") - -And if you use subrouters, host and path defined separately can be built -as well: - - r := mux.NewRouter() - s := r.Host("{subdomain}.domain.com").Subrouter() - s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -*/ -package mux diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go deleted file mode 100644 index cb03ddfe5..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "path" - "regexp" - - "github.com/fsouza/go-dockerclient/external/github.com/gorilla/context" -) - -// NewRouter returns a new router instance. -func NewRouter() *Router { - return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} -} - -// Router registers routes to be matched and dispatches a handler. -// -// It implements the http.Handler interface, so it can be registered to serve -// requests: -// -// var router = mux.NewRouter() -// -// func main() { -// http.Handle("/", router) -// } -// -// Or, for Google App Engine, register it in a init() function: -// -// func init() { -// http.Handle("/", router) -// } -// -// This will send all incoming requests to the router. -type Router struct { - // Configurable Handler to be used when no route matches. - NotFoundHandler http.Handler - // Parent route, if this is a subrouter. - parent parentRoute - // Routes to be matched, in order. - routes []*Route - // Routes by name for URL building. - namedRoutes map[string]*Route - // See Router.StrictSlash(). This defines the flag for new routes. - strictSlash bool - // If true, do not clear the request context after handling the request - KeepContext bool -} - -// Match matches registered routes against the request. -func (r *Router) Match(req *http.Request, match *RouteMatch) bool { - for _, route := range r.routes { - if route.Match(req, match) { - return true - } - } - - // Closest match for a router (includes sub-routers) - if r.NotFoundHandler != nil { - match.Handler = r.NotFoundHandler - return true - } - return false -} - -// ServeHTTP dispatches the handler registered in the matched route. -// -// When there is a match, the route variables can be retrieved calling -// mux.Vars(request). -func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { - // Clean path to canonical form and redirect. - if p := cleanPath(req.URL.Path); p != req.URL.Path { - - // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. - // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: - // http://code.google.com/p/go/issues/detail?id=5252 - url := *req.URL - url.Path = p - p = url.String() - - w.Header().Set("Location", p) - w.WriteHeader(http.StatusMovedPermanently) - return - } - var match RouteMatch - var handler http.Handler - if r.Match(req, &match) { - handler = match.Handler - setVars(req, match.Vars) - setCurrentRoute(req, match.Route) - } - if handler == nil { - handler = http.NotFoundHandler() - } - if !r.KeepContext { - defer context.Clear(req) - } - handler.ServeHTTP(w, req) -} - -// Get returns a route registered with the given name. -func (r *Router) Get(name string) *Route { - return r.getNamedRoutes()[name] -} - -// GetRoute returns a route registered with the given name. This method -// was renamed to Get() and remains here for backwards compatibility. -func (r *Router) GetRoute(name string) *Route { - return r.getNamedRoutes()[name] -} - -// StrictSlash defines the trailing slash behavior for new routes. The initial -// value is false. -// -// When true, if the route path is "/path/", accessing "/path" will redirect -// to the former and vice versa. In other words, your application will always -// see the path as specified in the route. -// -// When false, if the route path is "/path", accessing "/path/" will not match -// this route and vice versa. -// -// Special case: when a route sets a path prefix using the PathPrefix() method, -// strict slash is ignored for that route because the redirect behavior can't -// be determined from a prefix alone. However, any subrouters created from that -// route inherit the original StrictSlash setting. -func (r *Router) StrictSlash(value bool) *Router { - r.strictSlash = value - return r -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// getNamedRoutes returns the map where named routes are registered. -func (r *Router) getNamedRoutes() map[string]*Route { - if r.namedRoutes == nil { - if r.parent != nil { - r.namedRoutes = r.parent.getNamedRoutes() - } else { - r.namedRoutes = make(map[string]*Route) - } - } - return r.namedRoutes -} - -// getRegexpGroup returns regexp definitions from the parent route, if any. -func (r *Router) getRegexpGroup() *routeRegexpGroup { - if r.parent != nil { - return r.parent.getRegexpGroup() - } - return nil -} - -func (r *Router) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// Route factories -// ---------------------------------------------------------------------------- - -// NewRoute registers an empty route. -func (r *Router) NewRoute() *Route { - route := &Route{parent: r, strictSlash: r.strictSlash} - r.routes = append(r.routes, route) - return route -} - -// Handle registers a new route with a matcher for the URL path. -// See Route.Path() and Route.Handler(). -func (r *Router) Handle(path string, handler http.Handler) *Route { - return r.NewRoute().Path(path).Handler(handler) -} - -// HandleFunc registers a new route with a matcher for the URL path. -// See Route.Path() and Route.HandlerFunc(). -func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, - *http.Request)) *Route { - return r.NewRoute().Path(path).HandlerFunc(f) -} - -// Headers registers a new route with a matcher for request header values. -// See Route.Headers(). -func (r *Router) Headers(pairs ...string) *Route { - return r.NewRoute().Headers(pairs...) -} - -// Host registers a new route with a matcher for the URL host. -// See Route.Host(). -func (r *Router) Host(tpl string) *Route { - return r.NewRoute().Host(tpl) -} - -// MatcherFunc registers a new route with a custom matcher function. -// See Route.MatcherFunc(). -func (r *Router) MatcherFunc(f MatcherFunc) *Route { - return r.NewRoute().MatcherFunc(f) -} - -// Methods registers a new route with a matcher for HTTP methods. -// See Route.Methods(). -func (r *Router) Methods(methods ...string) *Route { - return r.NewRoute().Methods(methods...) -} - -// Path registers a new route with a matcher for the URL path. -// See Route.Path(). -func (r *Router) Path(tpl string) *Route { - return r.NewRoute().Path(tpl) -} - -// PathPrefix registers a new route with a matcher for the URL path prefix. -// See Route.PathPrefix(). -func (r *Router) PathPrefix(tpl string) *Route { - return r.NewRoute().PathPrefix(tpl) -} - -// Queries registers a new route with a matcher for URL query values. -// See Route.Queries(). -func (r *Router) Queries(pairs ...string) *Route { - return r.NewRoute().Queries(pairs...) -} - -// Schemes registers a new route with a matcher for URL schemes. -// See Route.Schemes(). -func (r *Router) Schemes(schemes ...string) *Route { - return r.NewRoute().Schemes(schemes...) -} - -// BuildVars registers a new route with a custom function for modifying -// route variables before building a URL. -func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { - return r.NewRoute().BuildVarsFunc(f) -} - -// Walk walks the router and all its sub-routers, calling walkFn for each route -// in the tree. The routes are walked in the order they were added. Sub-routers -// are explored depth-first. -func (r *Router) Walk(walkFn WalkFunc) error { - return r.walk(walkFn, []*Route{}) -} - -// SkipRouter is used as a return value from WalkFuncs to indicate that the -// router that walk is about to descend down to should be skipped. -var SkipRouter = errors.New("skip this router") - -// WalkFunc is the type of the function called for each route visited by Walk. -// At every invocation, it is given the current route, and the current router, -// and a list of ancestor routes that lead to the current route. -type WalkFunc func(route *Route, router *Router, ancestors []*Route) error - -func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { - for _, t := range r.routes { - if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" { - continue - } - - err := walkFn(t, r, ancestors) - if err == SkipRouter { - continue - } - for _, sr := range t.matchers { - if h, ok := sr.(*Router); ok { - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - } - } - if h, ok := t.handler.(*Router); ok { - ancestors = append(ancestors, t) - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - ancestors = ancestors[:len(ancestors)-1] - } - } - return nil -} - -// ---------------------------------------------------------------------------- -// Context -// ---------------------------------------------------------------------------- - -// RouteMatch stores information about a matched route. -type RouteMatch struct { - Route *Route - Handler http.Handler - Vars map[string]string -} - -type contextKey int - -const ( - varsKey contextKey = iota - routeKey -) - -// Vars returns the route variables for the current request, if any. -func Vars(r *http.Request) map[string]string { - if rv := context.Get(r, varsKey); rv != nil { - return rv.(map[string]string) - } - return nil -} - -// CurrentRoute returns the matched route for the current request, if any. -// This only works when called inside the handler of the matched route -// because the matched route is stored in the request context which is cleared -// after the handler returns, unless the KeepContext option is set on the -// Router. -func CurrentRoute(r *http.Request) *Route { - if rv := context.Get(r, routeKey); rv != nil { - return rv.(*Route) - } - return nil -} - -func setVars(r *http.Request, val interface{}) { - if val != nil { - context.Set(r, varsKey, val) - } -} - -func setCurrentRoute(r *http.Request, val interface{}) { - if val != nil { - context.Set(r, routeKey, val) - } -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -// cleanPath returns the canonical path for p, eliminating . and .. elements. -// Borrowed from the net/http package. -func cleanPath(p string) string { - if p == "" { - return "/" - } - if p[0] != '/' { - p = "/" + p - } - np := path.Clean(p) - // path.Clean removes trailing slash except for root; - // put the trailing slash back if necessary. - if p[len(p)-1] == '/' && np != "/" { - np += "/" - } - return np -} - -// uniqueVars returns an error if two slices contain duplicated strings. -func uniqueVars(s1, s2 []string) error { - for _, v1 := range s1 { - for _, v2 := range s2 { - if v1 == v2 { - return fmt.Errorf("mux: duplicated route variable %q", v2) - } - } - } - return nil -} - -// checkPairs returns the count of strings passed in, and an error if -// the count is not an even number. -func checkPairs(pairs ...string) (int, error) { - length := len(pairs) - if length%2 != 0 { - return length, fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - } - return length, nil -} - -// mapFromPairsToString converts variadic string parameters to a -// string to string map. -func mapFromPairsToString(pairs ...string) (map[string]string, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]string, length/2) - for i := 0; i < length; i += 2 { - m[pairs[i]] = pairs[i+1] - } - return m, nil -} - -// mapFromPairsToRegex converts variadic string paramers to a -// string to regex map. -func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]*regexp.Regexp, length/2) - for i := 0; i < length; i += 2 { - regex, err := regexp.Compile(pairs[i+1]) - if err != nil { - return nil, err - } - m[pairs[i]] = regex - } - return m, nil -} - -// matchInArray returns true if the given string value is in the array. -func matchInArray(arr []string, value string) bool { - for _, v := range arr { - if v == value { - return true - } - } - return false -} - -// matchMapWithString returns true if the given key/value pairs exist in a given map. -func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != "" { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v == value { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} - -// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against -// the given regex -func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != nil { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v.MatchString(value) { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go deleted file mode 100644 index 98f73fe9c..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go +++ /dev/null @@ -1,1358 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "fmt" - "net/http" - "strings" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/gorilla/context" -) - -func (r *Route) GoString() string { - matchers := make([]string, len(r.matchers)) - for i, m := range r.matchers { - matchers[i] = fmt.Sprintf("%#v", m) - } - return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", ")) -} - -func (r *routeRegexp) GoString() string { - return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR) -} - -type routeTest struct { - title string // title of the test - route *Route // the route being tested - request *http.Request // a request to test the route - vars map[string]string // the expected vars of the match - host string // the expected host of the match - path string // the expected path of the match - shouldMatch bool // whether the request is expected to match the route at all - shouldRedirect bool // whether the request should result in a redirect -} - -func TestHost(t *testing.T) { - // newRequestHost a new request with a method, url, and host header - newRequestHost := func(method, url, host string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - req.Host = host - return req - } - - tests := []routeTest{ - { - title: "Host route match", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route, wrong host in request URL", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with port, match", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: true, - }, - { - title: "Host route with port, wrong port in request URL", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: false, - }, - { - title: "Host route, match with host in request header", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route, wrong host in request header", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true}, - { - title: "Host route with port, wrong host in request header", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: false, - }, - { - title: "Host route with pattern, match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with pattern, additional capturing group, match", - route: new(Route).Host("aaa.{v1:[a-z]{2}(b|c)}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with pattern, wrong host in request URL", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with multiple patterns, match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with multiple patterns, wrong host in request URL", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with hyphenated name and pattern, match", - route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v-1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with hyphenated name and pattern, additional capturing group, match", - route: new(Route).Host("aaa.{v-1:[a-z]{2}(b|c)}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v-1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with multiple hyphenated names and patterns, match", - route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Path route with single pattern with pipe, match", - route: new(Route).Path("/{category:a|b/c}"), - request: newRequest("GET", "http://localhost/a"), - vars: map[string]string{"category": "a"}, - host: "", - path: "/a", - shouldMatch: true, - }, - { - title: "Path route with single pattern with pipe, match", - route: new(Route).Path("/{category:a|b/c}"), - request: newRequest("GET", "http://localhost/b/c"), - vars: map[string]string{"category": "b/c"}, - host: "", - path: "/b/c", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns with pipe, match", - route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), - request: newRequest("GET", "http://localhost/a/product_name/1"), - vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, - host: "", - path: "/a/product_name/1", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns with pipe, match", - route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), - request: newRequest("GET", "http://localhost/b/c/product_name/1"), - vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"}, - host: "", - path: "/b/c/product_name/1", - shouldMatch: true, - }, - } - for _, test := range tests { - testRoute(t, test) - } -} - -func TestPath(t *testing.T) { - tests := []routeTest{ - { - title: "Path route, match", - route: new(Route).Path("/111/222/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route, match with trailing slash in request and path", - route: new(Route).Path("/111/"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - }, - { - title: "Path route, do not match with trailing slash in path", - route: new(Route).Path("/111/"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: false, - }, - { - title: "Path route, do not match with trailing slash in request", - route: new(Route).Path("/111"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: false, - }, - { - title: "Path route, wrong path in request in request URL", - route: new(Route).Path("/111/222/333"), - request: newRequest("GET", "http://localhost/1/2/3"), - vars: map[string]string{}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with pattern, match", - route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with pattern, URL in request does not match", - route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with multiple patterns, match", - route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns, URL in request does not match", - route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with multiple patterns with pipe, match", - route: new(Route).Path("/{category:a|(b/c)}/{product}/{id:[0-9]+}"), - request: newRequest("GET", "http://localhost/a/product_name/1"), - vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, - host: "", - path: "/a/product_name/1", - shouldMatch: true, - }, - { - title: "Path route with hyphenated name and pattern, match", - route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v-1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with multiple hyphenated names and patterns, match", - route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with multiple hyphenated names and patterns with pipe, match", - route: new(Route).Path("/{product-category:a|(b/c)}/{product-name}/{product-id:[0-9]+}"), - request: newRequest("GET", "http://localhost/a/product_name/1"), - vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"}, - host: "", - path: "/a/product_name/1", - shouldMatch: true, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestPathPrefix(t *testing.T) { - tests := []routeTest{ - { - title: "PathPrefix route, match", - route: new(Route).PathPrefix("/111"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - }, - { - title: "PathPrefix route, match substring", - route: new(Route).PathPrefix("/1"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/1", - shouldMatch: true, - }, - { - title: "PathPrefix route, URL prefix in request does not match", - route: new(Route).PathPrefix("/111"), - request: newRequest("GET", "http://localhost/1/2/3"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: false, - }, - { - title: "PathPrefix route with pattern, match", - route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222", - shouldMatch: true, - }, - { - title: "PathPrefix route with pattern, URL prefix in request does not match", - route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222", - shouldMatch: false, - }, - { - title: "PathPrefix route with multiple patterns, match", - route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "111", "v2": "222"}, - host: "", - path: "/111/222", - shouldMatch: true, - }, - { - title: "PathPrefix route with multiple patterns, URL prefix in request does not match", - route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "111", "v2": "222"}, - host: "", - path: "/111/222", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestHostPath(t *testing.T) { - tests := []routeTest{ - { - title: "Host and Path route, match", - route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Host and Path route, wrong host in request URL", - route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Host and Path route with pattern, match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb", "v2": "222"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Host and Path route with pattern, URL in request does not match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb", "v2": "222"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Host and Path route with multiple patterns, match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Host and Path route with multiple patterns, URL in request does not match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestHeaders(t *testing.T) { - // newRequestHeaders creates a new request with a method, url, and headers - newRequestHeaders := func(method, url string, headers map[string]string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - for k, v := range headers { - req.Header.Add(k, v) - } - return req - } - - tests := []routeTest{ - { - title: "Headers route, match", - route: new(Route).Headers("foo", "bar", "baz", "ding"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Headers route, bad header values", - route: new(Route).Headers("foo", "bar", "baz", "ding"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Headers route, regex header values to match", - route: new(Route).Headers("foo", "ba[zr]"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Headers route, regex header values to match", - route: new(Route).HeadersRegexp("foo", "ba[zr]"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - } - - for _, test := range tests { - testRoute(t, test) - } - -} - -func TestMethods(t *testing.T) { - tests := []routeTest{ - { - title: "Methods route, match GET", - route: new(Route).Methods("GET", "POST"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Methods route, match POST", - route: new(Route).Methods("GET", "POST"), - request: newRequest("POST", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Methods route, bad method", - route: new(Route).Methods("GET", "POST"), - request: newRequest("PUT", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestQueries(t *testing.T) { - tests := []routeTest{ - { - title: "Queries route, match", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, match with a query string", - route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, match with a query string out of order", - route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, bad query", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?foo=bar&baz=dong"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with pattern, match", - route: new(Route).Queries("foo", "{v1}"), - request: newRequest("GET", "http://localhost?foo=bar"), - vars: map[string]string{"v1": "bar"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with multiple patterns, match", - route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern, match", - route: new(Route).Queries("foo", "{v1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=10"), - vars: map[string]string{"v1": "10"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern, regexp does not match", - route: new(Route).Queries("foo", "{v1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=a"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with regexp pattern with quantifier, match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?foo=1"), - vars: map[string]string{"v1": "1"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern with quantifier, additional variable in query string, match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?bar=2&foo=1"), - vars: map[string]string{"v1": "1"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern with quantifier, regexp does not match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?foo=12"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with regexp pattern with quantifier, additional capturing group", - route: new(Route).Queries("foo", "{v1:[0-9]{1}(a|b)}"), - request: newRequest("GET", "http://localhost?foo=1a"), - vars: map[string]string{"v1": "1a"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?foo=12"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with hyphenated name, match", - route: new(Route).Queries("foo", "{v-1}"), - request: newRequest("GET", "http://localhost?foo=bar"), - vars: map[string]string{"v-1": "bar"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with multiple hyphenated names, match", - route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{"v-1": "bar", "v-2": "ding"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with hyphenate name and pattern, match", - route: new(Route).Queries("foo", "{v-1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=10"), - vars: map[string]string{"v-1": "10"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group", - route: new(Route).Queries("foo", "{v-1:[0-9]{1}(a|b)}"), - request: newRequest("GET", "http://localhost?foo=1a"), - vars: map[string]string{"v-1": "1a"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with empty value, should match", - route: new(Route).Queries("foo", ""), - request: newRequest("GET", "http://localhost?foo=bar"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with empty value and no parameter in request, should not match", - route: new(Route).Queries("foo", ""), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with empty value and empty parameter in request, should match", - route: new(Route).Queries("foo", ""), - request: newRequest("GET", "http://localhost?foo="), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with overlapping value, should not match", - route: new(Route).Queries("foo", "bar"), - request: newRequest("GET", "http://localhost?foo=barfoo"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with no parameter in request, should not match", - route: new(Route).Queries("foo", "{bar}"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with empty parameter in request, should match", - route: new(Route).Queries("foo", "{bar}"), - request: newRequest("GET", "http://localhost?foo="), - vars: map[string]string{"foo": ""}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, bad submatch", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestSchemes(t *testing.T) { - tests := []routeTest{ - // Schemes - { - title: "Schemes route, match https", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "https://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Schemes route, match ftp", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "ftp://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Schemes route, bad scheme", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - for _, test := range tests { - testRoute(t, test) - } -} - -func TestMatcherFunc(t *testing.T) { - m := func(r *http.Request, m *RouteMatch) bool { - if r.URL.Host == "aaa.bbb.ccc" { - return true - } - return false - } - - tests := []routeTest{ - { - title: "MatchFunc route, match", - route: new(Route).MatcherFunc(m), - request: newRequest("GET", "http://aaa.bbb.ccc"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "MatchFunc route, non-match", - route: new(Route).MatcherFunc(m), - request: newRequest("GET", "http://aaa.222.ccc"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestBuildVarsFunc(t *testing.T) { - tests := []routeTest{ - { - title: "BuildVarsFunc set on route", - route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v1"] = "3" - vars["v2"] = "a" - return vars - }), - request: newRequest("GET", "http://localhost/111/2"), - path: "/111/3a", - shouldMatch: true, - }, - { - title: "BuildVarsFunc set on route and parent route", - route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v1"] = "2" - return vars - }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v2"] = "b" - return vars - }), - request: newRequest("GET", "http://localhost/1/a"), - path: "/2/b", - shouldMatch: true, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestSubRouter(t *testing.T) { - subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter() - subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter() - - tests := []routeTest{ - { - route: subrouter1.Path("/{v2:[a-z]+}"), - request: newRequest("GET", "http://aaa.google.com/bbb"), - vars: map[string]string{"v1": "aaa", "v2": "bbb"}, - host: "aaa.google.com", - path: "/bbb", - shouldMatch: true, - }, - { - route: subrouter1.Path("/{v2:[a-z]+}"), - request: newRequest("GET", "http://111.google.com/111"), - vars: map[string]string{"v1": "aaa", "v2": "bbb"}, - host: "aaa.google.com", - path: "/bbb", - shouldMatch: false, - }, - { - route: subrouter2.Path("/baz/{v2}"), - request: newRequest("GET", "http://localhost/foo/bar/baz/ding"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "/foo/bar/baz/ding", - shouldMatch: true, - }, - { - route: subrouter2.Path("/baz/{v2}"), - request: newRequest("GET", "http://localhost/foo/bar"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "/foo/bar/baz/ding", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestNamedRoutes(t *testing.T) { - r1 := NewRouter() - r1.NewRoute().Name("a") - r1.NewRoute().Name("b") - r1.NewRoute().Name("c") - - r2 := r1.NewRoute().Subrouter() - r2.NewRoute().Name("d") - r2.NewRoute().Name("e") - r2.NewRoute().Name("f") - - r3 := r2.NewRoute().Subrouter() - r3.NewRoute().Name("g") - r3.NewRoute().Name("h") - r3.NewRoute().Name("i") - - if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 { - t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes) - } else if r1.Get("i") == nil { - t.Errorf("Subroute name not registered") - } -} - -func TestStrictSlash(t *testing.T) { - r := NewRouter() - r.StrictSlash(true) - - tests := []routeTest{ - { - title: "Redirect path without slash", - route: r.NewRoute().Path("/111/"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Do not redirect path with slash", - route: r.NewRoute().Path("/111/"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - shouldRedirect: false, - }, - { - title: "Redirect path with slash", - route: r.NewRoute().Path("/111"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Do not redirect path without slash", - route: r.NewRoute().Path("/111"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - shouldRedirect: false, - }, - { - title: "Propagate StrictSlash to subrouters", - route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"), - request: newRequest("GET", "http://localhost/static/images"), - vars: map[string]string{}, - host: "", - path: "/static/images/", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Ignore StrictSlash for path prefix", - route: r.NewRoute().PathPrefix("/static/"), - request: newRequest("GET", "http://localhost/static/logo.png"), - vars: map[string]string{}, - host: "", - path: "/static/", - shouldMatch: true, - shouldRedirect: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestWalkSingleDepth(t *testing.T) { - r0 := NewRouter() - r1 := NewRouter() - r2 := NewRouter() - - r0.Path("/g") - r0.Path("/o") - r0.Path("/d").Handler(r1) - r0.Path("/r").Handler(r2) - r0.Path("/a") - - r1.Path("/z") - r1.Path("/i") - r1.Path("/l") - r1.Path("/l") - - r2.Path("/i") - r2.Path("/l") - r2.Path("/l") - - paths := []string{"g", "o", "r", "i", "l", "l", "a"} - depths := []int{0, 0, 0, 1, 1, 1, 0} - i := 0 - err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error { - matcher := route.matchers[0].(*routeRegexp) - if matcher.template == "/d" { - return SkipRouter - } - if len(ancestors) != depths[i] { - t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors)) - } - if matcher.template != "/"+paths[i] { - t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template) - } - i++ - return nil - }) - if err != nil { - panic(err) - } - if i != len(paths) { - t.Errorf("Expected %d routes, found %d", len(paths), i) - } -} - -func TestWalkNested(t *testing.T) { - router := NewRouter() - - g := router.Path("/g").Subrouter() - o := g.PathPrefix("/o").Subrouter() - r := o.PathPrefix("/r").Subrouter() - i := r.PathPrefix("/i").Subrouter() - l1 := i.PathPrefix("/l").Subrouter() - l2 := l1.PathPrefix("/l").Subrouter() - l2.Path("/a") - - paths := []string{"/g", "/g/o", "/g/o/r", "/g/o/r/i", "/g/o/r/i/l", "/g/o/r/i/l/l", "/g/o/r/i/l/l/a"} - idx := 0 - err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { - path := paths[idx] - tpl := route.regexp.path.template - if tpl != path { - t.Errorf(`Expected %s got %s`, path, tpl) - } - idx++ - return nil - }) - if err != nil { - panic(err) - } - if idx != len(paths) { - t.Errorf("Expected %d routes, found %d", len(paths), idx) - } -} - -func TestSubrouterErrorHandling(t *testing.T) { - superRouterCalled := false - subRouterCalled := false - - router := NewRouter() - router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - superRouterCalled = true - }) - subRouter := router.PathPrefix("/bign8").Subrouter() - subRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - subRouterCalled = true - }) - - req, _ := http.NewRequest("GET", "http://localhost/bign8/was/here", nil) - router.ServeHTTP(NewRecorder(), req) - - if superRouterCalled { - t.Error("Super router 404 handler called when sub-router 404 handler is available.") - } - if !subRouterCalled { - t.Error("Sub-router 404 handler was not called.") - } -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -func getRouteTemplate(route *Route) string { - host, path := "none", "none" - if route.regexp != nil { - if route.regexp.host != nil { - host = route.regexp.host.template - } - if route.regexp.path != nil { - path = route.regexp.path.template - } - } - return fmt.Sprintf("Host: %v, Path: %v", host, path) -} - -func testRoute(t *testing.T, test routeTest) { - request := test.request - route := test.route - vars := test.vars - shouldMatch := test.shouldMatch - host := test.host - path := test.path - url := test.host + test.path - shouldRedirect := test.shouldRedirect - - var match RouteMatch - ok := route.Match(request, &match) - if ok != shouldMatch { - msg := "Should match" - if !shouldMatch { - msg = "Should not match" - } - t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars) - return - } - if shouldMatch { - if test.vars != nil && !stringMapEqual(test.vars, match.Vars) { - t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars) - return - } - if host != "" { - u, _ := test.route.URLHost(mapToPairs(match.Vars)...) - if host != u.Host { - t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route)) - return - } - } - if path != "" { - u, _ := route.URLPath(mapToPairs(match.Vars)...) - if path != u.Path { - t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route)) - return - } - } - if url != "" { - u, _ := route.URL(mapToPairs(match.Vars)...) - if url != u.Host+u.Path { - t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route)) - return - } - } - if shouldRedirect && match.Handler == nil { - t.Errorf("(%v) Did not redirect", test.title) - return - } - if !shouldRedirect && match.Handler != nil { - t.Errorf("(%v) Unexpected redirect", test.title) - return - } - } -} - -// Tests that the context is cleared or not cleared properly depending on -// the configuration of the router -func TestKeepContext(t *testing.T) { - func1 := func(w http.ResponseWriter, r *http.Request) {} - - r := NewRouter() - r.HandleFunc("/", func1).Name("func1") - - req, _ := http.NewRequest("GET", "http://localhost/", nil) - context.Set(req, "t", 1) - - res := new(http.ResponseWriter) - r.ServeHTTP(*res, req) - - if _, ok := context.GetOk(req, "t"); ok { - t.Error("Context should have been cleared at end of request") - } - - r.KeepContext = true - - req, _ = http.NewRequest("GET", "http://localhost/", nil) - context.Set(req, "t", 1) - - r.ServeHTTP(*res, req) - if _, ok := context.GetOk(req, "t"); !ok { - t.Error("Context should NOT have been cleared at end of request") - } - -} - -type TestA301ResponseWriter struct { - hh http.Header - status int -} - -func (ho TestA301ResponseWriter) Header() http.Header { - return http.Header(ho.hh) -} - -func (ho TestA301ResponseWriter) Write(b []byte) (int, error) { - return 0, nil -} - -func (ho TestA301ResponseWriter) WriteHeader(code int) { - ho.status = code -} - -func Test301Redirect(t *testing.T) { - m := make(http.Header) - - func1 := func(w http.ResponseWriter, r *http.Request) {} - func2 := func(w http.ResponseWriter, r *http.Request) {} - - r := NewRouter() - r.HandleFunc("/api/", func2).Name("func2") - r.HandleFunc("/", func1).Name("func1") - - req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) - - res := TestA301ResponseWriter{ - hh: m, - status: 0, - } - r.ServeHTTP(&res, req) - - if "http://localhost/api/?abc=def" != res.hh["Location"][0] { - t.Errorf("Should have complete URL with query string") - } -} - -// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW -func TestSubrouterHeader(t *testing.T) { - expected := "func1 response" - func1 := func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, expected) - } - func2 := func(http.ResponseWriter, *http.Request) {} - - r := NewRouter() - s := r.Headers("SomeSpecialHeader", "").Subrouter() - s.HandleFunc("/", func1).Name("func1") - r.HandleFunc("/", func2).Name("func2") - - req, _ := http.NewRequest("GET", "http://localhost/", nil) - req.Header.Add("SomeSpecialHeader", "foo") - match := new(RouteMatch) - matched := r.Match(req, match) - if !matched { - t.Errorf("Should match request") - } - if match.Route.GetName() != "func1" { - t.Errorf("Expecting func1 handler, got %s", match.Route.GetName()) - } - resp := NewRecorder() - match.Handler.ServeHTTP(resp, req) - if resp.Body.String() != expected { - t.Errorf("Expecting %q", expected) - } -} - -// mapToPairs converts a string map to a slice of string pairs -func mapToPairs(m map[string]string) []string { - var i int - p := make([]string, len(m)*2) - for k, v := range m { - p[i] = k - p[i+1] = v - i += 2 - } - return p -} - -// stringMapEqual checks the equality of two string maps -func stringMapEqual(m1, m2 map[string]string) bool { - nil1 := m1 == nil - nil2 := m2 == nil - if nil1 != nil2 || len(m1) != len(m2) { - return false - } - for k, v := range m1 { - if v != m2[k] { - return false - } - } - return true -} - -// newRequest is a helper function to create a new request with a method and url -func newRequest(method, url string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - return req -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go deleted file mode 100644 index 755db483e..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go +++ /dev/null @@ -1,714 +0,0 @@ -// Old tests ported to Go1. This is a mess. Want to drop it one day. - -// Copyright 2011 Gorilla 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 mux - -import ( - "bytes" - "net/http" - "testing" -) - -// ---------------------------------------------------------------------------- -// ResponseRecorder -// ---------------------------------------------------------------------------- -// 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. - -// ResponseRecorder is an implementation of http.ResponseWriter that -// records its mutations for later inspection in tests. -type ResponseRecorder struct { - Code int // the HTTP response code from WriteHeader - HeaderMap http.Header // the HTTP response headers - Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to - Flushed bool -} - -// NewRecorder returns an initialized ResponseRecorder. -func NewRecorder() *ResponseRecorder { - return &ResponseRecorder{ - HeaderMap: make(http.Header), - Body: new(bytes.Buffer), - } -} - -// DefaultRemoteAddr is the default remote address to return in RemoteAddr if -// an explicit DefaultRemoteAddr isn't set on ResponseRecorder. -const DefaultRemoteAddr = "1.2.3.4" - -// Header returns the response headers. -func (rw *ResponseRecorder) Header() http.Header { - return rw.HeaderMap -} - -// Write always succeeds and writes to rw.Body, if not nil. -func (rw *ResponseRecorder) Write(buf []byte) (int, error) { - if rw.Body != nil { - rw.Body.Write(buf) - } - if rw.Code == 0 { - rw.Code = http.StatusOK - } - return len(buf), nil -} - -// WriteHeader sets rw.Code. -func (rw *ResponseRecorder) WriteHeader(code int) { - rw.Code = code -} - -// Flush sets rw.Flushed to true. -func (rw *ResponseRecorder) Flush() { - rw.Flushed = true -} - -// ---------------------------------------------------------------------------- - -func TestRouteMatchers(t *testing.T) { - var scheme, host, path, query, method string - var headers map[string]string - var resultVars map[bool]map[string]string - - router := NewRouter() - router.NewRoute().Host("{var1}.google.com"). - Path("/{var2:[a-z]+}/{var3:[0-9]+}"). - Queries("foo", "bar"). - Methods("GET"). - Schemes("https"). - Headers("x-requested-with", "XMLHttpRequest") - router.NewRoute().Host("www.{var4}.com"). - PathPrefix("/foo/{var5:[a-z]+}/{var6:[0-9]+}"). - Queries("baz", "ding"). - Methods("POST"). - Schemes("http"). - Headers("Content-Type", "application/json") - - reset := func() { - // Everything match. - scheme = "https" - host = "www.google.com" - path = "/product/42" - query = "?foo=bar" - method = "GET" - headers = map[string]string{"X-Requested-With": "XMLHttpRequest"} - resultVars = map[bool]map[string]string{ - true: {"var1": "www", "var2": "product", "var3": "42"}, - false: {}, - } - } - - reset2 := func() { - // Everything match. - scheme = "http" - host = "www.google.com" - path = "/foo/product/42/path/that/is/ignored" - query = "?baz=ding" - method = "POST" - headers = map[string]string{"Content-Type": "application/json"} - resultVars = map[bool]map[string]string{ - true: {"var4": "google", "var5": "product", "var6": "42"}, - false: {}, - } - } - - match := func(shouldMatch bool) { - url := scheme + "://" + host + path + query - request, _ := http.NewRequest(method, url, nil) - for key, value := range headers { - request.Header.Add(key, value) - } - - var routeMatch RouteMatch - matched := router.Match(request, &routeMatch) - if matched != shouldMatch { - // Need better messages. :) - if matched { - t.Errorf("Should match.") - } else { - t.Errorf("Should not match.") - } - } - - if matched { - currentRoute := routeMatch.Route - if currentRoute == nil { - t.Errorf("Expected a current route.") - } - vars := routeMatch.Vars - expectedVars := resultVars[shouldMatch] - if len(vars) != len(expectedVars) { - t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) - } - for name, value := range vars { - if expectedVars[name] != value { - t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) - } - } - } - } - - // 1st route -------------------------------------------------------------- - - // Everything match. - reset() - match(true) - - // Scheme doesn't match. - reset() - scheme = "http" - match(false) - - // Host doesn't match. - reset() - host = "www.mygoogle.com" - match(false) - - // Path doesn't match. - reset() - path = "/product/notdigits" - match(false) - - // Query doesn't match. - reset() - query = "?foo=baz" - match(false) - - // Method doesn't match. - reset() - method = "POST" - match(false) - - // Header doesn't match. - reset() - headers = map[string]string{} - match(false) - - // Everything match, again. - reset() - match(true) - - // 2nd route -------------------------------------------------------------- - - // Everything match. - reset2() - match(true) - - // Scheme doesn't match. - reset2() - scheme = "https" - match(false) - - // Host doesn't match. - reset2() - host = "sub.google.com" - match(false) - - // Path doesn't match. - reset2() - path = "/bar/product/42" - match(false) - - // Query doesn't match. - reset2() - query = "?foo=baz" - match(false) - - // Method doesn't match. - reset2() - method = "GET" - match(false) - - // Header doesn't match. - reset2() - headers = map[string]string{} - match(false) - - // Everything match, again. - reset2() - match(true) -} - -type headerMatcherTest struct { - matcher headerMatcher - headers map[string]string - result bool -} - -var headerMatcherTests = []headerMatcherTest{ - { - matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), - headers: map[string]string{"X-Requested-With": "XMLHttpRequest"}, - result: true, - }, - { - matcher: headerMatcher(map[string]string{"x-requested-with": ""}), - headers: map[string]string{"X-Requested-With": "anything"}, - result: true, - }, - { - matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), - headers: map[string]string{}, - result: false, - }, -} - -type hostMatcherTest struct { - matcher *Route - url string - vars map[string]string - result bool -} - -var hostMatcherTests = []hostMatcherTest{ - { - matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), - url: "http://abc.def.ghi/", - vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, - result: true, - }, - { - matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), - url: "http://a.b.c/", - vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, - result: false, - }, -} - -type methodMatcherTest struct { - matcher methodMatcher - method string - result bool -} - -var methodMatcherTests = []methodMatcherTest{ - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "GET", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "POST", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "PUT", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "DELETE", - result: false, - }, -} - -type pathMatcherTest struct { - matcher *Route - url string - vars map[string]string - result bool -} - -var pathMatcherTests = []pathMatcherTest{ - { - matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), - url: "http://localhost:8080/123/456/789", - vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, - result: true, - }, - { - matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), - url: "http://localhost:8080/1/2/3", - vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, - result: false, - }, -} - -type schemeMatcherTest struct { - matcher schemeMatcher - url string - result bool -} - -var schemeMatcherTests = []schemeMatcherTest{ - { - matcher: schemeMatcher([]string{"http", "https"}), - url: "http://localhost:8080/", - result: true, - }, - { - matcher: schemeMatcher([]string{"http", "https"}), - url: "https://localhost:8080/", - result: true, - }, - { - matcher: schemeMatcher([]string{"https"}), - url: "http://localhost:8080/", - result: false, - }, - { - matcher: schemeMatcher([]string{"http"}), - url: "https://localhost:8080/", - result: false, - }, -} - -type urlBuildingTest struct { - route *Route - vars []string - url string -} - -var urlBuildingTests = []urlBuildingTest{ - { - route: new(Route).Host("foo.domain.com"), - vars: []string{}, - url: "http://foo.domain.com", - }, - { - route: new(Route).Host("{subdomain}.domain.com"), - vars: []string{"subdomain", "bar"}, - url: "http://bar.domain.com", - }, - { - route: new(Route).Host("foo.domain.com").Path("/articles"), - vars: []string{}, - url: "http://foo.domain.com/articles", - }, - { - route: new(Route).Path("/articles"), - vars: []string{}, - url: "/articles", - }, - { - route: new(Route).Path("/articles/{category}/{id:[0-9]+}"), - vars: []string{"category", "technology", "id", "42"}, - url: "/articles/technology/42", - }, - { - route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"), - vars: []string{"subdomain", "foo", "category", "technology", "id", "42"}, - url: "http://foo.domain.com/articles/technology/42", - }, -} - -func TestHeaderMatcher(t *testing.T) { - for _, v := range headerMatcherTests { - request, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - for key, value := range v.headers { - request.Header.Add(key, value) - } - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, request.Header) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, request.Header) - } - } - } -} - -func TestHostMatcher(t *testing.T) { - for _, v := range hostMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - vars := routeMatch.Vars - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - if result { - if len(vars) != len(v.vars) { - t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) - } - for name, value := range vars { - if v.vars[name] != value { - t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) - } - } - } else { - if len(vars) != 0 { - t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) - } - } - } -} - -func TestMethodMatcher(t *testing.T) { - for _, v := range methodMatcherTests { - request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.method) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.method) - } - } - } -} - -func TestPathMatcher(t *testing.T) { - for _, v := range pathMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - vars := routeMatch.Vars - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - if result { - if len(vars) != len(v.vars) { - t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) - } - for name, value := range vars { - if v.vars[name] != value { - t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) - } - } - } else { - if len(vars) != 0 { - t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) - } - } - } -} - -func TestSchemeMatcher(t *testing.T) { - for _, v := range schemeMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - } -} - -func TestUrlBuilding(t *testing.T) { - - for _, v := range urlBuildingTests { - u, _ := v.route.URL(v.vars...) - url := u.String() - if url != v.url { - t.Errorf("expected %v, got %v", v.url, url) - /* - reversePath := "" - reverseHost := "" - if v.route.pathTemplate != nil { - reversePath = v.route.pathTemplate.Reverse - } - if v.route.hostTemplate != nil { - reverseHost = v.route.hostTemplate.Reverse - } - - t.Errorf("%#v:\nexpected: %q\ngot: %q\nreverse path: %q\nreverse host: %q", v.route, v.url, url, reversePath, reverseHost) - */ - } - } - - ArticleHandler := func(w http.ResponseWriter, r *http.Request) { - } - - router := NewRouter() - router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article") - - url, _ := router.Get("article").URL("category", "technology", "id", "42") - expected := "/articles/technology/42" - if url.String() != expected { - t.Errorf("Expected %v, got %v", expected, url.String()) - } -} - -func TestMatchedRouteName(t *testing.T) { - routeName := "stock" - router := NewRouter() - route := router.NewRoute().Path("/products/").Name(routeName) - - url := "http://www.example.com/products/" - request, _ := http.NewRequest("GET", url, nil) - var rv RouteMatch - ok := router.Match(request, &rv) - - if !ok || rv.Route != route { - t.Errorf("Expected same route, got %+v.", rv.Route) - } - - retName := rv.Route.GetName() - if retName != routeName { - t.Errorf("Expected %q, got %q.", routeName, retName) - } -} - -func TestSubRouting(t *testing.T) { - // Example from docs. - router := NewRouter() - subrouter := router.NewRoute().Host("www.example.com").Subrouter() - route := subrouter.NewRoute().Path("/products/").Name("products") - - url := "http://www.example.com/products/" - request, _ := http.NewRequest("GET", url, nil) - var rv RouteMatch - ok := router.Match(request, &rv) - - if !ok || rv.Route != route { - t.Errorf("Expected same route, got %+v.", rv.Route) - } - - u, _ := router.Get("products").URL() - builtUrl := u.String() - // Yay, subroute aware of the domain when building! - if builtUrl != url { - t.Errorf("Expected %q, got %q.", url, builtUrl) - } -} - -func TestVariableNames(t *testing.T) { - route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}") - if route.err == nil { - t.Errorf("Expected error for duplicated variable names") - } -} - -func TestRedirectSlash(t *testing.T) { - var route *Route - var routeMatch RouteMatch - r := NewRouter() - - r.StrictSlash(false) - route = r.NewRoute() - if route.strictSlash != false { - t.Errorf("Expected false redirectSlash.") - } - - r.StrictSlash(true) - route = r.NewRoute() - if route.strictSlash != true { - t.Errorf("Expected true redirectSlash.") - } - - route = new(Route) - route.strictSlash = true - route.Path("/{arg1}/{arg2:[0-9]+}/") - request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil) - routeMatch = RouteMatch{} - _ = route.Match(request, &routeMatch) - vars := routeMatch.Vars - if vars["arg1"] != "foo" { - t.Errorf("Expected foo.") - } - if vars["arg2"] != "123" { - t.Errorf("Expected 123.") - } - rsp := NewRecorder() - routeMatch.Handler.ServeHTTP(rsp, request) - if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" { - t.Errorf("Expected redirect header.") - } - - route = new(Route) - route.strictSlash = true - route.Path("/{arg1}/{arg2:[0-9]+}") - request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil) - routeMatch = RouteMatch{} - _ = route.Match(request, &routeMatch) - vars = routeMatch.Vars - if vars["arg1"] != "foo" { - t.Errorf("Expected foo.") - } - if vars["arg2"] != "123" { - t.Errorf("Expected 123.") - } - rsp = NewRecorder() - routeMatch.Handler.ServeHTTP(rsp, request) - if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" { - t.Errorf("Expected redirect header.") - } -} - -// Test for the new regexp library, still not available in stable Go. -func TestNewRegexp(t *testing.T) { - var p *routeRegexp - var matches []string - - tests := map[string]map[string][]string{ - "/{foo:a{2}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": nil, - "/aaaa": nil, - }, - "/{foo:a{2,}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": {"aaa"}, - "/aaaa": {"aaaa"}, - }, - "/{foo:a{2,3}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": {"aaa"}, - "/aaaa": nil, - }, - "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": { - "/a": nil, - "/ab": nil, - "/abc": nil, - "/abcd": nil, - "/abc/ab": {"abc", "ab"}, - "/abc/abc": nil, - "/abcd/ab": nil, - }, - `/{foo:\w{3,}}/{bar:\d{2,}}`: { - "/a": nil, - "/ab": nil, - "/abc": nil, - "/abc/1": nil, - "/abc/12": {"abc", "12"}, - "/abcd/12": {"abcd", "12"}, - "/abcd/123": {"abcd", "123"}, - }, - } - - for pattern, paths := range tests { - p, _ = newRouteRegexp(pattern, false, false, false, false) - for path, result := range paths { - matches = p.regexp.FindStringSubmatch(path) - if result == nil { - if matches != nil { - t.Errorf("%v should not match %v.", pattern, path) - } - } else { - if len(matches) != len(result)+1 { - t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches)) - } else { - for k, v := range result { - if matches[k+1] != v { - t.Errorf("Expected %v, got %v.", v, matches[k+1]) - } - } - } - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go deleted file mode 100644 index 06728dd54..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "bytes" - "fmt" - "net/http" - "net/url" - "regexp" - "strconv" - "strings" -) - -// newRouteRegexp parses a route template and returns a routeRegexp, -// used to match a host, a path or a query string. -// -// It will extract named variables, assemble a regexp to be matched, create -// a "reverse" template to build URLs and compile regexps to validate variable -// values used in URL building. -// -// Previously we accepted only Python-like identifiers for variable -// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that -// name and pattern can't be empty, and names can't contain a colon. -func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash bool) (*routeRegexp, error) { - // Check if it is well-formed. - idxs, errBraces := braceIndices(tpl) - if errBraces != nil { - return nil, errBraces - } - // Backup the original. - template := tpl - // Now let's parse it. - defaultPattern := "[^/]+" - if matchQuery { - defaultPattern = "[^?&]*" - } else if matchHost { - defaultPattern = "[^.]+" - matchPrefix = false - } - // Only match strict slash if not matching - if matchPrefix || matchHost || matchQuery { - strictSlash = false - } - // Set a flag for strictSlash. - endSlash := false - if strictSlash && strings.HasSuffix(tpl, "/") { - tpl = tpl[:len(tpl)-1] - endSlash = true - } - varsN := make([]string, len(idxs)/2) - varsR := make([]*regexp.Regexp, len(idxs)/2) - pattern := bytes.NewBufferString("") - pattern.WriteByte('^') - reverse := bytes.NewBufferString("") - var end int - var err error - for i := 0; i < len(idxs); i += 2 { - // Set all values we are interested in. - raw := tpl[end:idxs[i]] - end = idxs[i+1] - parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) - name := parts[0] - patt := defaultPattern - if len(parts) == 2 { - patt = parts[1] - } - // Name or pattern can't be empty. - if name == "" || patt == "" { - return nil, fmt.Errorf("mux: missing name or pattern in %q", - tpl[idxs[i]:end]) - } - // Build the regexp pattern. - varIdx := i / 2 - fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(varIdx), patt) - // Build the reverse template. - fmt.Fprintf(reverse, "%s%%s", raw) - - // Append variable name and compiled pattern. - varsN[varIdx] = name - varsR[varIdx], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) - if err != nil { - return nil, err - } - } - // Add the remaining. - raw := tpl[end:] - pattern.WriteString(regexp.QuoteMeta(raw)) - if strictSlash { - pattern.WriteString("[/]?") - } - if matchQuery { - // Add the default pattern if the query value is empty - if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { - pattern.WriteString(defaultPattern) - } - } - if !matchPrefix { - pattern.WriteByte('$') - } - reverse.WriteString(raw) - if endSlash { - reverse.WriteByte('/') - } - // Compile full regexp. - reg, errCompile := regexp.Compile(pattern.String()) - if errCompile != nil { - return nil, errCompile - } - // Done! - return &routeRegexp{ - template: template, - matchHost: matchHost, - matchQuery: matchQuery, - strictSlash: strictSlash, - regexp: reg, - reverse: reverse.String(), - varsN: varsN, - varsR: varsR, - }, nil -} - -// routeRegexp stores a regexp to match a host or path and information to -// collect and validate route variables. -type routeRegexp struct { - // The unmodified template. - template string - // True for host match, false for path or query string match. - matchHost bool - // True for query string match, false for path and host match. - matchQuery bool - // The strictSlash value defined on the route, but disabled if PathPrefix was used. - strictSlash bool - // Expanded regexp. - regexp *regexp.Regexp - // Reverse template. - reverse string - // Variable names. - varsN []string - // Variable regexps (validators). - varsR []*regexp.Regexp -} - -// Match matches the regexp against the URL host or path. -func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { - if !r.matchHost { - if r.matchQuery { - return r.matchQueryString(req) - } else { - return r.regexp.MatchString(req.URL.Path) - } - } - return r.regexp.MatchString(getHost(req)) -} - -// url builds a URL part using the given values. -func (r *routeRegexp) url(values map[string]string) (string, error) { - urlValues := make([]interface{}, len(r.varsN)) - for k, v := range r.varsN { - value, ok := values[v] - if !ok { - return "", fmt.Errorf("mux: missing route variable %q", v) - } - urlValues[k] = value - } - rv := fmt.Sprintf(r.reverse, urlValues...) - if !r.regexp.MatchString(rv) { - // The URL is checked against the full regexp, instead of checking - // individual variables. This is faster but to provide a good error - // message, we check individual regexps if the URL doesn't match. - for k, v := range r.varsN { - if !r.varsR[k].MatchString(values[v]) { - return "", fmt.Errorf( - "mux: variable %q doesn't match, expected %q", values[v], - r.varsR[k].String()) - } - } - } - return rv, nil -} - -// getUrlQuery returns a single query parameter from a request URL. -// For a URL with foo=bar&baz=ding, we return only the relevant key -// value pair for the routeRegexp. -func (r *routeRegexp) getUrlQuery(req *http.Request) string { - if !r.matchQuery { - return "" - } - templateKey := strings.SplitN(r.template, "=", 2)[0] - for key, vals := range req.URL.Query() { - if key == templateKey && len(vals) > 0 { - return key + "=" + vals[0] - } - } - return "" -} - -func (r *routeRegexp) matchQueryString(req *http.Request) bool { - return r.regexp.MatchString(r.getUrlQuery(req)) -} - -// braceIndices returns the first level curly brace indices from a string. -// It returns an error in case of unbalanced braces. -func braceIndices(s string) ([]int, error) { - var level, idx int - idxs := make([]int, 0) - for i := 0; i < len(s); i++ { - switch s[i] { - case '{': - if level++; level == 1 { - idx = i - } - case '}': - if level--; level == 0 { - idxs = append(idxs, idx, i+1) - } else if level < 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - } - } - if level != 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - return idxs, nil -} - -// varGroupName builds a capturing group name for the indexed variable. -func varGroupName(idx int) string { - return "v" + strconv.Itoa(idx) -} - -// ---------------------------------------------------------------------------- -// routeRegexpGroup -// ---------------------------------------------------------------------------- - -// routeRegexpGroup groups the route matchers that carry variables. -type routeRegexpGroup struct { - host *routeRegexp - path *routeRegexp - queries []*routeRegexp -} - -// setMatch extracts the variables from the URL once a route matches. -func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { - // Store host variables. - if v.host != nil { - hostVars := v.host.regexp.FindStringSubmatch(getHost(req)) - if hostVars != nil { - subexpNames := v.host.regexp.SubexpNames() - varName := 0 - for i, name := range subexpNames[1:] { - if name != "" && name == varGroupName(varName) { - m.Vars[v.host.varsN[varName]] = hostVars[i+1] - varName++ - } - } - } - } - // Store path variables. - if v.path != nil { - pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path) - if pathVars != nil { - subexpNames := v.path.regexp.SubexpNames() - varName := 0 - for i, name := range subexpNames[1:] { - if name != "" && name == varGroupName(varName) { - m.Vars[v.path.varsN[varName]] = pathVars[i+1] - varName++ - } - } - // Check if we should redirect. - if v.path.strictSlash { - p1 := strings.HasSuffix(req.URL.Path, "/") - p2 := strings.HasSuffix(v.path.template, "/") - if p1 != p2 { - u, _ := url.Parse(req.URL.String()) - if p1 { - u.Path = u.Path[:len(u.Path)-1] - } else { - u.Path += "/" - } - m.Handler = http.RedirectHandler(u.String(), 301) - } - } - } - } - // Store query string variables. - for _, q := range v.queries { - queryVars := q.regexp.FindStringSubmatch(q.getUrlQuery(req)) - if queryVars != nil { - subexpNames := q.regexp.SubexpNames() - varName := 0 - for i, name := range subexpNames[1:] { - if name != "" && name == varGroupName(varName) { - m.Vars[q.varsN[varName]] = queryVars[i+1] - varName++ - } - } - } - } -} - -// getHost tries its best to return the request host. -func getHost(r *http.Request) string { - if r.URL.IsAbs() { - return r.URL.Host - } - host := r.Host - // Slice off any port information. - if i := strings.Index(host, ":"); i != -1 { - host = host[:i] - } - return host - -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go deleted file mode 100644 index 913432c1c..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "regexp" - "strings" -) - -// Route stores information to match a request and build URLs. -type Route struct { - // Parent where the route was registered (a Router). - parent parentRoute - // Request handler for the route. - handler http.Handler - // List of matchers. - matchers []matcher - // Manager for the variables from host and path. - regexp *routeRegexpGroup - // If true, when the path pattern is "/path/", accessing "/path" will - // redirect to the former and vice versa. - strictSlash bool - // If true, this route never matches: it is only used to build URLs. - buildOnly bool - // The name used to build URLs. - name string - // Error resulted from building a route. - err error - - buildVarsFunc BuildVarsFunc -} - -// Match matches the route against the request. -func (r *Route) Match(req *http.Request, match *RouteMatch) bool { - if r.buildOnly || r.err != nil { - return false - } - // Match everything. - for _, m := range r.matchers { - if matched := m.Match(req, match); !matched { - return false - } - } - // Yay, we have a match. Let's collect some info about it. - if match.Route == nil { - match.Route = r - } - if match.Handler == nil { - match.Handler = r.handler - } - if match.Vars == nil { - match.Vars = make(map[string]string) - } - // Set variables. - if r.regexp != nil { - r.regexp.setMatch(req, match, r) - } - return true -} - -// ---------------------------------------------------------------------------- -// Route attributes -// ---------------------------------------------------------------------------- - -// GetError returns an error resulted from building the route, if any. -func (r *Route) GetError() error { - return r.err -} - -// BuildOnly sets the route to never match: it is only used to build URLs. -func (r *Route) BuildOnly() *Route { - r.buildOnly = true - return r -} - -// Handler -------------------------------------------------------------------- - -// Handler sets a handler for the route. -func (r *Route) Handler(handler http.Handler) *Route { - if r.err == nil { - r.handler = handler - } - return r -} - -// HandlerFunc sets a handler function for the route. -func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { - return r.Handler(http.HandlerFunc(f)) -} - -// GetHandler returns the handler for the route, if any. -func (r *Route) GetHandler() http.Handler { - return r.handler -} - -// Name ----------------------------------------------------------------------- - -// Name sets the name for the route, used to build URLs. -// If the name was registered already it will be overwritten. -func (r *Route) Name(name string) *Route { - if r.name != "" { - r.err = fmt.Errorf("mux: route already has name %q, can't set %q", - r.name, name) - } - if r.err == nil { - r.name = name - r.getNamedRoutes()[name] = r - } - return r -} - -// GetName returns the name for the route, if any. -func (r *Route) GetName() string { - return r.name -} - -// ---------------------------------------------------------------------------- -// Matchers -// ---------------------------------------------------------------------------- - -// matcher types try to match a request. -type matcher interface { - Match(*http.Request, *RouteMatch) bool -} - -// addMatcher adds a matcher to the route. -func (r *Route) addMatcher(m matcher) *Route { - if r.err == nil { - r.matchers = append(r.matchers, m) - } - return r -} - -// addRegexpMatcher adds a host or path matcher and builder to a route. -func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error { - if r.err != nil { - return r.err - } - r.regexp = r.getRegexpGroup() - if !matchHost && !matchQuery { - if len(tpl) == 0 || tpl[0] != '/' { - return fmt.Errorf("mux: path must start with a slash, got %q", tpl) - } - if r.regexp.path != nil { - tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl - } - } - rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash) - if err != nil { - return err - } - for _, q := range r.regexp.queries { - if err = uniqueVars(rr.varsN, q.varsN); err != nil { - return err - } - } - if matchHost { - if r.regexp.path != nil { - if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { - return err - } - } - r.regexp.host = rr - } else { - if r.regexp.host != nil { - if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { - return err - } - } - if matchQuery { - r.regexp.queries = append(r.regexp.queries, rr) - } else { - r.regexp.path = rr - } - } - r.addMatcher(rr) - return nil -} - -// Headers -------------------------------------------------------------------- - -// headerMatcher matches the request against header values. -type headerMatcher map[string]string - -func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithString(m, r.Header, true) -} - -// Headers adds a matcher for request header values. -// It accepts a sequence of key/value pairs to be matched. For example: -// -// r := mux.NewRouter() -// r.Headers("Content-Type", "application/json", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both request header values match. -// If the value is an empty string, it will match any value if the key is set. -func (r *Route) Headers(pairs ...string) *Route { - if r.err == nil { - var headers map[string]string - headers, r.err = mapFromPairsToString(pairs...) - return r.addMatcher(headerMatcher(headers)) - } - return r -} - -// headerRegexMatcher matches the request against the route given a regex for the header -type headerRegexMatcher map[string]*regexp.Regexp - -func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithRegex(m, r.Header, true) -} - -// Regular expressions can be used with headers as well. -// It accepts a sequence of key/value pairs, where the value has regex support. For example -// r := mux.NewRouter() -// r.HeadersRegexp("Content-Type", "application/(text|json)", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both the request header matches both regular expressions. -// It the value is an empty string, it will match any value if the key is set. -func (r *Route) HeadersRegexp(pairs ...string) *Route { - if r.err == nil { - var headers map[string]*regexp.Regexp - headers, r.err = mapFromPairsToRegex(pairs...) - return r.addMatcher(headerRegexMatcher(headers)) - } - return r -} - -// Host ----------------------------------------------------------------------- - -// Host adds a matcher for the URL host. -// It accepts a template with zero or more URL variables enclosed by {}. -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next dot. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Host("www.example.com") -// r.Host("{subdomain}.domain.com") -// r.Host("{subdomain:[a-z]+}.domain.com") -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Host(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, true, false, false) - return r -} - -// MatcherFunc ---------------------------------------------------------------- - -// MatcherFunc is the function signature used by custom matchers. -type MatcherFunc func(*http.Request, *RouteMatch) bool - -func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { - return m(r, match) -} - -// MatcherFunc adds a custom function to be used as request matcher. -func (r *Route) MatcherFunc(f MatcherFunc) *Route { - return r.addMatcher(f) -} - -// Methods -------------------------------------------------------------------- - -// methodMatcher matches the request against HTTP methods. -type methodMatcher []string - -func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.Method) -} - -// Methods adds a matcher for HTTP methods. -// It accepts a sequence of one or more methods to be matched, e.g.: -// "GET", "POST", "PUT". -func (r *Route) Methods(methods ...string) *Route { - for k, v := range methods { - methods[k] = strings.ToUpper(v) - } - return r.addMatcher(methodMatcher(methods)) -} - -// Path ----------------------------------------------------------------------- - -// Path adds a matcher for the URL path. -// It accepts a template with zero or more URL variables enclosed by {}. The -// template must start with a "/". -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Path("/products/").Handler(ProductsHandler) -// r.Path("/products/{key}").Handler(ProductsHandler) -// r.Path("/articles/{category}/{id:[0-9]+}"). -// Handler(ArticleHandler) -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Path(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, false, false) - return r -} - -// PathPrefix ----------------------------------------------------------------- - -// PathPrefix adds a matcher for the URL path prefix. This matches if the given -// template is a prefix of the full URL path. See Route.Path() for details on -// the tpl argument. -// -// Note that it does not treat slashes specially ("/foobar/" will be matched by -// the prefix "/foo") so you may want to use a trailing slash here. -// -// Also note that the setting of Router.StrictSlash() has no effect on routes -// with a PathPrefix matcher. -func (r *Route) PathPrefix(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, true, false) - return r -} - -// Query ---------------------------------------------------------------------- - -// Queries adds a matcher for URL query values. -// It accepts a sequence of key/value pairs. Values may define variables. -// For example: -// -// r := mux.NewRouter() -// r.Queries("foo", "bar", "id", "{id:[0-9]+}") -// -// The above route will only match if the URL contains the defined queries -// values, e.g.: ?foo=bar&id=42. -// -// It the value is an empty string, it will match any value if the key is set. -// -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -func (r *Route) Queries(pairs ...string) *Route { - length := len(pairs) - if length%2 != 0 { - r.err = fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - return nil - } - for i := 0; i < length; i += 2 { - if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil { - return r - } - } - - return r -} - -// Schemes -------------------------------------------------------------------- - -// schemeMatcher matches the request against URL schemes. -type schemeMatcher []string - -func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.URL.Scheme) -} - -// Schemes adds a matcher for URL schemes. -// It accepts a sequence of schemes to be matched, e.g.: "http", "https". -func (r *Route) Schemes(schemes ...string) *Route { - for k, v := range schemes { - schemes[k] = strings.ToLower(v) - } - return r.addMatcher(schemeMatcher(schemes)) -} - -// BuildVarsFunc -------------------------------------------------------------- - -// BuildVarsFunc is the function signature used by custom build variable -// functions (which can modify route variables before a route's URL is built). -type BuildVarsFunc func(map[string]string) map[string]string - -// BuildVarsFunc adds a custom function to be used to modify build variables -// before a route's URL is built. -func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { - r.buildVarsFunc = f - return r -} - -// Subrouter ------------------------------------------------------------------ - -// Subrouter creates a subrouter for the route. -// -// It will test the inner routes only if the parent route matched. For example: -// -// r := mux.NewRouter() -// s := r.Host("www.example.com").Subrouter() -// s.HandleFunc("/products/", ProductsHandler) -// s.HandleFunc("/products/{key}", ProductHandler) -// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) -// -// Here, the routes registered in the subrouter won't be tested if the host -// doesn't match. -func (r *Route) Subrouter() *Router { - router := &Router{parent: r, strictSlash: r.strictSlash} - r.addMatcher(router) - return router -} - -// ---------------------------------------------------------------------------- -// URL building -// ---------------------------------------------------------------------------- - -// URL builds a URL for the route. -// -// It accepts a sequence of key/value pairs for the route variables. For -// example, given this route: -// -// r := mux.NewRouter() -// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// ...a URL for it can be built using: -// -// url, err := r.Get("article").URL("category", "technology", "id", "42") -// -// ...which will return an url.URL with the following path: -// -// "/articles/technology/42" -// -// This also works for host variables: -// -// r := mux.NewRouter() -// r.Host("{subdomain}.domain.com"). -// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// // url.String() will be "http://news.domain.com/articles/technology/42" -// url, err := r.Get("article").URL("subdomain", "news", -// "category", "technology", -// "id", "42") -// -// All variables defined in the route are required, and their values must -// conform to the corresponding patterns. -func (r *Route) URL(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil { - return nil, errors.New("mux: route doesn't have a host or path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - var scheme, host, path string - if r.regexp.host != nil { - // Set a default scheme. - scheme = "http" - if host, err = r.regexp.host.url(values); err != nil { - return nil, err - } - } - if r.regexp.path != nil { - if path, err = r.regexp.path.url(values); err != nil { - return nil, err - } - } - return &url.URL{ - Scheme: scheme, - Host: host, - Path: path, - }, nil -} - -// URLHost builds the host part of the URL for a route. See Route.URL(). -// -// The route must have a host defined. -func (r *Route) URLHost(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.host == nil { - return nil, errors.New("mux: route doesn't have a host") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - host, err := r.regexp.host.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Scheme: "http", - Host: host, - }, nil -} - -// URLPath builds the path part of the URL for a route. See Route.URL(). -// -// The route must have a path defined. -func (r *Route) URLPath(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.path == nil { - return nil, errors.New("mux: route doesn't have a path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - path, err := r.regexp.path.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Path: path, - }, nil -} - -// prepareVars converts the route variable pairs into a map. If the route has a -// BuildVarsFunc, it is invoked. -func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { - m, err := mapFromPairsToString(pairs...) - if err != nil { - return nil, err - } - return r.buildVars(m), nil -} - -func (r *Route) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - if r.buildVarsFunc != nil { - m = r.buildVarsFunc(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// parentRoute allows routes to know about parent host and path definitions. -type parentRoute interface { - getNamedRoutes() map[string]*Route - getRegexpGroup() *routeRegexpGroup - buildVars(map[string]string) map[string]string -} - -// getNamedRoutes returns the map where named routes are registered. -func (r *Route) getNamedRoutes() map[string]*Route { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - return r.parent.getNamedRoutes() -} - -// getRegexpGroup returns regexp definitions from this route. -func (r *Route) getRegexpGroup() *routeRegexpGroup { - if r.regexp == nil { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - regexp := r.parent.getRegexpGroup() - if regexp == nil { - r.regexp = new(routeRegexpGroup) - } else { - // Copy. - r.regexp = &routeRegexpGroup{ - host: regexp.host, - path: regexp.path, - queries: regexp.queries, - } - } - } - return r.regexp -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go deleted file mode 100644 index 53b2289bf..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go +++ /dev/null @@ -1,472 +0,0 @@ -package user - -import ( - "io" - "reflect" - "sort" - "strconv" - "strings" - "testing" -) - -func TestUserParseLine(t *testing.T) { - var ( - a, b string - c []string - d int - ) - - parseLine("", &a, &b) - if a != "" || b != "" { - t.Fatalf("a and b should be empty ('%v', '%v')", a, b) - } - - parseLine("a", &a, &b) - if a != "a" || b != "" { - t.Fatalf("a should be 'a' and b should be empty ('%v', '%v')", a, b) - } - - parseLine("bad boys:corny cows", &a, &b) - if a != "bad boys" || b != "corny cows" { - t.Fatalf("a should be 'bad boys' and b should be 'corny cows' ('%v', '%v')", a, b) - } - - parseLine("", &c) - if len(c) != 0 { - t.Fatalf("c should be empty (%#v)", c) - } - - parseLine("d,e,f:g:h:i,j,k", &c, &a, &b, &c) - if a != "g" || b != "h" || len(c) != 3 || c[0] != "i" || c[1] != "j" || c[2] != "k" { - t.Fatalf("a should be 'g', b should be 'h', and c should be ['i','j','k'] ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("::::::::::", &a, &b, &c) - if a != "" || b != "" || len(c) != 0 { - t.Fatalf("a, b, and c should all be empty ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("not a number", &d) - if d != 0 { - t.Fatalf("d should be 0 (%v)", d) - } - - parseLine("b:12:c", &a, &d, &b) - if a != "b" || b != "c" || d != 12 { - t.Fatalf("a should be 'b' and b should be 'c', and d should be 12 ('%v', '%v', %v)", a, b, d) - } -} - -func TestUserParsePasswd(t *testing.T) { - users, err := ParsePasswdFilter(strings.NewReader(` -root:x:0:0:root:/root:/bin/bash -adm:x:3:4:adm:/var/adm:/bin/false -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(users) != 3 { - t.Fatalf("Expected 3 users, got %v", len(users)) - } - if users[0].Uid != 0 || users[0].Name != "root" { - t.Fatalf("Expected users[0] to be 0 - root, got %v - %v", users[0].Uid, users[0].Name) - } - if users[1].Uid != 3 || users[1].Name != "adm" { - t.Fatalf("Expected users[1] to be 3 - adm, got %v - %v", users[1].Uid, users[1].Name) - } -} - -func TestUserParseGroup(t *testing.T) { - groups, err := ParseGroupFilter(strings.NewReader(` -root:x:0:root -adm:x:4:root,adm,daemon -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(groups) != 3 { - t.Fatalf("Expected 3 groups, got %v", len(groups)) - } - if groups[0].Gid != 0 || groups[0].Name != "root" || len(groups[0].List) != 1 { - t.Fatalf("Expected groups[0] to be 0 - root - 1 member, got %v - %v - %v", groups[0].Gid, groups[0].Name, len(groups[0].List)) - } - if groups[1].Gid != 4 || groups[1].Name != "adm" || len(groups[1].List) != 3 { - t.Fatalf("Expected groups[1] to be 4 - adm - 3 members, got %v - %v - %v", groups[1].Gid, groups[1].Name, len(groups[1].List)) - } -} - -func TestValidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - expected ExecUser - }{ - { - ref: "root", - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{0, 1234}, - Home: "/root", - }, - }, - { - ref: "adm", - expected: ExecUser{ - Uid: 42, - Gid: 43, - Sgids: []int{1234}, - Home: "/var/adm", - }, - }, - { - ref: "root:adm", - expected: ExecUser{ - Uid: 0, - Gid: 43, - Sgids: defaultExecUser.Sgids, - Home: "/root", - }, - }, - { - ref: "adm:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "42:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "1337:1234", - expected: ExecUser{ - Uid: 1337, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "1337", - expected: ExecUser{ - Uid: 1337, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "", - expected: ExecUser{ - Uid: defaultExecUser.Uid, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} - -func TestInvalidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - tests := []string{ - // No such user/group. - "notuser", - "notuser:notgroup", - "root:notgroup", - "notuser:adm", - "8888:notgroup", - "notuser:8888", - - // Invalid user/group values. - "-1:0", - "0:-3", - "-5:-2", - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test, nil, passwd, group) - if err == nil { - t.Logf("got unexpected success when parsing '%s': %#v", test, execUser) - t.Fail() - continue - } - } -} - -func TestGetExecUserNilSources(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - passwd, group bool - expected ExecUser - }{ - { - ref: "", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "root", - passwd: true, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/root", - }, - }, - { - ref: "0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "0:0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - } - - for _, test := range tests { - var passwd, group io.Reader - - if test.passwd { - passwd = strings.NewReader(passwdContent) - } - - if test.group { - group = strings.NewReader(groupContent) - } - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} - -func TestGetAdditionalGroups(t *testing.T) { - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -adm:x:4343:root,adm-duplicate -this is just some garbage data -` - tests := []struct { - groups []string - expected []int - hasError bool - }{ - { - // empty group - groups: []string{}, - expected: []int{}, - }, - { - // single group - groups: []string{"adm"}, - expected: []int{43}, - }, - { - // multiple groups - groups: []string{"adm", "grp"}, - expected: []int{43, 1234}, - }, - { - // invalid group - groups: []string{"adm", "grp", "not-exist"}, - expected: nil, - hasError: true, - }, - { - // group with numeric id - groups: []string{"43"}, - expected: []int{43}, - }, - { - // group with unknown numeric id - groups: []string{"adm", "10001"}, - expected: []int{43, 10001}, - }, - { - // groups specified twice with numeric and name - groups: []string{"adm", "43"}, - expected: []int{43}, - }, - { - // groups with too small id - groups: []string{"-1"}, - expected: nil, - hasError: true, - }, - { - // groups with too large id - groups: []string{strconv.Itoa(1 << 31)}, - expected: nil, - hasError: true, - }, - } - - for _, test := range tests { - group := strings.NewReader(groupContent) - - gids, err := GetAdditionalGroups(test.groups, group) - if test.hasError && err == nil { - t.Errorf("Parse(%#v) expects error but has none", test) - continue - } - if !test.hasError && err != nil { - t.Errorf("Parse(%#v) has error %v", test, err) - continue - } - sort.Sort(sort.IntSlice(gids)) - if !reflect.DeepEqual(gids, test.expected) { - t.Errorf("Gids(%v), expect %v from groups %v", gids, test.expected, test.groups) - } - } -} - -func TestGetAdditionalGroupsNumeric(t *testing.T) { - tests := []struct { - groups []string - expected []int - hasError bool - }{ - { - // numeric groups only - groups: []string{"1234", "5678"}, - expected: []int{1234, 5678}, - }, - { - // numeric and alphabetic - groups: []string{"1234", "fake"}, - expected: nil, - hasError: true, - }, - } - - for _, test := range tests { - gids, err := GetAdditionalGroups(test.groups, nil) - if test.hasError && err == nil { - t.Errorf("Parse(%#v) expects error but has none", test) - continue - } - if !test.hasError && err != nil { - t.Errorf("Parse(%#v) has error %v", test, err) - continue - } - sort.Sort(sort.IntSlice(gids)) - if !reflect.DeepEqual(gids, test.expected) { - t.Errorf("Gids(%v), expect %v from groups %v", gids, test.expected, test.groups) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context_test.go deleted file mode 100644 index 05345fc5e..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context_test.go +++ /dev/null @@ -1,575 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context - -import ( - "fmt" - "math/rand" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -// otherContext is a Context that's not one of the types defined in context.go. -// This lets us test code paths that differ based on the underlying type of the -// Context. -type otherContext struct { - Context -} - -func TestBackground(t *testing.T) { - c := Background() - if c == nil { - t.Fatalf("Background returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.Background"; got != want { - t.Errorf("Background().String() = %q want %q", got, want) - } -} - -func TestTODO(t *testing.T) { - c := TODO() - if c == nil { - t.Fatalf("TODO returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.TODO"; got != want { - t.Errorf("TODO().String() = %q want %q", got, want) - } -} - -func TestWithCancel(t *testing.T) { - c1, cancel := WithCancel(Background()) - - if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { - t.Errorf("c1.String() = %q want %q", got, want) - } - - o := otherContext{c1} - c2, _ := WithCancel(o) - contexts := []Context{c1, o, c2} - - for i, c := range contexts { - if d := c.Done(); d == nil { - t.Errorf("c[%d].Done() == %v want non-nil", i, d) - } - if e := c.Err(); e != nil { - t.Errorf("c[%d].Err() == %v want nil", i, e) - } - - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - } - - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - - for i, c := range contexts { - select { - case <-c.Done(): - default: - t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) - } - if e := c.Err(); e != Canceled { - t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) - } - } -} - -func TestParentFinishesChild(t *testing.T) { - // Context tree: - // parent -> cancelChild - // parent -> valueChild -> timerChild - parent, cancel := WithCancel(Background()) - cancelChild, stop := WithCancel(parent) - defer stop() - valueChild := WithValue(parent, "key", "value") - timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) - defer stop() - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-cancelChild.Done(): - t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) - case x := <-timerChild.Done(): - t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) - case x := <-valueChild.Done(): - t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) - default: - } - - // The parent's children should contain the two cancelable children. - pc := parent.(*cancelCtx) - cc := cancelChild.(*cancelCtx) - tc := timerChild.(*timerCtx) - pc.mu.Lock() - if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { - t.Errorf("bad linkage: pc.children = %v, want %v and %v", - pc.children, cc, tc) - } - pc.mu.Unlock() - - if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) - } - if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) - } - - cancel() - - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) - } - pc.mu.Unlock() - - // parent and children should all be finished. - check := func(ctx Context, name string) { - select { - case <-ctx.Done(): - default: - t.Errorf("<-%s.Done() blocked, but shouldn't have", name) - } - if e := ctx.Err(); e != Canceled { - t.Errorf("%s.Err() == %v want %v", name, e, Canceled) - } - } - check(parent, "parent") - check(cancelChild, "cancelChild") - check(valueChild, "valueChild") - check(timerChild, "timerChild") - - // WithCancel should return a canceled context on a canceled parent. - precanceledChild := WithValue(parent, "key", "value") - select { - case <-precanceledChild.Done(): - default: - t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") - } - if e := precanceledChild.Err(); e != Canceled { - t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) - } -} - -func TestChildFinishesFirst(t *testing.T) { - cancelable, stop := WithCancel(Background()) - defer stop() - for _, parent := range []Context{Background(), cancelable} { - child, cancel := WithCancel(parent) - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-child.Done(): - t.Errorf("<-child.Done() == %v want nothing (it should block)", x) - default: - } - - cc := child.(*cancelCtx) - pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() - if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { - t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) - } - - if pcok { - pc.mu.Lock() - if len(pc.children) != 1 || !pc.children[cc] { - t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) - } - pc.mu.Unlock() - } - - cancel() - - if pcok { - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) - } - pc.mu.Unlock() - } - - // child should be finished. - select { - case <-child.Done(): - default: - t.Errorf("<-child.Done() blocked, but shouldn't have") - } - if e := child.Err(); e != Canceled { - t.Errorf("child.Err() == %v want %v", e, Canceled) - } - - // parent should not be finished. - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - default: - } - if e := parent.Err(); e != nil { - t.Errorf("parent.Err() == %v want nil", e) - } - } -} - -func testDeadline(c Context, wait time.Duration, t *testing.T) { - select { - case <-time.After(wait): - t.Fatalf("context should have timed out") - case <-c.Done(): - } - if e := c.Err(); e != DeadlineExceeded { - t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) - } -} - -func TestDeadline(t *testing.T) { - c, _ := WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 200*time.Millisecond, t) - - c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - o := otherContext{c} - testDeadline(o, 200*time.Millisecond, t) - - c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - o = otherContext{c} - c, _ = WithDeadline(o, time.Now().Add(300*time.Millisecond)) - testDeadline(c, 200*time.Millisecond, t) -} - -func TestTimeout(t *testing.T) { - c, _ := WithTimeout(Background(), 100*time.Millisecond) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 200*time.Millisecond, t) - - c, _ = WithTimeout(Background(), 100*time.Millisecond) - o := otherContext{c} - testDeadline(o, 200*time.Millisecond, t) - - c, _ = WithTimeout(Background(), 100*time.Millisecond) - o = otherContext{c} - c, _ = WithTimeout(o, 300*time.Millisecond) - testDeadline(c, 200*time.Millisecond, t) -} - -func TestCanceledTimeout(t *testing.T) { - c, _ := WithTimeout(Background(), 200*time.Millisecond) - o := otherContext{c} - c, cancel := WithTimeout(o, 400*time.Millisecond) - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - select { - case <-c.Done(): - default: - t.Errorf("<-c.Done() blocked, but shouldn't have") - } - if e := c.Err(); e != Canceled { - t.Errorf("c.Err() == %v want %v", e, Canceled) - } -} - -type key1 int -type key2 int - -var k1 = key1(1) -var k2 = key2(1) // same int as k1, different type -var k3 = key2(3) // same type as k2, different int - -func TestValues(t *testing.T) { - check := func(c Context, nm, v1, v2, v3 string) { - if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { - t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) - } - if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { - t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) - } - if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { - t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) - } - } - - c0 := Background() - check(c0, "c0", "", "", "") - - c1 := WithValue(Background(), k1, "c1k1") - check(c1, "c1", "c1k1", "", "") - - if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { - t.Errorf("c.String() = %q want %q", got, want) - } - - c2 := WithValue(c1, k2, "c2k2") - check(c2, "c2", "c1k1", "c2k2", "") - - c3 := WithValue(c2, k3, "c3k3") - check(c3, "c2", "c1k1", "c2k2", "c3k3") - - c4 := WithValue(c3, k1, nil) - check(c4, "c4", "", "c2k2", "c3k3") - - o0 := otherContext{Background()} - check(o0, "o0", "", "", "") - - o1 := otherContext{WithValue(Background(), k1, "c1k1")} - check(o1, "o1", "c1k1", "", "") - - o2 := WithValue(o1, k2, "o2k2") - check(o2, "o2", "c1k1", "o2k2", "") - - o3 := otherContext{c4} - check(o3, "o3", "", "c2k2", "c3k3") - - o4 := WithValue(o3, k3, nil) - check(o4, "o4", "", "c2k2", "") -} - -func TestAllocs(t *testing.T) { - bg := Background() - for _, test := range []struct { - desc string - f func() - limit float64 - gccgoLimit float64 - }{ - { - desc: "Background()", - f: func() { Background() }, - limit: 0, - gccgoLimit: 0, - }, - { - desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), - f: func() { - c := WithValue(bg, k1, nil) - c.Value(k1) - }, - limit: 3, - gccgoLimit: 3, - }, - { - desc: "WithTimeout(bg, 15*time.Millisecond)", - f: func() { - c, _ := WithTimeout(bg, 15*time.Millisecond) - <-c.Done() - }, - limit: 8, - gccgoLimit: 15, - }, - { - desc: "WithCancel(bg)", - f: func() { - c, cancel := WithCancel(bg) - cancel() - <-c.Done() - }, - limit: 5, - gccgoLimit: 8, - }, - { - desc: "WithTimeout(bg, 100*time.Millisecond)", - f: func() { - c, cancel := WithTimeout(bg, 100*time.Millisecond) - cancel() - <-c.Done() - }, - limit: 8, - gccgoLimit: 25, - }, - } { - limit := test.limit - if runtime.Compiler == "gccgo" { - // gccgo does not yet do escape analysis. - // TOOD(iant): Remove this when gccgo does do escape analysis. - limit = test.gccgoLimit - } - if n := testing.AllocsPerRun(100, test.f); n > limit { - t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) - } - } -} - -func TestSimultaneousCancels(t *testing.T) { - root, cancel := WithCancel(Background()) - m := map[Context]CancelFunc{root: cancel} - q := []Context{root} - // Create a tree of contexts. - for len(q) != 0 && len(m) < 100 { - parent := q[0] - q = q[1:] - for i := 0; i < 4; i++ { - ctx, cancel := WithCancel(parent) - m[ctx] = cancel - q = append(q, ctx) - } - } - // Start all the cancels in a random order. - var wg sync.WaitGroup - wg.Add(len(m)) - for _, cancel := range m { - go func(cancel CancelFunc) { - cancel() - wg.Done() - }(cancel) - } - // Wait on all the contexts in a random order. - for ctx := range m { - select { - case <-ctx.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) - } - } - // Wait for all the cancel functions to return. - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) - } -} - -func TestInterlockedCancels(t *testing.T) { - parent, cancelParent := WithCancel(Background()) - child, cancelChild := WithCancel(parent) - go func() { - parent.Done() - cancelChild() - }() - cancelParent() - select { - case <-child.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) - } -} - -func TestLayersCancel(t *testing.T) { - testLayers(t, time.Now().UnixNano(), false) -} - -func TestLayersTimeout(t *testing.T) { - testLayers(t, time.Now().UnixNano(), true) -} - -func testLayers(t *testing.T, seed int64, testTimeout bool) { - rand.Seed(seed) - errorf := func(format string, a ...interface{}) { - t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) - } - const ( - timeout = 200 * time.Millisecond - minLayers = 30 - ) - type value int - var ( - vals []*value - cancels []CancelFunc - numTimers int - ctx = Background() - ) - for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { - switch rand.Intn(3) { - case 0: - v := new(value) - ctx = WithValue(ctx, v, v) - vals = append(vals, v) - case 1: - var cancel CancelFunc - ctx, cancel = WithCancel(ctx) - cancels = append(cancels, cancel) - case 2: - var cancel CancelFunc - ctx, cancel = WithTimeout(ctx, timeout) - cancels = append(cancels, cancel) - numTimers++ - } - } - checkValues := func(when string) { - for _, key := range vals { - if val := ctx.Value(key).(*value); key != val { - errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) - } - } - } - select { - case <-ctx.Done(): - errorf("ctx should not be canceled yet") - default: - } - if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { - t.Errorf("ctx.String() = %q want prefix %q", s, prefix) - } - t.Log(ctx) - checkValues("before cancel") - if testTimeout { - select { - case <-ctx.Done(): - case <-time.After(timeout + 100*time.Millisecond): - errorf("ctx should have timed out") - } - checkValues("after timeout") - } else { - cancel := cancels[rand.Intn(len(cancels))] - cancel() - select { - case <-ctx.Done(): - default: - errorf("ctx should be canceled") - } - checkValues("after cancel") - } -} - -func TestCancelRemoves(t *testing.T) { - checkChildren := func(when string, ctx Context, want int) { - if got := len(ctx.(*cancelCtx).children); got != want { - t.Errorf("%s: context has %d children, want %d", when, got, want) - } - } - - ctx, _ := WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel := WithCancel(ctx) - checkChildren("with WithCancel child ", ctx, 1) - cancel() - checkChildren("after cancelling WithCancel child", ctx, 0) - - ctx, _ = WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel = WithTimeout(ctx, 60*time.Minute) - checkChildren("with WithTimeout child ", ctx, 1) - cancel() - checkChildren("after cancelling WithTimeout child", ctx, 0) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/withtimeout_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/withtimeout_test.go deleted file mode 100644 index 00d5d1ca9..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/withtimeout_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context_test - -import ( - "fmt" - "time" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" -) - -func ExampleWithTimeout() { - // Pass a context with a timeout to tell a blocking function that it - // should abandon its work after the timeout elapses. - ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) - select { - case <-time.After(200 * time.Millisecond): - fmt.Println("overslept") - case <-ctx.Done(): - fmt.Println(ctx.Err()) // prints "context deadline exceeded" - } - // Output: - // context deadline exceeded -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/creds_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/creds_test.go deleted file mode 100644 index 31cf39b1e..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/creds_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// 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 linux - -package unix_test - -import ( - "bytes" - "net" - "os" - "syscall" - "testing" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" -) - -// TestSCMCredentials tests the sending and receiving of credentials -// (PID, UID, GID) in an ancillary message between two UNIX -// sockets. The SO_PASSCRED socket option is enabled on the sending -// socket for this to work. -func TestSCMCredentials(t *testing.T) { - fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - - err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) - if err != nil { - t.Fatalf("SetsockoptInt: %v", err) - } - - srvFile := os.NewFile(uintptr(fds[0]), "server") - defer srvFile.Close() - srv, err := net.FileConn(srvFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer srv.Close() - - cliFile := os.NewFile(uintptr(fds[1]), "client") - defer cliFile.Close() - cli, err := net.FileConn(cliFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer cli.Close() - - var ucred unix.Ucred - if os.Getuid() != 0 { - ucred.Pid = int32(os.Getpid()) - ucred.Uid = 0 - ucred.Gid = 0 - oob := unix.UnixCredentials(&ucred) - _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if op, ok := err.(*net.OpError); ok { - err = op.Err - } - if sys, ok := err.(*os.SyscallError); ok { - err = sys.Err - } - if err != syscall.EPERM { - t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) - } - } - - ucred.Pid = int32(os.Getpid()) - ucred.Uid = uint32(os.Getuid()) - ucred.Gid = uint32(os.Getgid()) - oob := unix.UnixCredentials(&ucred) - - // this is going to send a dummy byte - n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if err != nil { - t.Fatalf("WriteMsgUnix: %v", err) - } - if n != 0 { - t.Fatalf("WriteMsgUnix n = %d, want 0", n) - } - if oobn != len(oob) { - t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) - } - - oob2 := make([]byte, 10*len(oob)) - n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2) - if err != nil { - t.Fatalf("ReadMsgUnix: %v", err) - } - if flags != 0 { - t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags) - } - if n != 1 { - t.Fatalf("ReadMsgUnix n = %d, want 1 (dummy byte)", n) - } - if oobn2 != oobn { - // without SO_PASSCRED set on the socket, ReadMsgUnix will - // return zero oob bytes - t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn) - } - oob2 = oob2[:oobn2] - if !bytes.Equal(oob, oob2) { - t.Fatal("ReadMsgUnix oob bytes don't match") - } - - scm, err := unix.ParseSocketControlMessage(oob2) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - newUcred, err := unix.ParseUnixCredentials(&scm[0]) - if err != nil { - t.Fatalf("ParseUnixCredentials: %v", err) - } - if *newUcred != ucred { - t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/export_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/export_test.go deleted file mode 100644 index b4fdd970b..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/export_test.go +++ /dev/null @@ -1,9 +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 darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix - -var Itoa = itoa diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mmap_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mmap_unix_test.go deleted file mode 100644 index 30aa6fe23..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mmap_unix_test.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "testing" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" -) - -func TestMmap(t *testing.T) { - b, err := unix.Mmap(-1, 0, unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) - if err != nil { - t.Fatalf("Mmap: %v", err) - } - if err := unix.Munmap(b); err != nil { - t.Fatalf("Munmap: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd_test.go deleted file mode 100644 index 7cd360647..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd openbsd - -package unix_test - -import ( - "testing" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" -) - -const MNT_WAIT = 1 - -func TestGetfsstat(t *testing.T) { - n, err := unix.Getfsstat(nil, MNT_WAIT) - if err != nil { - t.Fatal(err) - } - - data := make([]unix.Statfs_t, n) - n, err = unix.Getfsstat(data, MNT_WAIT) - if err != nil { - t.Fatal(err) - } - - empty := unix.Statfs_t{} - for _, stat := range data { - if stat == empty { - t.Fatal("an empty Statfs_t struct was returned") - } - } -} - -func TestSysctlRaw(t *testing.T) { - _, err := unix.SysctlRaw("kern.proc.pid", unix.Getpid()) - if err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_test.go deleted file mode 100644 index 62f8052a8..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_test.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build freebsd - -package unix_test - -import ( - "testing" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" -) - -func TestSysctUint64(t *testing.T) { - _, err := unix.SysctlUint64("vm.max_kernel_address") - if err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_test.go deleted file mode 100644 index b1b2c23a0..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "fmt" - "testing" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" -) - -func testSetGetenv(t *testing.T, key, value string) { - err := unix.Setenv(key, value) - if err != nil { - t.Fatalf("Setenv failed to set %q: %v", value, err) - } - newvalue, found := unix.Getenv(key) - if !found { - t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) - } - if newvalue != value { - t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) - } -} - -func TestEnv(t *testing.T) { - testSetGetenv(t, "TESTENV", "AVALUE") - // make sure TESTENV gets set to "", not deleted - testSetGetenv(t, "TESTENV", "") -} - -func TestItoa(t *testing.T) { - // Make most negative integer: 0x8000... - i := 1 - for i<<1 != 0 { - i <<= 1 - } - if i >= 0 { - t.Fatal("bad math") - } - s := unix.Itoa(i) - f := fmt.Sprint(i) - if s != f { - t.Fatalf("itoa(%d) = %s, want %s", i, s, f) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix_test.go deleted file mode 100644 index ddad90e5f..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix_test.go +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "flag" - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "testing" - "time" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" -) - -// Tests that below functions, structures and constants are consistent -// on all Unix-like systems. -func _() { - // program scheduling priority functions and constants - var ( - _ func(int, int, int) error = unix.Setpriority - _ func(int, int) (int, error) = unix.Getpriority - ) - const ( - _ int = unix.PRIO_USER - _ int = unix.PRIO_PROCESS - _ int = unix.PRIO_PGRP - ) - - // termios constants - const ( - _ int = unix.TCIFLUSH - _ int = unix.TCIOFLUSH - _ int = unix.TCOFLUSH - ) - - // fcntl file locking structure and constants - var ( - _ = unix.Flock_t{ - Type: int16(0), - Whence: int16(0), - Start: int64(0), - Len: int64(0), - Pid: int32(0), - } - ) - const ( - _ = unix.F_GETLK - _ = unix.F_SETLK - _ = unix.F_SETLKW - ) -} - -// TestFcntlFlock tests whether the file locking structure matches -// the calling convention of each kernel. -func TestFcntlFlock(t *testing.T) { - name := filepath.Join(os.TempDir(), "TestFcntlFlock") - fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) - if err != nil { - t.Fatalf("Open failed: %v", err) - } - defer unix.Unlink(name) - defer unix.Close(fd) - flock := unix.Flock_t{ - Type: unix.F_RDLCK, - Start: 0, Len: 0, Whence: 1, - } - if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil { - t.Fatalf("FcntlFlock failed: %v", err) - } -} - -// TestPassFD tests passing a file descriptor over a Unix socket. -// -// This test involved both a parent and child process. The parent -// process is invoked as a normal test, with "go test", which then -// runs the child process by running the current test binary with args -// "-test.run=^TestPassFD$" and an environment variable used to signal -// that the test should become the child process instead. -func TestPassFD(t *testing.T) { - switch runtime.GOOS { - case "dragonfly": - // TODO(jsing): Figure out why sendmsg is returning EINVAL. - t.Skip("skipping test on dragonfly") - case "solaris": - // TODO(aram): Figure out why ReadMsgUnix is returning empty message. - t.Skip("skipping test on solaris, see issue 7402") - } - if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { - passFDChild() - return - } - - tempDir, err := ioutil.TempDir("", "TestPassFD") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempDir) - - fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - writeFile := os.NewFile(uintptr(fds[0]), "child-writes") - readFile := os.NewFile(uintptr(fds[1]), "parent-reads") - defer writeFile.Close() - defer readFile.Close() - - cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) - cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} - if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { - cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) - } - cmd.ExtraFiles = []*os.File{writeFile} - - out, err := cmd.CombinedOutput() - if len(out) > 0 || err != nil { - t.Fatalf("child process: %q, %v", out, err) - } - - c, err := net.FileConn(readFile) - if err != nil { - t.Fatalf("FileConn: %v", err) - } - defer c.Close() - - uc, ok := c.(*net.UnixConn) - if !ok { - t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) - } - - buf := make([]byte, 32) // expect 1 byte - oob := make([]byte, 32) // expect 24 bytes - closeUnix := time.AfterFunc(5*time.Second, func() { - t.Logf("timeout reading from unix socket") - uc.Close() - }) - _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) - closeUnix.Stop() - - scms, err := unix.ParseSocketControlMessage(oob[:oobn]) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != 1 { - t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) - } - scm := scms[0] - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("unix.ParseUnixRights: %v", err) - } - if len(gotFds) != 1 { - t.Fatalf("wanted 1 fd; got %#v", gotFds) - } - - f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") - defer f.Close() - - got, err := ioutil.ReadAll(f) - want := "Hello from child process!\n" - if string(got) != want { - t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) - } -} - -// passFDChild is the child process used by TestPassFD. -func passFDChild() { - defer os.Exit(0) - - // Look for our fd. It should be fd 3, but we work around an fd leak - // bug here (http://golang.org/issue/2603) to let it be elsewhere. - var uc *net.UnixConn - for fd := uintptr(3); fd <= 10; fd++ { - f := os.NewFile(fd, "unix-conn") - var ok bool - netc, _ := net.FileConn(f) - uc, ok = netc.(*net.UnixConn) - if ok { - break - } - } - if uc == nil { - fmt.Println("failed to find unix fd") - return - } - - // Make a file f to send to our parent process on uc. - // We make it in tempDir, which our parent will clean up. - flag.Parse() - tempDir := flag.Arg(0) - f, err := ioutil.TempFile(tempDir, "") - if err != nil { - fmt.Printf("TempFile: %v", err) - return - } - - f.Write([]byte("Hello from child process!\n")) - f.Seek(0, 0) - - rights := unix.UnixRights(int(f.Fd())) - dummyByte := []byte("x") - n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) - if err != nil { - fmt.Printf("WriteMsgUnix: %v", err) - return - } - if n != 1 || oobn != len(rights) { - fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) - return - } -} - -// TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, -// and ParseUnixRights are able to successfully round-trip lists of file descriptors. -func TestUnixRightsRoundtrip(t *testing.T) { - testCases := [...][][]int{ - {{42}}, - {{1, 2}}, - {{3, 4, 5}}, - {{}}, - {{1, 2}, {3, 4, 5}, {}, {7}}, - } - for _, testCase := range testCases { - b := []byte{} - var n int - for _, fds := range testCase { - // Last assignment to n wins - n = len(b) + unix.CmsgLen(4*len(fds)) - b = append(b, unix.UnixRights(fds...)...) - } - // Truncate b - b = b[:n] - - scms, err := unix.ParseSocketControlMessage(b) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != len(testCase) { - t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) - } - for i, scm := range scms { - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("ParseUnixRights: %v", err) - } - wantFds := testCase[i] - if len(gotFds) != len(wantFds) { - t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) - } - for j, fd := range gotFds { - if fd != wantFds[j] { - t.Fatalf("expected fd %v, got %v", wantFds[j], fd) - } - } - } - } -} - -func TestRlimit(t *testing.T) { - var rlimit, zero unix.Rlimit - err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Getrlimit: save failed: %v", err) - } - if zero == rlimit { - t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) - } - set := rlimit - set.Cur = set.Max - 1 - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set) - if err != nil { - t.Fatalf("Setrlimit: set failed: %#v %v", set, err) - } - var get unix.Rlimit - err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get) - if err != nil { - t.Fatalf("Getrlimit: get failed: %v", err) - } - set = rlimit - set.Cur = set.Max - 1 - if set != get { - // Seems like Darwin requires some privilege to - // increase the soft limit of rlimit sandbox, though - // Setrlimit never reports an error. - switch runtime.GOOS { - case "darwin": - default: - t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) - } - } - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) - } -} - -func TestSeekFailure(t *testing.T) { - _, err := unix.Seek(-1, 0, 0) - if err == nil { - t.Fatalf("Seek(-1, 0, 0) did not fail") - } - str := err.Error() // used to crash on Linux - t.Logf("Seek: %v", str) - if str == "" { - t.Fatalf("Seek(-1, 0, 0) return error with empty message") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/image_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/image_test.go deleted file mode 100644 index c7544a643..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/image_test.go +++ /dev/null @@ -1,1018 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "reflect" - "strings" - "testing" - "time" -) - -func newTestClient(rt *FakeRoundTripper) Client { - endpoint := "http://localhost:4243" - u, _ := parseEndpoint("http://localhost:4243", false) - testAPIVersion, _ := NewAPIVersion("1.17") - client := Client{ - HTTPClient: &http.Client{Transport: rt}, - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - SkipServerVersionCheck: true, - serverAPIVersion: testAPIVersion, - } - return client -} - -type stdoutMock struct { - *bytes.Buffer -} - -func (m stdoutMock) Close() error { - return nil -} - -type stdinMock struct { - *bytes.Buffer -} - -func (m stdinMock) Close() error { - return nil -} - -func TestListImages(t *testing.T) { - body := `[ - { - "Repository":"base", - "Tag":"ubuntu-12.10", - "Id":"b750fe79269d", - "Created":1364102658 - }, - { - "Repository":"base", - "Tag":"ubuntu-quantal", - "Id":"b750fe79269d", - "Created":1364102658 - }, - { - "RepoTag": [ - "ubuntu:12.04", - "ubuntu:precise", - "ubuntu:latest" - ], - "Id": "8dbd9e392a964c", - "Created": 1365714795, - "Size": 131506275, - "VirtualSize": 131506275 - }, - { - "RepoTag": [ - "ubuntu:12.10", - "ubuntu:quantal" - ], - "ParentId": "27cf784147099545", - "Id": "b750fe79269d2e", - "Created": 1364102658, - "Size": 24653, - "VirtualSize": 180116135 - } -]` - var expected []APIImages - err := json.Unmarshal([]byte(body), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - images, err := client.ListImages(ListImagesOptions{}) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(images, expected) { - t.Errorf("ListImages: Wrong return value. Want %#v. Got %#v.", expected, images) - } -} - -func TestListImagesParameters(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "null", status: http.StatusOK} - client := newTestClient(fakeRT) - _, err := client.ListImages(ListImagesOptions{All: false}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ListImages({All: false}: Wrong HTTP method. Want GET. Got %s.", req.Method) - } - if all := req.URL.Query().Get("all"); all != "0" && all != "" { - t.Errorf("ListImages({All: false}): Wrong parameter. Want all=0 or not present at all. Got all=%s", all) - } - fakeRT.Reset() - _, err = client.ListImages(ListImagesOptions{All: true}) - if err != nil { - t.Fatal(err) - } - req = fakeRT.requests[0] - if all := req.URL.Query().Get("all"); all != "1" { - t.Errorf("ListImages({All: true}): Wrong parameter. Want all=1. Got all=%s", all) - } - fakeRT.Reset() - _, err = client.ListImages(ListImagesOptions{Filters: map[string][]string{ - "dangling": {"true"}, - }}) - if err != nil { - t.Fatal(err) - } - req = fakeRT.requests[0] - body := req.URL.Query().Get("filters") - var filters map[string][]string - err = json.Unmarshal([]byte(body), &filters) - if err != nil { - t.Fatal(err) - } - if len(filters["dangling"]) != 1 || filters["dangling"][0] != "true" { - t.Errorf("ListImages(dangling=[true]): Wrong filter map. Want dangling=[true], got dangling=%v", filters["dangling"]) - } -} - -func TestImageHistory(t *testing.T) { - body := `[ - { - "Id": "25daec02219d2d852f7526137213a9b199926b4b24e732eab5b8bc6c49bd470e", - "Tags": [ - "debian:7.6", - "debian:latest", - "debian:7", - "debian:wheezy" - ], - "Created": 1409856216, - "CreatedBy": "/bin/sh -c #(nop) CMD [/bin/bash]" - }, - { - "Id": "41026a5347fb5be6ed16115bf22df8569697139f246186de9ae8d4f67c335dce", - "Created": 1409856213, - "CreatedBy": "/bin/sh -c #(nop) ADD file:1ee9e97209d00e3416a4543b23574cc7259684741a46bbcbc755909b8a053a38 in /", - "Size": 85178663 - }, - { - "Id": "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158", - "Tags": [ - "scratch:latest" - ], - "Created": 1371157430 - } -]` - var expected []ImageHistory - err := json.Unmarshal([]byte(body), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - history, err := client.ImageHistory("debian:latest") - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(history, expected) { - t.Errorf("ImageHistory: Wrong return value. Want %#v. Got %#v.", expected, history) - } -} - -func TestRemoveImage(t *testing.T) { - name := "test" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - err := client.RemoveImage(name) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "DELETE" - if req.Method != expectedMethod { - t.Errorf("RemoveImage(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/images/" + name)) - if req.URL.Path != u.Path { - t.Errorf("RemoveImage(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } -} - -func TestRemoveImageNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound}) - err := client.RemoveImage("test:") - if err != ErrNoSuchImage { - t.Errorf("RemoveImage: wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestRemoveImageExtended(t *testing.T) { - name := "test" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - err := client.RemoveImageExtended(name, RemoveImageOptions{Force: true, NoPrune: true}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "DELETE" - if req.Method != expectedMethod { - t.Errorf("RemoveImage(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/images/" + name)) - if req.URL.Path != u.Path { - t.Errorf("RemoveImage(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } - expectedQuery := "force=1&noprune=1" - if query := req.URL.Query().Encode(); query != expectedQuery { - t.Errorf("PushImage: Wrong query string. Want %q. Got %q.", expectedQuery, query) - } -} - -func TestInspectImage(t *testing.T) { - body := `{ - "Id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - "Parent":"27cf784147099545", - "Created":"2013-03-23T22:24:18.818426Z", - "Container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", - "ContainerConfig":{"Memory":1}, - "VirtualSize":12345 -}` - - created, err := time.Parse(time.RFC3339Nano, "2013-03-23T22:24:18.818426Z") - if err != nil { - t.Fatal(err) - } - - expected := Image{ - ID: "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - Parent: "27cf784147099545", - Created: created, - Container: "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", - ContainerConfig: Config{ - Memory: 1, - }, - VirtualSize: 12345, - } - fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(fakeRT) - image, err := client.InspectImage(expected.ID) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*image, expected) { - t.Errorf("InspectImage(%q): Wrong image returned. Want %#v. Got %#v.", expected.ID, expected, *image) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("InspectImage(%q): Wrong HTTP method. Want GET. Got %s.", expected.ID, req.Method) - } - u, _ := url.Parse(client.getURL("/images/" + expected.ID + "/json")) - if req.URL.Path != u.Path { - t.Errorf("InspectImage(%q): Wrong request URL. Want %q. Got %q.", expected.ID, u.Path, req.URL.Path) - } -} - -func TestInspectImageNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound}) - name := "test" - image, err := client.InspectImage(name) - if image != nil { - t.Errorf("InspectImage(%q): expected image, got %#v.", name, image) - } - if err != ErrNoSuchImage { - t.Errorf("InspectImage(%q): wrong error. Want %#v. Got %#v.", name, ErrNoSuchImage, err) - } -} - -func TestPushImage(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - expected := "Pushing 1/100" - if buf.String() != expected { - t.Errorf("PushImage: Wrong output. Want %q. Got %q.", expected, buf.String()) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PushImage: Wrong HTTP method. Want POST. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/images/test/push")) - if req.URL.Path != u.Path { - t.Errorf("PushImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } - if query := req.URL.Query().Encode(); query != "" { - t.Errorf("PushImage: Wrong query string. Want no parameters, got %q.", query) - } - - auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth")) - if err != nil { - t.Errorf("PushImage: caught error decoding auth. %#v", err.Error()) - } - if strings.TrimSpace(string(auth)) != "{}" { - t.Errorf("PushImage: wrong body. Want %q. Got %q.", - base64.URLEncoding.EncodeToString([]byte("{}")), req.Header.Get("X-Registry-Auth")) - } -} - -func TestPushImageWithRawJSON(t *testing.T) { - body := ` - {"status":"Pushing..."} - {"status":"Pushing", "progress":"1/? (n/a)", "progressDetail":{"current":1}}} - {"status":"Image successfully pushed"} - ` - fakeRT := &FakeRoundTripper{ - message: body, - status: http.StatusOK, - header: map[string]string{ - "Content-Type": "application/json", - }, - } - client := newTestClient(fakeRT) - var buf bytes.Buffer - - err := client.PushImage(PushImageOptions{ - Name: "test", - OutputStream: &buf, - RawJSONStream: true, - }, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - if buf.String() != body { - t.Errorf("PushImage: Wrong raw output. Want %q. Got %q.", body, buf.String()) - } -} - -func TestPushImageWithAuthentication(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - inputAuth := AuthConfiguration{ - Username: "gopher", - Password: "gopher123", - Email: "gopher@tsuru.io", - } - err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, inputAuth) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - var gotAuth AuthConfiguration - - auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth")) - if err != nil { - t.Errorf("PushImage: caught error decoding auth. %#v", err.Error()) - } - - err = json.Unmarshal(auth, &gotAuth) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(gotAuth, inputAuth) { - t.Errorf("PushImage: wrong auth configuration. Want %#v. Got %#v.", inputAuth, gotAuth) - } -} - -func TestPushImageCustomRegistry(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var authConfig AuthConfiguration - var buf bytes.Buffer - opts := PushImageOptions{ - Name: "test", Registry: "docker.tsuru.io", - OutputStream: &buf, - } - err := client.PushImage(opts, authConfig) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedQuery := "registry=docker.tsuru.io" - if query := req.URL.Query().Encode(); query != expectedQuery { - t.Errorf("PushImage: Wrong query string. Want %q. Got %q.", expectedQuery, query) - } -} - -func TestPushImageNoName(t *testing.T) { - client := Client{} - err := client.PushImage(PushImageOptions{}, AuthConfiguration{}) - if err != ErrNoSuchImage { - t.Errorf("PushImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestPullImage(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - err := client.PullImage(PullImageOptions{Repository: "base", OutputStream: &buf}, - AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - expected := "Pulling 1/100" - if buf.String() != expected { - t.Errorf("PullImage: Wrong output. Want %q. Got %q.", expected, buf.String()) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PullImage: Wrong HTTP method. Want POST. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/images/create")) - if req.URL.Path != u.Path { - t.Errorf("PullImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQuery := "fromImage=base" - if query := req.URL.Query().Encode(); query != expectedQuery { - t.Errorf("PullImage: Wrong query strin. Want %q. Got %q.", expectedQuery, query) - } -} - -func TestPullImageWithRawJSON(t *testing.T) { - body := ` - {"status":"Pulling..."} - {"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}} - ` - fakeRT := &FakeRoundTripper{ - message: body, - status: http.StatusOK, - header: map[string]string{ - "Content-Type": "application/json", - }, - } - client := newTestClient(fakeRT) - var buf bytes.Buffer - err := client.PullImage(PullImageOptions{ - Repository: "base", - OutputStream: &buf, - RawJSONStream: true, - }, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - if buf.String() != body { - t.Errorf("PullImage: Wrong raw output. Want %q. Got %q", body, buf.String()) - } -} - -func TestPullImageWithoutOutputStream(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := PullImageOptions{ - Repository: "base", - Registry: "docker.tsuru.io", - } - err := client.PullImage(opts, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestPullImageCustomRegistry(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := PullImageOptions{ - Repository: "base", - Registry: "docker.tsuru.io", - OutputStream: &buf, - } - err := client.PullImage(opts, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestPullImageTag(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := PullImageOptions{ - Repository: "base", - Registry: "docker.tsuru.io", - Tag: "latest", - OutputStream: &buf, - } - err := client.PullImage(opts, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}, "tag": {"latest"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestPullImageNoRepository(t *testing.T) { - var opts PullImageOptions - client := Client{} - err := client.PullImage(opts, AuthConfiguration{}) - if err != ErrNoSuchImage { - t.Errorf("PullImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestImportImageFromUrl(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := ImportImageOptions{ - Source: "http://mycompany.com/file.tar", - Repository: "testimage", - Tag: "tag", - OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestImportImageFromInput(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - in := bytes.NewBufferString("tar content") - var buf bytes.Buffer - opts := ImportImageOptions{ - Source: "-", Repository: "testimage", - InputStream: in, OutputStream: &buf, - Tag: "tag", - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } - body, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("ImportImage: caugth error while reading body %#v", err.Error()) - } - e := "tar content" - if string(body) != e { - t.Errorf("ImportImage: wrong body. Want %#v. Got %#v.", e, string(body)) - } -} - -func TestImportImageDoesNotPassesInputIfSourceIsNotDash(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - in := bytes.NewBufferString("foo") - opts := ImportImageOptions{ - Source: "http://test.com/container.tar", Repository: "testimage", - InputStream: in, OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } - body, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("ImportImage: caugth error while reading body %#v", err.Error()) - } - if string(body) != "" { - t.Errorf("ImportImage: wrong body. Want nothing. Got %#v.", string(body)) - } -} - -func TestImportImageShouldPassTarContentToBodyWhenSourceIsFilePath(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - tarPath := "testing/data/container.tar" - opts := ImportImageOptions{ - Source: tarPath, Repository: "testimage", - OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - tar, err := os.Open(tarPath) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - tarContent, err := ioutil.ReadAll(tar) - body, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tarContent, body) { - t.Errorf("ImportImage: wrong body. Want %#v content. Got %#v.", tarPath, body) - } -} - -func TestImportImageShouldChangeSourceToDashWhenItsAFilePath(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - tarPath := "testing/data/container.tar" - opts := ImportImageOptions{ - Source: tarPath, Repository: "testimage", - OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {"-"}, "repo": {opts.Repository}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestBuildImageParameters(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - Pull: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - Memory: 1024, - Memswap: 2048, - CPUShares: 10, - CPUQuota: 7500, - CPUPeriod: 100000, - CPUSetCPUs: "0-3", - Ulimits: []ULimit{{Name: "nofile", Soft: 100, Hard: 200}}, - InputStream: &buf, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != nil && strings.Index(err.Error(), "build image fail") == -1 { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{ - "t": {opts.Name}, - "nocache": {"1"}, - "q": {"1"}, - "pull": {"1"}, - "rm": {"1"}, - "forcerm": {"1"}, - "memory": {"1024"}, - "memswap": {"2048"}, - "cpushares": {"10"}, - "cpuquota": {"7500"}, - "cpuperiod": {"100000"}, - "cpusetcpus": {"0-3"}, - "ulimits": {"[{\"Name\":\"nofile\",\"Soft\":100,\"Hard\":200}]"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestBuildImageParametersForRemoteBuild(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - Remote: "testing/data/container.tar", - SuppressOutput: true, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"t": {opts.Name}, "remote": {opts.Remote}, "q": {"1"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestBuildImageMissingRepoAndNilInput(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - SuppressOutput: true, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != ErrMissingRepo { - t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingRepo, err) - } -} - -func TestBuildImageMissingOutputStream(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := BuildImageOptions{Name: "testImage"} - err := client.BuildImage(opts) - if err != ErrMissingOutputStream { - t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingOutputStream, err) - } -} - -func TestBuildImageWithRawJSON(t *testing.T) { - body := ` - {"stream":"Step 0 : FROM ubuntu:latest\n"} - {"stream":" ---\u003e 4300eb9d3c8d\n"} - {"stream":"Step 1 : MAINTAINER docker \n"} - {"stream":" ---\u003e Using cache\n"} - {"stream":" ---\u003e 3a3ed758c370\n"} - {"stream":"Step 2 : CMD /usr/bin/top\n"} - {"stream":" ---\u003e Running in 36b1479cc2e4\n"} - {"stream":" ---\u003e 4b6188aebe39\n"} - {"stream":"Removing intermediate container 36b1479cc2e4\n"} - {"stream":"Successfully built 4b6188aebe39\n"} - ` - fakeRT := &FakeRoundTripper{ - message: body, - status: http.StatusOK, - header: map[string]string{ - "Content-Type": "application/json", - }, - } - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - RmTmpContainer: true, - InputStream: &buf, - OutputStream: &buf, - RawJSONStream: true, - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - if buf.String() != body { - t.Errorf("BuildImage: Wrong raw output. Want %q. Got %q.", body, buf.String()) - } -} - -func TestBuildImageRemoteWithoutName(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Remote: "testing/data/container.tar", - SuppressOutput: true, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"t": {opts.Remote}, "remote": {opts.Remote}, "q": {"1"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestTagImageParameters(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := TagImageOptions{Repo: "testImage"} - err := client.TagImage("base", opts) - if err != nil && strings.Index(err.Error(), "tag image fail") == -1 { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := "http://localhost:4243/images/base/tag?repo=testImage" - got := req.URL.String() - if !reflect.DeepEqual(got, expected) { - t.Errorf("TagImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestTagImageMissingRepo(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := TagImageOptions{Repo: "testImage"} - err := client.TagImage("", opts) - if err != ErrNoSuchImage { - t.Errorf("TestTag: wrong error returned. Want %#v. Got %#v.", - ErrNoSuchImage, err) - } -} - -func TestIsUrl(t *testing.T) { - url := "http://foo.bar/" - result := isURL(url) - if !result { - t.Errorf("isURL: wrong match. Expected %#v to be a url. Got %#v.", url, result) - } - url = "/foo/bar.tar" - result = isURL(url) - if result { - t.Errorf("isURL: wrong match. Expected %#v to not be a url. Got %#v", url, result) - } -} - -func TestLoadImage(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - tar, err := os.Open("testing/data/container.tar") - if err != nil { - t.Fatal(err) - } else { - defer tar.Close() - } - opts := LoadImageOptions{InputStream: tar} - err = client.LoadImage(opts) - if nil != err { - t.Error(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("LoadImage: wrong method. Expected %q. Got %q.", "POST", req.Method) - } - if req.URL.Path != "/images/load" { - t.Errorf("LoadImage: wrong URL. Expected %q. Got %q.", "/images/load", req.URL.Path) - } -} - -func TestExportImage(t *testing.T) { - var buf bytes.Buffer - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := ExportImageOptions{Name: "testimage", OutputStream: &buf} - err := client.ExportImage(opts) - if nil != err { - t.Error(err) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ExportImage: wrong method. Expected %q. Got %q.", "GET", req.Method) - } - expectedPath := "/images/testimage/get" - if req.URL.Path != expectedPath { - t.Errorf("ExportIMage: wrong path. Expected %q. Got %q.", expectedPath, req.URL.Path) - } -} - -func TestExportImages(t *testing.T) { - var buf bytes.Buffer - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := ExportImagesOptions{Names: []string{"testimage1", "testimage2:latest"}, OutputStream: &buf} - err := client.ExportImages(opts) - if nil != err { - t.Error(err) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ExportImage: wrong method. Expected %q. Got %q.", "GET", req.Method) - } - expected := "http://localhost:4243/images/get?names=testimage1&names=testimage2%3Alatest" - got := req.URL.String() - if !reflect.DeepEqual(got, expected) { - t.Errorf("ExportIMage: wrong path. Expected %q. Got %q.", expected, got) - } -} - -func TestExportImagesNoNames(t *testing.T) { - var buf bytes.Buffer - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := ExportImagesOptions{Names: []string{}, OutputStream: &buf} - err := client.ExportImages(opts) - if err == nil { - t.Error("Expected an error") - } - if err != ErrMustSpecifyNames { - t.Error(err) - } -} - -func TestSearchImages(t *testing.T) { - body := `[ - { - "description":"A container with Cassandra 2.0.3", - "is_official":true, - "is_automated":true, - "name":"poklet/cassandra", - "star_count":17 - }, - { - "description":"A container with Cassandra 2.0.3", - "is_official":true, - "is_automated":false, - "name":"poklet/cassandra", - "star_count":17 - } - , - { - "description":"A container with Cassandra 2.0.3", - "is_official":false, - "is_automated":true, - "name":"poklet/cassandra", - "star_count":17 - } -]` - var expected []APIImageSearch - err := json.Unmarshal([]byte(body), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - result, err := client.SearchImages("cassandra") - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("SearchImages: Wrong return value. Want %#v. Got %#v.", expected, result) - } -} - -func TestSearchImagesEx(t *testing.T) { - body := `[ - { - "description":"A container with Cassandra 2.0.3", - "is_official":true, - "is_automated":true, - "name":"poklet/cassandra", - "star_count":17 - }, - { - "description":"A container with Cassandra 2.0.3", - "is_official":true, - "is_automated":false, - "name":"poklet/cassandra", - "star_count":17 - } - , - { - "description":"A container with Cassandra 2.0.3", - "is_official":false, - "is_automated":true, - "name":"poklet/cassandra", - "star_count":17 - } -]` - var expected []APIImageSearch - err := json.Unmarshal([]byte(body), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - auth := AuthConfiguration{} - result, err := client.SearchImagesEx("cassandra", auth) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("SearchImages: Wrong return value. Want %#v. Got %#v.", expected, result) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/integration_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/integration_test.go deleted file mode 100644 index f5aeea27a..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/integration_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build docker_integration - -package docker - -import ( - "bytes" - "os" - "testing" -) - -var dockerEndpoint string - -func init() { - dockerEndpoint = os.Getenv("DOCKER_HOST") - if dockerEndpoint == "" { - dockerEndpoint = "unix:///var/run/docker.sock" - } -} - -func TestIntegrationPullCreateStartLogs(t *testing.T) { - imageName := pullImage(t) - client := getClient() - hostConfig := HostConfig{PublishAllPorts: true} - createOpts := CreateContainerOptions{ - Config: &Config{ - Image: imageName, - Cmd: []string{"cat", "/home/gopher/file.txt"}, - User: "gopher", - }, - HostConfig: &hostConfig, - } - container, err := client.CreateContainer(createOpts) - if err != nil { - t.Fatal(err) - } - err = client.StartContainer(container.ID, &hostConfig) - if err != nil { - t.Fatal(err) - } - status, err := client.WaitContainer(container.ID) - if err != nil { - t.Error(err) - } - if status != 0 { - t.Error("WaitContainer(%q): wrong status. Want 0. Got %d", container.ID, status) - } - var stdout, stderr bytes.Buffer - logsOpts := LogsOptions{ - Container: container.ID, - OutputStream: &stdout, - ErrorStream: &stderr, - Stdout: true, - Stderr: true, - } - err = client.Logs(logsOpts) - if err != nil { - t.Error(err) - } - if stderr.String() != "" { - t.Errorf("Got unexpected stderr from logs: %q", stderr.String()) - } - expected := `Welcome to reality, wake up and rejoice -Welcome to reality, you've made the right choice -Welcome to reality, and let them hear your voice, shout it out! -` - if stdout.String() != expected { - t.Errorf("Got wrong stdout from logs.\nWant:\n%#v.\n\nGot:\n%#v.", expected, stdout.String()) - } -} - -func pullImage(t *testing.T) string { - imageName := "fsouza/go-dockerclient-integration" - var buf bytes.Buffer - pullOpts := PullImageOptions{ - Repository: imageName, - OutputStream: &buf, - } - client := getClient() - err := client.PullImage(pullOpts, AuthConfiguration{}) - if err != nil { - t.Logf("Pull output: %s", buf.String()) - t.Fatal(err) - } - return imageName -} - -func getClient() *Client { - client, _ := NewClient(dockerEndpoint) - return client -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/misc_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/misc_test.go deleted file mode 100644 index ceaf076ed..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/misc_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "net/http" - "net/url" - "reflect" - "sort" - "testing" -) - -type DockerVersion struct { - Version string - GitCommit string - GoVersion string -} - -func TestVersion(t *testing.T) { - body := `{ - "Version":"0.2.2", - "GitCommit":"5a2a5cc+CHANGES", - "GoVersion":"go1.0.3" -}` - fakeRT := FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(&fakeRT) - expected := DockerVersion{ - Version: "0.2.2", - GitCommit: "5a2a5cc+CHANGES", - GoVersion: "go1.0.3", - } - version, err := client.Version() - if err != nil { - t.Fatal(err) - } - - if result := version.Get("Version"); result != expected.Version { - t.Errorf("Version(): Wrong result. Want %#v. Got %#v.", expected.Version, version.Get("Version")) - } - if result := version.Get("GitCommit"); result != expected.GitCommit { - t.Errorf("GitCommit(): Wrong result. Want %#v. Got %#v.", expected.GitCommit, version.Get("GitCommit")) - } - if result := version.Get("GoVersion"); result != expected.GoVersion { - t.Errorf("GoVersion(): Wrong result. Want %#v. Got %#v.", expected.GoVersion, version.Get("GoVersion")) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("Version(): wrong request method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/version")) - if req.URL.Path != u.Path { - t.Errorf("Version(): wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestVersionError(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "internal error", status: http.StatusInternalServerError} - client := newTestClient(fakeRT) - version, err := client.Version() - if version != nil { - t.Errorf("Version(): expected value, got %#v.", version) - } - if err == nil { - t.Error("Version(): unexpected error") - } -} - -func TestInfo(t *testing.T) { - body := `{ - "Containers":11, - "Images":16, - "Debug":0, - "NFd":11, - "NGoroutines":21, - "MemoryLimit":1, - "SwapLimit":0 -}` - fakeRT := FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(&fakeRT) - expected := Env{} - expected.SetInt("Containers", 11) - expected.SetInt("Images", 16) - expected.SetBool("Debug", false) - expected.SetInt("NFd", 11) - expected.SetInt("NGoroutines", 21) - expected.SetBool("MemoryLimit", true) - expected.SetBool("SwapLimit", false) - info, err := client.Info() - if err != nil { - t.Fatal(err) - } - infoSlice := []string(*info) - expectedSlice := []string(expected) - sort.Strings(infoSlice) - sort.Strings(expectedSlice) - if !reflect.DeepEqual(expectedSlice, infoSlice) { - t.Errorf("Info(): Wrong result.\nWant %#v.\nGot %#v.", expected, *info) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("Info(): Wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/info")) - if req.URL.Path != u.Path { - t.Errorf("Info(): Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestInfoError(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "internal error", status: http.StatusInternalServerError} - client := newTestClient(fakeRT) - version, err := client.Info() - if version != nil { - t.Errorf("Info(): expected value, got %#v.", version) - } - if err == nil { - t.Error("Info(): unexpected error") - } -} - -func TestParseRepositoryTag(t *testing.T) { - var tests = []struct { - input string - expectedRepo string - expectedTag string - }{ - { - "localhost.localdomain:5000/samalba/hipache:latest", - "localhost.localdomain:5000/samalba/hipache", - "latest", - }, - { - "localhost.localdomain:5000/samalba/hipache", - "localhost.localdomain:5000/samalba/hipache", - "", - }, - { - "tsuru/python", - "tsuru/python", - "", - }, - { - "tsuru/python:2.7", - "tsuru/python", - "2.7", - }, - } - for _, tt := range tests { - repo, tag := ParseRepositoryTag(tt.input) - if repo != tt.expectedRepo { - t.Errorf("ParseRepositoryTag(%q): wrong repository. Want %q. Got %q", tt.input, tt.expectedRepo, repo) - } - if tag != tt.expectedTag { - t.Errorf("ParseRepositoryTag(%q): wrong tag. Want %q. Got %q", tt.input, tt.expectedTag, tag) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/network_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/network_test.go deleted file mode 100644 index 2bff70fe4..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/network_test.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/json" - "net/http" - "net/url" - "reflect" - "testing" -) - -func TestListNetworks(t *testing.T) { - jsonNetworks := `[ - { - "ID": "8dfafdbc3a40", - "Name": "blah", - "Type": "bridge", - "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}] - }, - { - "ID": "9fb1e39c", - "Name": "foo", - "Type": "bridge", - "Endpoints":[{"ID": "c080be979dda", "Name": "lllll2222", "Network": "9fb1e39c"}] - } -]` - var expected []Network - err := json.Unmarshal([]byte(jsonNetworks), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: jsonNetworks, status: http.StatusOK}) - containers, err := client.ListNetworks() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(containers, expected) { - t.Errorf("ListNetworks: Expected %#v. Got %#v.", expected, containers) - } -} - -func TestNetworkInfo(t *testing.T) { - jsonNetwork := `{ - "ID": "8dfafdbc3a40", - "Name": "blah", - "Type": "bridge", - "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}] - }` - var expected Network - err := json.Unmarshal([]byte(jsonNetwork), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonNetwork, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "8dfafdbc3a40" - network, err := client.NetworkInfo(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*network, expected) { - t.Errorf("NetworkInfo(%q): Expected %#v. Got %#v.", id, expected, network) - } - expectedURL, _ := url.Parse(client.getURL("/networks/8dfafdbc3a40")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("NetworkInfo(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestNetworkCreate(t *testing.T) { - jsonID := `{"ID": "8dfafdbc3a40"}` - jsonNetwork := `{ - "ID": "8dfafdbc3a40", - "Name": "foobar", - "Driver": "bridge" - }` - var expected Network - err := json.Unmarshal([]byte(jsonNetwork), &expected) - if err != nil { - t.Fatal(err) - } - - client := newTestClient(&FakeRoundTripper{message: jsonID, status: http.StatusOK}) - opts := CreateNetworkOptions{"foobar", false, "bridge", IPAMOptions{}, nil} - network, err := client.CreateNetwork(opts) - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(*network, expected) { - t.Errorf("CreateNetwork: Expected %#v. Got %#v.", expected, network) - } -} - -func TestNetworkRemove(t *testing.T) { - id := "8dfafdbc3a40" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - err := client.RemoveNetwork(id) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "DELETE" - if req.Method != expectedMethod { - t.Errorf("RemoveNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/networks/" + id)) - if req.URL.Path != u.Path { - t.Errorf("RemoveNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path) - } -} - -func TestNetworkConnect(t *testing.T) { - id := "8dfafdbc3a40" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - opts := NetworkConnectionOptions{"foobar"} - err := client.ConnectNetwork(id, opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "POST" - if req.Method != expectedMethod { - t.Errorf("ConnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/networks/" + id + "/connect")) - if req.URL.Path != u.Path { - t.Errorf("ConnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path) - } -} - -func TestNetworkConnectNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound}) - opts := NetworkConnectionOptions{"foobar"} - err := client.ConnectNetwork("8dfafdbc3a40", opts) - if serr, ok := err.(*NoSuchNetworkOrContainer); !ok { - t.Errorf("ConnectNetwork: wrong error type: %s.", serr) - } -} - -func TestNetworkDisconnect(t *testing.T) { - id := "8dfafdbc3a40" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - opts := NetworkConnectionOptions{"foobar"} - err := client.DisconnectNetwork(id, opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "POST" - if req.Method != expectedMethod { - t.Errorf("DisconnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/networks/" + id + "/disconnect")) - if req.URL.Path != u.Path { - t.Errorf("DisconnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path) - } -} - -func TestNetworkDisconnectNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound}) - opts := NetworkConnectionOptions{"foobar"} - err := client.DisconnectNetwork("8dfafdbc3a40", opts) - if serr, ok := err.(*NoSuchNetworkOrContainer); !ok { - t.Errorf("DisconnectNetwork: wrong error type: %s.", serr) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/.dockerignore b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/.dockerignore deleted file mode 100644 index 027e8c20e..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -container.tar -dockerfile.tar -foofile diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/Dockerfile b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/Dockerfile deleted file mode 100644 index 0948dcfa8..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/Dockerfile +++ /dev/null @@ -1,15 +0,0 @@ -# this file describes how to build tsuru python image -# to run it: -# 1- install docker -# 2- run: $ docker build -t tsuru/python https://raw.github.com/tsuru/basebuilder/master/python/Dockerfile - -from base:ubuntu-quantal -run apt-get install wget -y --force-yes -run wget http://github.com/tsuru/basebuilder/tarball/master -O basebuilder.tar.gz --no-check-certificate -run mkdir /var/lib/tsuru -run tar -xvf basebuilder.tar.gz -C /var/lib/tsuru --strip 1 -run cp /var/lib/tsuru/python/deploy /var/lib/tsuru -run cp /var/lib/tsuru/base/restart /var/lib/tsuru -run cp /var/lib/tsuru/base/start /var/lib/tsuru -run /var/lib/tsuru/base/install -run /var/lib/tsuru/base/setup diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/barfile b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/barfile deleted file mode 100644 index e69de29bb..000000000 diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/ca.pem b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/ca.pem deleted file mode 100644 index 8e38bba13..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/ca.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC1TCCAb+gAwIBAgIQJ9MsNxrUxumNbAytGi3GEDALBgkqhkiG9w0BAQswFjEU -MBIGA1UEChMLQm9vdDJEb2NrZXIwHhcNMTQxMDE2MjAyMTM4WhcNMTcwOTMwMjAy -MTM4WjAWMRQwEgYDVQQKEwtCb290MkRvY2tlcjCCASIwDQYJKoZIhvcNAQEBBQAD -ggEPADCCAQoCggEBALpFCSARjG+5yXoqr7UMzuE0df7RRZfeRZI06lJ02ZqV4Iii -rgL7ML9yPxX50NbLnjiilSDTUhnyocYFItokzUzz8qpX/nlYhuN2Iqwh4d0aWS8z -f5y248F+H1z+HY2W8NPl/6DVlVwYaNW1/k+RPMlHS0INLR6j+3Ievew7RNE0NnM2 -znELW6NetekDt3GUcz0Z95vDUDfdPnIk1eIFMmYvLxZh23xOca4Q37a3S8F3d+dN -+OOpwjdgY9Qme0NQUaXpgp58jWuQfB8q7mZrdnLlLqRa8gx1HeDSotX7UmWtWPkb -vd9EdlKLYw5PVpxMV1rkwf2t4TdgD5NfkpXlXkkCAwEAAaMjMCEwDgYDVR0PAQH/ -BAQDAgCkMA8GA1UdEwEB/wQFMAMBAf8wCwYJKoZIhvcNAQELA4IBAQBxYjHVSKqE -MJw7CW0GddesULtXXVWGJuZdWJLQlPvPMfIfjIvlcZyS4cdVNiQ3sREFIZz8TpII -CT0/Pg3sgv/FcOQe1CN0xZYZcyiAZHK1z0fJQq2qVpdv7+tJcjI2vvU6NI24iQCo -W1wz25trJz9QbdB2MRLMjyz7TSWuafztIvcfEzaIdQ0Whqund/cSuPGQx5IwF83F -rvlkOyJSH2+VIEBTCIuykJeL0DLTt8cePBQR5L1ISXb4RUMK9ZtqRscBRv8sn7o2 -ixG3wtL0gYF4xLtsQWVxI3iFVrU3WzOH/3c5shVRkWBd+AQRSwCJI4mKH7penJCF -i3/zzlkvOnjV ------END CERTIFICATE----- diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/cert.pem b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/cert.pem deleted file mode 100644 index 5e7244b24..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/cert.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC6DCCAdKgAwIBAgIRANO6ymxQAjp66KmEka1G6b0wCwYJKoZIhvcNAQELMBYx -FDASBgNVBAoTC0Jvb3QyRG9ja2VyMB4XDTE0MTAxNjIwMjE1MloXDTE3MDkzMDIw -MjE1MlowFjEUMBIGA1UEChMLQm9vdDJEb2NrZXIwggEiMA0GCSqGSIb3DQEBAQUA -A4IBDwAwggEKAoIBAQDGA1mAhSOpZspD1dpZ7qVEQrIJw4Xo8252jHaORnEdDiFm -b6brEmr6jw8t4P3IGxbqBc/TqRV+SSXxwYEVvfpeQKH+SmqStoMNtD3Ura161az4 -V0BcxMtSlsUGpoz+//QCAq8qiaxMwgiyc5253mkQm88anj2cNt7xbewiu/KFWuf7 -BVpNK1+ltpJmlukfcj/G+I1bw7j1KxBjDrFqe5cyDuuZcDL2tmUXP/ZWDyXwSv+H -AOckqn44z6aXlBkVvOXDBZJqY76d/vWVDNCuZeXRnqlhP3t1kH4V0RQXo+JD2tgt -JgdU0unzyoFOSWNUBPm73tqmjUGGAmGHBmeegJr/AgMBAAGjNTAzMA4GA1UdDwEB -/wQEAwIAgDATBgNVHSUEDDAKBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMAsGCSqG -SIb3DQEBCwOCAQEABVTWl5SmBP+j5He5bQsgnIXjviSKqe40/10V4LJAOmilycRF -zLrzM+YMwfjg6PLIs8CldAMWHw9y9ktZY4MxkgCktaiaN/QmMTMwFWEcN4wy5IpM -U5l93eAg7xsnY430h3QBBADujX4wdF3fs8rSL8zAAQFL0ihurwU124K3yXKsrwpb -CiVUGfIN4sPwjy8Ws9oxHFDC9/P8lgjHZ1nBIf8KSHnMzlxDGj7isQfhtH+7mcCL -cM1qO2NirS2v7uaEPPY+MJstAz+W7EJCW9dfMSmHna2SDC37Xkin7uEY9z+qaKFL -8d/XxOB/L8Ucy8VZhdsv0dsBq5KfJntITM0ksQ== ------END CERTIFICATE----- diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/container.tar b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/container.tar deleted file mode 100644 index e4b066e3b..000000000 Binary files a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/container.tar and /dev/null differ diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/dockerfile.tar b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/dockerfile.tar deleted file mode 100644 index 32c9ce647..000000000 Binary files a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/dockerfile.tar and /dev/null differ diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/foofile b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/foofile deleted file mode 100644 index e69de29bb..000000000 diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/key.pem b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/key.pem deleted file mode 100644 index a9346bcf4..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAxgNZgIUjqWbKQ9XaWe6lREKyCcOF6PNudox2jkZxHQ4hZm+m -6xJq+o8PLeD9yBsW6gXP06kVfkkl8cGBFb36XkCh/kpqkraDDbQ91K2tetWs+FdA -XMTLUpbFBqaM/v/0AgKvKomsTMIIsnOdud5pEJvPGp49nDbe8W3sIrvyhVrn+wVa -TStfpbaSZpbpH3I/xviNW8O49SsQYw6xanuXMg7rmXAy9rZlFz/2Vg8l8Er/hwDn -JKp+OM+ml5QZFbzlwwWSamO+nf71lQzQrmXl0Z6pYT97dZB+FdEUF6PiQ9rYLSYH -VNLp88qBTkljVAT5u97apo1BhgJhhwZnnoCa/wIDAQABAoIBAQCaGy9EC9pmU95l -DwGh7k5nIrUnTilg1FwLHWSDdCVCZKXv8ENrPelOWZqJrUo1u4eI2L8XTsewgkNq -tJu/DRzWz9yDaO0qg6rZNobMh+K076lvmZA44twOydJLS8H+D7ua+PXU2FLlZjmY -kMyXRJZmW6zCXZc7haTbJx6ZJccoquk/DkS4FcFurJP177u1YrWS9TTw9kensUtU -jQ63uf56UTN1i+0+Rxl7OW1TZlqwlri5I4njg5249+FxwwHzIq8+l7zD7K9pl8c/ -nG1HuulvU2bVlDlRdyslMPAH34vw9Sku1BD8furrJLr1na5lRSLKJODEaIPEsLwv -CdEUwP9JAoGBAO76ZW80RyNB2fA+wbTq70Sr8CwrXxYemXrez5LKDC7SsohKFCPE -IedpO/n+nmymiiJvMm874EExoG6BVrbkWkeb+2vinEfOQNlDMsDx7WLjPekP3t6i -rXHO3CjFooVFq2z3mZa/Nc5NZqu8fNWNCKJxZDJphdoj6sORNJIUvZVjAoGBANQd -++J+ITcu3/+A6JrGcgLunBFQYPqkiItk0J4QKYKuX5ik9rWcQDN8TTtfW2mDuiQ4 -NrCwuVPq1V1kB16JzH017SsYLo9g8I20YjnBZge9pKTeUaLVTb3C50LW8FBylop0 -Bnm597dNbtSjphjoTMg0XyC19o3Esf2YeWG0QNS1AoGAWWDfFRNJU99qIldmXULM -0DM6NVrXSk+ReYnhunXEzrJQwXZrR+EwCPurydk36Uz0NuK9yypquhdUeF/5TZfk -SAoHo5byekyipl9imRUigqyY2BTudvgCxKDoaHtaSFwBPFTyZZYICquaLbrmOXxw -8UhVgCFFRYvPXuts7QHC0h8CgYBWEvy9gfU0kV7wLX02IUTuj6jhFb7ktpN6DSTi -nyhZES1VoctDEu6ydcRZTW6ouH12aSE4Pd5WgTqntQmQgVZrkNB25k8ue2Xh+srJ -KQOgLIJ9LIHwE6KCWG7DnrjRzE3uTPq7to0g4tkQjH/AJ7PQof/gJDayfJjFkXPg -A+cy6QKBgEPbKpiqscm03gT2QanBut5pg4dqPOxp0SlErA3kSFNTRK3oYBQPC+LH -qA5nD5brdkeNBB58Rll8Zpzxiff50bcvLP/7/Sb3NjaXFTEY0gVbdRof3n6N0YP3 -Hu5XDNJ9RNkNzE5RIG1g86KE+aKlcrKMaigqAiuIy2PSnjkQeGk8 ------END RSA PRIVATE KEY----- diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/server.pem b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/server.pem deleted file mode 100644 index 89cc445e1..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/server.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC/DCCAeagAwIBAgIQMUILcXtvmSOK63zEBo0VXzALBgkqhkiG9w0BAQswFjEU -MBIGA1UEChMLQm9vdDJEb2NrZXIwHhcNMTQxMDE2MjAyMTQ2WhcNMTcwOTMwMjAy -MTQ2WjAWMRQwEgYDVQQKEwtCb290MkRvY2tlcjCCASIwDQYJKoZIhvcNAQEBBQAD -ggEPADCCAQoCggEBANxUOUhNnqFnrTlLsBYzfFRZWQo268l+4K4lOJCVbfDonP3g -Mz0vGi9fcyFqEWSA8Y+ShXna625HTnReCwFdsu0861qCIq7v95hFFCyOe0iIxpd0 -AKLnl90d+1vonE7andgFgoobbTiMly4UK4H6z8D148fFNIihoteOG3PIF89TFxP7 -CJ/3wXnx/IKpdlO8PAnub3tBPJHvGDj7KORLy4IBxRX5VBAdfGNybE66fcrehEva -rLA4m9pgiaR/Nnr9FdKhPyqYdjflLNvzydxNvMIV4M0hFlhXmYvpMjA5/XsTnsyV -t9JHJa5Upwqsbne08t7rsm7liZNxZlko8xPOTQcCAwEAAaNKMEgwDgYDVR0PAQH/ -BAQDAgCgMAwGA1UdEwEB/wQCMAAwKAYDVR0RBCEwH4ILYm9vdDJkb2NrZXKHBH8A -AAGHBAoAAg+HBMCoO2cwCwYJKoZIhvcNAQELA4IBAQAYoYcDkDWkl73FZ0WnPmAj -LiF7HU95Qg3KyEpFsAJeShSLPPbQntmwhdekEzY4tQ3eKQB/+zHFjzsCr/lmDUmH -Ea/ryQ17C+jyH+Ykg0IWW6L6veZhvRDg6Z9focVtPVBRxPTqC/Qhb54blWRASV+W -UreMuXQ5+1dQptAM7ixOeLVHjBi/bd9TL3jvwBVCr9QedteMjjK4TCF9Tbcou+MF -2w3OJJZMDhcD+YwoK9uJDqlKmcTm/vVMbSsp/pTMcnQ7jxCeR8/XyX+VwTZwaHAa -o92Q/eg3THAiWhvyT/SzyH9dHHBAyXynUwGCggKawHktfvW4QXRPuLxLrJ7iB5cy ------END CERTIFICATE----- diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem deleted file mode 100644 index c897e5da5..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEoAIBAAKCAQEA3FQ5SE2eoWetOUuwFjN8VFlZCjbryX7griU4kJVt8Oic/eAz -PS8aL19zIWoRZIDxj5KFedrrbkdOdF4LAV2y7TzrWoIiru/3mEUULI57SIjGl3QA -oueX3R37W+icTtqd2AWCihttOIyXLhQrgfrPwPXjx8U0iKGi144bc8gXz1MXE/sI -n/fBefH8gql2U7w8Ce5ve0E8ke8YOPso5EvLggHFFflUEB18Y3JsTrp9yt6ES9qs -sDib2mCJpH82ev0V0qE/Kph2N+Us2/PJ3E28whXgzSEWWFeZi+kyMDn9exOezJW3 -0kclrlSnCqxud7Ty3uuybuWJk3FmWSjzE85NBwIDAQABAoIBAG0ak+cW8LeShHf7 -3+2Of0GxoOLrAWWdG5uAuPr31CJYve0FybnBimDtDjD8ujIfm/7xmoEWBEFutA3x -x9dcU88gvJbsHEqub9gKVQwfXjMz78tt2SbSMiR/xUnk7QorPcCMMfE71aEMFYzu -1gCed6Rg3vO81t/V0rKVH0j9S7UQz5v/oX15eVDV5LOqyCHwAi6K0eXXbqnbI0TH -SOQ/nexM2msVXWbO9t6ra6f5V7FXziDK5Xi+rPxRbX9mkrDzxDAevfuRqYBx5vtL -W2Q2hKjUAHFgXFniNSZBS7dCdAtz0el/3ct+cNmpuTMhhs7M6wC1CuYiZ/DxLiFh -Si73VckCgYEA+/ceh3+VjtQ0rgEw8sD9bqYEA8IaBiObjneIoFnKBYRG7yZd8JMm -HD4M/aQ1qhcRLPN7GR03YQULgQJURbKSjJHnhfTXHyeHC3NN4gMVHQXewu2MHCh6 -7FCQ9CfK0KcYLgegVVvL3PrF3hyWGnmTu+G0UkDQRYVnaNrB7snrW6UCgYEA39tq -+MCQdu0moJ5szSZf02undg9EeW6isk9qzi7TId3/MLci2eH7PEnipipPUK3+DERq -aba0y0TKgBR2EXvXLFJA/+kfdo2loIEHOfox85HVfxgUaFRti63ZI0uF8D0QT2Yy -oJal+RFghVoSnv4LjhRKEPbIkScTXGjdK+7wFjsCfz79iKRXQQx0ALd/lL0bgkAn -QNmvrNHcFQeI2p8700WNzC39aX67SsvEt3qxkrjzC1gxhpTAuReIK1gVPPwvqHN8 -BmV20FD5kMlMCix2mNCopwgUWvKvLAvoGFTxncKMA39+aJbuXAjiqJTekKgNvOE7 -i9kEWw0GTNPp3JHV6QECgYAPwb0M11kT1euDIMOdyRazpf86kyaJuZzgGjD1ZFxe -JOcigbGFTp/FhZnbglzk2+pm6KXo3QBq0mPCki4hWusxZnTGzpz1VlETNCHTFeZQ -M7KoaIR/N3oie9Et59H8r/+m5xWnMhNqratyl316DX24uXrhKM3DUdHODl+LCR2D -IwKBgE1MbHuwolUPEw3HeO4R7NMFVTFei7E/fpUsimPfArGg8UydwvloNT1myJos -N2JzfGGjN2KPVcBk9fOs71mJ6VcK3C3g5JIccplk6h9VNaw55+zdQvKPTzoBoTvy -A+Fwx2AlF61KeRF87DL2YTRJ6B9MHmWgf7+GVZOxomLgEAcZ ------END RSA PRIVATE KEY----- diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server.go deleted file mode 100644 index b16e71367..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server.go +++ /dev/null @@ -1,1246 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package testing provides a fake implementation of the Docker API, useful for -// testing purpose. -package testing - -import ( - "archive/tar" - "crypto/rand" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - mathrand "math/rand" - "net" - "net/http" - "regexp" - "strconv" - "strings" - "sync" - "time" - - "github.com/fsouza/go-dockerclient" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy" - "github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux" -) - -var nameRegexp = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]+$`) - -// DockerServer represents a programmable, concurrent (not much), HTTP server -// implementing a fake version of the Docker remote API. -// -// It can used in standalone mode, listening for connections or as an arbitrary -// HTTP handler. -// -// For more details on the remote API, check http://goo.gl/G3plxW. -type DockerServer struct { - containers []*docker.Container - uploadedFiles map[string]string - execs []*docker.ExecInspect - execMut sync.RWMutex - cMut sync.RWMutex - images []docker.Image - iMut sync.RWMutex - imgIDs map[string]string - networks []*docker.Network - netMut sync.RWMutex - listener net.Listener - mux *mux.Router - hook func(*http.Request) - failures map[string]string - multiFailures []map[string]string - execCallbacks map[string]func() - statsCallbacks map[string]func(string) docker.Stats - customHandlers map[string]http.Handler - handlerMutex sync.RWMutex - cChan chan<- *docker.Container - volStore map[string]*volumeCounter - volMut sync.RWMutex -} - -type volumeCounter struct { - volume docker.Volume - count int -} - -// NewServer returns a new instance of the fake server, in standalone mode. Use -// the method URL to get the URL of the server. -// -// It receives the bind address (use 127.0.0.1:0 for getting an available port -// on the host), a channel of containers and a hook function, that will be -// called on every request. -// -// The fake server will send containers in the channel whenever the container -// changes its state, via the HTTP API (i.e.: create, start and stop). This -// channel may be nil, which means that the server won't notify on state -// changes. -func NewServer(bind string, containerChan chan<- *docker.Container, hook func(*http.Request)) (*DockerServer, error) { - listener, err := net.Listen("tcp", bind) - if err != nil { - return nil, err - } - server := DockerServer{ - listener: listener, - imgIDs: make(map[string]string), - hook: hook, - failures: make(map[string]string), - execCallbacks: make(map[string]func()), - statsCallbacks: make(map[string]func(string) docker.Stats), - customHandlers: make(map[string]http.Handler), - uploadedFiles: make(map[string]string), - cChan: containerChan, - } - server.buildMuxer() - go http.Serve(listener, &server) - return &server, nil -} - -func (s *DockerServer) notify(container *docker.Container) { - if s.cChan != nil { - s.cChan <- container - } -} - -func (s *DockerServer) buildMuxer() { - s.mux = mux.NewRouter() - s.mux.Path("/commit").Methods("POST").HandlerFunc(s.handlerWrapper(s.commitContainer)) - s.mux.Path("/containers/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.listContainers)) - s.mux.Path("/containers/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.createContainer)) - s.mux.Path("/containers/{id:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectContainer)) - s.mux.Path("/containers/{id:.*}/rename").Methods("POST").HandlerFunc(s.handlerWrapper(s.renameContainer)) - s.mux.Path("/containers/{id:.*}/top").Methods("GET").HandlerFunc(s.handlerWrapper(s.topContainer)) - s.mux.Path("/containers/{id:.*}/start").Methods("POST").HandlerFunc(s.handlerWrapper(s.startContainer)) - s.mux.Path("/containers/{id:.*}/kill").Methods("POST").HandlerFunc(s.handlerWrapper(s.stopContainer)) - s.mux.Path("/containers/{id:.*}/stop").Methods("POST").HandlerFunc(s.handlerWrapper(s.stopContainer)) - s.mux.Path("/containers/{id:.*}/pause").Methods("POST").HandlerFunc(s.handlerWrapper(s.pauseContainer)) - s.mux.Path("/containers/{id:.*}/unpause").Methods("POST").HandlerFunc(s.handlerWrapper(s.unpauseContainer)) - s.mux.Path("/containers/{id:.*}/wait").Methods("POST").HandlerFunc(s.handlerWrapper(s.waitContainer)) - s.mux.Path("/containers/{id:.*}/attach").Methods("POST").HandlerFunc(s.handlerWrapper(s.attachContainer)) - s.mux.Path("/containers/{id:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeContainer)) - s.mux.Path("/containers/{id:.*}/exec").Methods("POST").HandlerFunc(s.handlerWrapper(s.createExecContainer)) - s.mux.Path("/containers/{id:.*}/stats").Methods("GET").HandlerFunc(s.handlerWrapper(s.statsContainer)) - s.mux.Path("/containers/{id:.*}/archive").Methods("PUT").HandlerFunc(s.handlerWrapper(s.uploadToContainer)) - s.mux.Path("/exec/{id:.*}/resize").Methods("POST").HandlerFunc(s.handlerWrapper(s.resizeExecContainer)) - s.mux.Path("/exec/{id:.*}/start").Methods("POST").HandlerFunc(s.handlerWrapper(s.startExecContainer)) - s.mux.Path("/exec/{id:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectExecContainer)) - s.mux.Path("/images/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.pullImage)) - s.mux.Path("/build").Methods("POST").HandlerFunc(s.handlerWrapper(s.buildImage)) - s.mux.Path("/images/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.listImages)) - s.mux.Path("/images/{id:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeImage)) - s.mux.Path("/images/{name:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectImage)) - s.mux.Path("/images/{name:.*}/push").Methods("POST").HandlerFunc(s.handlerWrapper(s.pushImage)) - s.mux.Path("/images/{name:.*}/tag").Methods("POST").HandlerFunc(s.handlerWrapper(s.tagImage)) - s.mux.Path("/events").Methods("GET").HandlerFunc(s.listEvents) - s.mux.Path("/_ping").Methods("GET").HandlerFunc(s.handlerWrapper(s.pingDocker)) - s.mux.Path("/images/load").Methods("POST").HandlerFunc(s.handlerWrapper(s.loadImage)) - s.mux.Path("/images/{id:.*}/get").Methods("GET").HandlerFunc(s.handlerWrapper(s.getImage)) - s.mux.Path("/networks").Methods("GET").HandlerFunc(s.handlerWrapper(s.listNetworks)) - s.mux.Path("/networks/{id:.*}").Methods("GET").HandlerFunc(s.handlerWrapper(s.networkInfo)) - s.mux.Path("/networks").Methods("POST").HandlerFunc(s.handlerWrapper(s.createNetwork)) - s.mux.Path("/volumes").Methods("GET").HandlerFunc(s.handlerWrapper(s.listVolumes)) - s.mux.Path("/volumes/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.createVolume)) - s.mux.Path("/volumes/{name:.*}").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectVolume)) - s.mux.Path("/volumes/{name:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeVolume)) -} - -// SetHook changes the hook function used by the server. -// -// The hook function is a function called on every request. -func (s *DockerServer) SetHook(hook func(*http.Request)) { - s.hook = hook -} - -// PrepareExec adds a callback to a container exec in the fake server. -// -// This function will be called whenever the given exec id is started, and the -// given exec id will remain in the "Running" start while the function is -// running, so it's useful for emulating an exec that runs for two seconds, for -// example: -// -// opts := docker.CreateExecOptions{ -// AttachStdin: true, -// AttachStdout: true, -// AttachStderr: true, -// Tty: true, -// Cmd: []string{"/bin/bash", "-l"}, -// } -// // Client points to a fake server. -// exec, err := client.CreateExec(opts) -// // handle error -// server.PrepareExec(exec.ID, func() {time.Sleep(2 * time.Second)}) -// err = client.StartExec(exec.ID, docker.StartExecOptions{Tty: true}) // will block for 2 seconds -// // handle error -func (s *DockerServer) PrepareExec(id string, callback func()) { - s.execCallbacks[id] = callback -} - -// PrepareStats adds a callback that will be called for each container stats -// call. -// -// This callback function will be called multiple times if stream is set to -// true when stats is called. -func (s *DockerServer) PrepareStats(id string, callback func(string) docker.Stats) { - s.statsCallbacks[id] = callback -} - -// PrepareFailure adds a new expected failure based on a URL regexp it receives -// an id for the failure. -func (s *DockerServer) PrepareFailure(id string, urlRegexp string) { - s.failures[id] = urlRegexp -} - -// PrepareMultiFailures enqueues a new expected failure based on a URL regexp -// it receives an id for the failure. -func (s *DockerServer) PrepareMultiFailures(id string, urlRegexp string) { - s.multiFailures = append(s.multiFailures, map[string]string{"error": id, "url": urlRegexp}) -} - -// ResetFailure removes an expected failure identified by the given id. -func (s *DockerServer) ResetFailure(id string) { - delete(s.failures, id) -} - -// ResetMultiFailures removes all enqueued failures. -func (s *DockerServer) ResetMultiFailures() { - s.multiFailures = []map[string]string{} -} - -// CustomHandler registers a custom handler for a specific path. -// -// For example: -// -// server.CustomHandler("/containers/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { -// http.Error(w, "Something wrong is not right", http.StatusInternalServerError) -// })) -func (s *DockerServer) CustomHandler(path string, handler http.Handler) { - s.handlerMutex.Lock() - s.customHandlers[path] = handler - s.handlerMutex.Unlock() -} - -// MutateContainer changes the state of a container, returning an error if the -// given id does not match to any container "running" in the server. -func (s *DockerServer) MutateContainer(id string, state docker.State) error { - for _, container := range s.containers { - if container.ID == id { - container.State = state - return nil - } - } - return errors.New("container not found") -} - -// Stop stops the server. -func (s *DockerServer) Stop() { - if s.listener != nil { - s.listener.Close() - } -} - -// URL returns the HTTP URL of the server. -func (s *DockerServer) URL() string { - if s.listener == nil { - return "" - } - return "http://" + s.listener.Addr().String() + "/" -} - -// ServeHTTP handles HTTP requests sent to the server. -func (s *DockerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { - s.handlerMutex.RLock() - defer s.handlerMutex.RUnlock() - for re, handler := range s.customHandlers { - if m, _ := regexp.MatchString(re, r.URL.Path); m { - handler.ServeHTTP(w, r) - return - } - } - s.mux.ServeHTTP(w, r) - if s.hook != nil { - s.hook(r) - } -} - -// DefaultHandler returns default http.Handler mux, it allows customHandlers to -// call the default behavior if wanted. -func (s *DockerServer) DefaultHandler() http.Handler { - return s.mux -} - -func (s *DockerServer) handlerWrapper(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { - for errorID, urlRegexp := range s.failures { - matched, err := regexp.MatchString(urlRegexp, r.URL.Path) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !matched { - continue - } - http.Error(w, errorID, http.StatusBadRequest) - return - } - for i, failure := range s.multiFailures { - matched, err := regexp.MatchString(failure["url"], r.URL.Path) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !matched { - continue - } - http.Error(w, failure["error"], http.StatusBadRequest) - s.multiFailures = append(s.multiFailures[:i], s.multiFailures[i+1:]...) - return - } - f(w, r) - } -} - -func (s *DockerServer) listContainers(w http.ResponseWriter, r *http.Request) { - all := r.URL.Query().Get("all") - s.cMut.RLock() - result := make([]docker.APIContainers, 0, len(s.containers)) - for _, container := range s.containers { - if all == "1" || container.State.Running { - result = append(result, docker.APIContainers{ - ID: container.ID, - Image: container.Image, - Command: fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " ")), - Created: container.Created.Unix(), - Status: container.State.String(), - Ports: container.NetworkSettings.PortMappingAPI(), - Names: []string{fmt.Sprintf("/%s", container.Name)}, - }) - } - } - s.cMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) listImages(w http.ResponseWriter, r *http.Request) { - s.cMut.RLock() - result := make([]docker.APIImages, len(s.images)) - for i, image := range s.images { - result[i] = docker.APIImages{ - ID: image.ID, - Created: image.Created.Unix(), - } - for tag, id := range s.imgIDs { - if id == image.ID { - result[i].RepoTags = append(result[i].RepoTags, tag) - } - } - } - s.cMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) findImage(id string) (string, error) { - s.iMut.RLock() - defer s.iMut.RUnlock() - image, ok := s.imgIDs[id] - if ok { - return image, nil - } - image, _, err := s.findImageByID(id) - return image, err -} - -func (s *DockerServer) findImageByID(id string) (string, int, error) { - s.iMut.RLock() - defer s.iMut.RUnlock() - for i, image := range s.images { - if image.ID == id { - return image.ID, i, nil - } - } - return "", -1, errors.New("No such image") -} - -func (s *DockerServer) createContainer(w http.ResponseWriter, r *http.Request) { - var config struct { - *docker.Config - HostConfig *docker.HostConfig - } - defer r.Body.Close() - err := json.NewDecoder(r.Body).Decode(&config) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - name := r.URL.Query().Get("name") - if name != "" && !nameRegexp.MatchString(name) { - http.Error(w, "Invalid container name", http.StatusInternalServerError) - return - } - if _, err := s.findImage(config.Image); err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - ports := map[docker.Port][]docker.PortBinding{} - for port := range config.ExposedPorts { - ports[port] = []docker.PortBinding{{ - HostIP: "0.0.0.0", - HostPort: strconv.Itoa(mathrand.Int() % 0xffff), - }} - } - - //the container may not have cmd when using a Dockerfile - var path string - var args []string - if len(config.Cmd) == 1 { - path = config.Cmd[0] - } else if len(config.Cmd) > 1 { - path = config.Cmd[0] - args = config.Cmd[1:] - } - - generatedID := s.generateID() - config.Config.Hostname = generatedID[:12] - container := docker.Container{ - Name: name, - ID: generatedID, - Created: time.Now(), - Path: path, - Args: args, - Config: config.Config, - HostConfig: config.HostConfig, - State: docker.State{ - Running: false, - Pid: mathrand.Int() % 50000, - ExitCode: 0, - StartedAt: time.Now(), - }, - Image: config.Image, - NetworkSettings: &docker.NetworkSettings{ - IPAddress: fmt.Sprintf("172.16.42.%d", mathrand.Int()%250+2), - IPPrefixLen: 24, - Gateway: "172.16.42.1", - Bridge: "docker0", - Ports: ports, - }, - } - s.cMut.Lock() - if container.Name != "" { - for _, c := range s.containers { - if c.Name == container.Name { - defer s.cMut.Unlock() - http.Error(w, "there's already a container with this name", http.StatusConflict) - return - } - } - } - s.containers = append(s.containers, &container) - s.cMut.Unlock() - w.WriteHeader(http.StatusCreated) - s.notify(&container) - - json.NewEncoder(w).Encode(container) -} - -func (s *DockerServer) generateID() string { - var buf [16]byte - rand.Read(buf[:]) - return fmt.Sprintf("%x", buf) -} - -func (s *DockerServer) renameContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, index, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - copy := *container - copy.Name = r.URL.Query().Get("name") - s.cMut.Lock() - defer s.cMut.Unlock() - if s.containers[index].ID == copy.ID { - s.containers[index] = © - } - w.WriteHeader(http.StatusNoContent) -} - -func (s *DockerServer) inspectContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(container) -} - -func (s *DockerServer) statsContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - _, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - stream, _ := strconv.ParseBool(r.URL.Query().Get("stream")) - callback := s.statsCallbacks[id] - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - encoder := json.NewEncoder(w) - for { - var stats docker.Stats - if callback != nil { - stats = callback(id) - } - encoder.Encode(stats) - if !stream { - break - } - } -} - -func (s *DockerServer) uploadToContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if !container.State.Running { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "Container %s is not running", id) - return - } - path := r.URL.Query().Get("path") - s.uploadedFiles[id] = path - w.WriteHeader(http.StatusOK) -} - -func (s *DockerServer) topContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if !container.State.Running { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "Container %s is not running", id) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - result := docker.TopResult{ - Titles: []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}, - Processes: [][]string{ - {"root", "7535", "7516", "0", "03:20", "?", "00:00:00", container.Path + " " + strings.Join(container.Args, " ")}, - }, - } - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) startContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - defer r.Body.Close() - var hostConfig docker.HostConfig - err = json.NewDecoder(r.Body).Decode(&hostConfig) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - container.HostConfig = &hostConfig - if len(hostConfig.PortBindings) > 0 { - ports := map[docker.Port][]docker.PortBinding{} - for key, items := range hostConfig.PortBindings { - bindings := make([]docker.PortBinding, len(items)) - for i := range items { - binding := docker.PortBinding{ - HostIP: items[i].HostIP, - HostPort: items[i].HostPort, - } - if binding.HostIP == "" { - binding.HostIP = "0.0.0.0" - } - if binding.HostPort == "" { - binding.HostPort = strconv.Itoa(mathrand.Int() % 0xffff) - } - bindings[i] = binding - } - ports[key] = bindings - } - container.NetworkSettings.Ports = ports - } - if container.State.Running { - http.Error(w, "", http.StatusNotModified) - return - } - container.State.Running = true - s.notify(container) -} - -func (s *DockerServer) stopContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - if !container.State.Running { - http.Error(w, "Container not running", http.StatusBadRequest) - return - } - w.WriteHeader(http.StatusNoContent) - container.State.Running = false - s.notify(container) -} - -func (s *DockerServer) pauseContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - if container.State.Paused { - http.Error(w, "Container already paused", http.StatusBadRequest) - return - } - w.WriteHeader(http.StatusNoContent) - container.State.Paused = true -} - -func (s *DockerServer) unpauseContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - if !container.State.Paused { - http.Error(w, "Container not paused", http.StatusBadRequest) - return - } - w.WriteHeader(http.StatusNoContent) - container.State.Paused = false -} - -func (s *DockerServer) attachContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - hijacker, ok := w.(http.Hijacker) - if !ok { - http.Error(w, "cannot hijack connection", http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/vnd.docker.raw-stream") - w.WriteHeader(http.StatusOK) - conn, _, err := hijacker.Hijack() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - wg := sync.WaitGroup{} - if r.URL.Query().Get("stdin") == "1" { - wg.Add(1) - go func() { - ioutil.ReadAll(conn) - wg.Done() - }() - } - outStream := stdcopy.NewStdWriter(conn, stdcopy.Stdout) - if container.State.Running { - fmt.Fprintf(outStream, "Container is running\n") - } else { - fmt.Fprintf(outStream, "Container is not running\n") - } - fmt.Fprintln(outStream, "What happened?") - fmt.Fprintln(outStream, "Something happened") - wg.Wait() - if r.URL.Query().Get("stream") == "1" { - for { - time.Sleep(1e6) - s.cMut.RLock() - if !container.State.Running { - s.cMut.RUnlock() - break - } - s.cMut.RUnlock() - } - } - conn.Close() -} - -func (s *DockerServer) waitContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - for { - time.Sleep(1e6) - s.cMut.RLock() - if !container.State.Running { - s.cMut.RUnlock() - break - } - s.cMut.RUnlock() - } - result := map[string]int{"StatusCode": container.State.ExitCode} - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) removeContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - force := r.URL.Query().Get("force") - container, index, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if container.State.Running && force != "1" { - msg := "Error: API error (406): Impossible to remove a running container, please stop it first" - http.Error(w, msg, http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusNoContent) - s.cMut.Lock() - defer s.cMut.Unlock() - if s.containers[index].ID == id || s.containers[index].Name == id { - s.containers[index] = s.containers[len(s.containers)-1] - s.containers = s.containers[:len(s.containers)-1] - } -} - -func (s *DockerServer) commitContainer(w http.ResponseWriter, r *http.Request) { - id := r.URL.Query().Get("container") - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - var config *docker.Config - runConfig := r.URL.Query().Get("run") - if runConfig != "" { - config = new(docker.Config) - err = json.Unmarshal([]byte(runConfig), config) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - } - w.WriteHeader(http.StatusOK) - image := docker.Image{ - ID: "img-" + container.ID, - Parent: container.Image, - Container: container.ID, - Comment: r.URL.Query().Get("m"), - Author: r.URL.Query().Get("author"), - Config: config, - } - repository := r.URL.Query().Get("repo") - tag := r.URL.Query().Get("tag") - s.iMut.Lock() - s.images = append(s.images, image) - if repository != "" { - if tag != "" { - repository += ":" + tag - } - s.imgIDs[repository] = image.ID - } - s.iMut.Unlock() - fmt.Fprintf(w, `{"ID":%q}`, image.ID) -} - -func (s *DockerServer) findContainer(idOrName string) (*docker.Container, int, error) { - s.cMut.RLock() - defer s.cMut.RUnlock() - for i, container := range s.containers { - if container.ID == idOrName || container.Name == idOrName { - return container, i, nil - } - } - return nil, -1, errors.New("No such container") -} - -func (s *DockerServer) buildImage(w http.ResponseWriter, r *http.Request) { - if ct := r.Header.Get("Content-Type"); ct == "application/tar" { - gotDockerFile := false - tr := tar.NewReader(r.Body) - for { - header, err := tr.Next() - if err != nil { - break - } - if header.Name == "Dockerfile" { - gotDockerFile = true - } - } - if !gotDockerFile { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("miss Dockerfile")) - return - } - } - //we did not use that Dockerfile to build image cause we are a fake Docker daemon - image := docker.Image{ - ID: s.generateID(), - Created: time.Now(), - } - - query := r.URL.Query() - repository := image.ID - if t := query.Get("t"); t != "" { - repository = t - } - s.iMut.Lock() - s.images = append(s.images, image) - s.imgIDs[repository] = image.ID - s.iMut.Unlock() - w.Write([]byte(fmt.Sprintf("Successfully built %s", image.ID))) -} - -func (s *DockerServer) pullImage(w http.ResponseWriter, r *http.Request) { - fromImageName := r.URL.Query().Get("fromImage") - tag := r.URL.Query().Get("tag") - image := docker.Image{ - ID: s.generateID(), - } - s.iMut.Lock() - s.images = append(s.images, image) - if fromImageName != "" { - if tag != "" { - fromImageName = fmt.Sprintf("%s:%s", fromImageName, tag) - } - s.imgIDs[fromImageName] = image.ID - } - s.iMut.Unlock() -} - -func (s *DockerServer) pushImage(w http.ResponseWriter, r *http.Request) { - name := mux.Vars(r)["name"] - tag := r.URL.Query().Get("tag") - if tag != "" { - name += ":" + tag - } - s.iMut.RLock() - if _, ok := s.imgIDs[name]; !ok { - s.iMut.RUnlock() - http.Error(w, "No such image", http.StatusNotFound) - return - } - s.iMut.RUnlock() - fmt.Fprintln(w, "Pushing...") - fmt.Fprintln(w, "Pushed") -} - -func (s *DockerServer) tagImage(w http.ResponseWriter, r *http.Request) { - name := mux.Vars(r)["name"] - s.iMut.RLock() - if _, ok := s.imgIDs[name]; !ok { - s.iMut.RUnlock() - http.Error(w, "No such image", http.StatusNotFound) - return - } - s.iMut.RUnlock() - s.iMut.Lock() - defer s.iMut.Unlock() - newRepo := r.URL.Query().Get("repo") - newTag := r.URL.Query().Get("tag") - if newTag != "" { - newRepo += ":" + newTag - } - s.imgIDs[newRepo] = s.imgIDs[name] - w.WriteHeader(http.StatusCreated) -} - -func (s *DockerServer) removeImage(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - s.iMut.RLock() - var tag string - if img, ok := s.imgIDs[id]; ok { - id, tag = img, id - } - var tags []string - for tag, taggedID := range s.imgIDs { - if taggedID == id { - tags = append(tags, tag) - } - } - s.iMut.RUnlock() - _, index, err := s.findImageByID(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.WriteHeader(http.StatusNoContent) - s.iMut.Lock() - defer s.iMut.Unlock() - if len(tags) < 2 { - s.images[index] = s.images[len(s.images)-1] - s.images = s.images[:len(s.images)-1] - } - if tag != "" { - delete(s.imgIDs, tag) - } -} - -func (s *DockerServer) inspectImage(w http.ResponseWriter, r *http.Request) { - name := mux.Vars(r)["name"] - s.iMut.RLock() - defer s.iMut.RUnlock() - if id, ok := s.imgIDs[name]; ok { - for _, img := range s.images { - if img.ID == id { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(img) - return - } - } - } - http.Error(w, "not found", http.StatusNotFound) -} - -func (s *DockerServer) listEvents(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var events [][]byte - count := mathrand.Intn(20) - for i := 0; i < count; i++ { - data, err := json.Marshal(s.generateEvent()) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - events = append(events, data) - } - w.WriteHeader(http.StatusOK) - for _, d := range events { - fmt.Fprintln(w, d) - time.Sleep(time.Duration(mathrand.Intn(200)) * time.Millisecond) - } -} - -func (s *DockerServer) pingDocker(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func (s *DockerServer) generateEvent() *docker.APIEvents { - var eventType string - switch mathrand.Intn(4) { - case 0: - eventType = "create" - case 1: - eventType = "start" - case 2: - eventType = "stop" - case 3: - eventType = "destroy" - } - return &docker.APIEvents{ - ID: s.generateID(), - Status: eventType, - From: "mybase:latest", - Time: time.Now().Unix(), - } -} - -func (s *DockerServer) loadImage(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func (s *DockerServer) getImage(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/tar") -} - -func (s *DockerServer) createExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - - execID := s.generateID() - container.ExecIDs = append(container.ExecIDs, execID) - - exec := docker.ExecInspect{ - ID: execID, - Container: *container, - } - - var params docker.CreateExecOptions - err = json.NewDecoder(r.Body).Decode(¶ms) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if len(params.Cmd) > 0 { - exec.ProcessConfig.EntryPoint = params.Cmd[0] - if len(params.Cmd) > 1 { - exec.ProcessConfig.Arguments = params.Cmd[1:] - } - } - - exec.ProcessConfig.User = params.User - exec.ProcessConfig.Tty = params.Tty - - s.execMut.Lock() - s.execs = append(s.execs, &exec) - s.execMut.Unlock() - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]string{"Id": exec.ID}) -} - -func (s *DockerServer) startExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - if exec, err := s.getExec(id, false); err == nil { - s.execMut.Lock() - exec.Running = true - s.execMut.Unlock() - if callback, ok := s.execCallbacks[id]; ok { - callback() - delete(s.execCallbacks, id) - } else if callback, ok := s.execCallbacks["*"]; ok { - callback() - delete(s.execCallbacks, "*") - } - s.execMut.Lock() - exec.Running = false - s.execMut.Unlock() - w.WriteHeader(http.StatusOK) - return - } - w.WriteHeader(http.StatusNotFound) -} - -func (s *DockerServer) resizeExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - if _, err := s.getExec(id, false); err == nil { - w.WriteHeader(http.StatusOK) - return - } - w.WriteHeader(http.StatusNotFound) -} - -func (s *DockerServer) inspectExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - if exec, err := s.getExec(id, true); err == nil { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(exec) - return - } - w.WriteHeader(http.StatusNotFound) -} - -func (s *DockerServer) getExec(id string, copy bool) (*docker.ExecInspect, error) { - s.execMut.RLock() - defer s.execMut.RUnlock() - for _, exec := range s.execs { - if exec.ID == id { - if copy { - cp := *exec - exec = &cp - } - return exec, nil - } - } - return nil, errors.New("exec not found") -} - -func (s *DockerServer) findNetwork(idOrName string) (*docker.Network, int, error) { - s.netMut.RLock() - defer s.netMut.RUnlock() - for i, network := range s.networks { - if network.ID == idOrName || network.Name == idOrName { - return network, i, nil - } - } - return nil, -1, errors.New("No such network") -} - -func (s *DockerServer) listNetworks(w http.ResponseWriter, r *http.Request) { - s.netMut.RLock() - result := make([]docker.Network, 0, len(s.networks)) - for _, network := range s.networks { - result = append(result, *network) - } - s.netMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) networkInfo(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - network, _, err := s.findNetwork(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(network) -} - -// isValidName validates configuration objects supported by libnetwork -func isValidName(name string) bool { - if name == "" || strings.Contains(name, ".") { - return false - } - return true -} - -func (s *DockerServer) createNetwork(w http.ResponseWriter, r *http.Request) { - var config *docker.CreateNetworkOptions - defer r.Body.Close() - err := json.NewDecoder(r.Body).Decode(&config) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !isValidName(config.Name) { - http.Error(w, "Invalid network name", http.StatusBadRequest) - return - } - if n, _, _ := s.findNetwork(config.Name); n != nil { - http.Error(w, "network already exists", http.StatusForbidden) - return - } - - generatedID := s.generateID() - network := docker.Network{ - Name: config.Name, - ID: generatedID, - Driver: config.Driver, - } - s.netMut.Lock() - s.networks = append(s.networks, &network) - s.netMut.Unlock() - w.WriteHeader(http.StatusCreated) - var c = struct{ ID string }{ID: network.ID} - json.NewEncoder(w).Encode(c) -} - -func (s *DockerServer) listVolumes(w http.ResponseWriter, r *http.Request) { - s.volMut.RLock() - result := make([]docker.Volume, 0, len(s.volStore)) - for _, volumeCounter := range s.volStore { - result = append(result, volumeCounter.volume) - } - s.volMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) createVolume(w http.ResponseWriter, r *http.Request) { - var data struct { - *docker.CreateVolumeOptions - } - defer r.Body.Close() - err := json.NewDecoder(r.Body).Decode(&data) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - volume := &docker.Volume{ - Name: data.CreateVolumeOptions.Name, - Driver: data.CreateVolumeOptions.Driver, - } - // If the name is not specified, generate one. Just using generateID for now - if len(volume.Name) == 0 { - volume.Name = s.generateID() - } - // If driver is not specified, use local - if len(volume.Driver) == 0 { - volume.Driver = "local" - } - // Mount point is a default one with name - volume.Mountpoint = "/var/lib/docker/volumes/" + volume.Name - - // If the volume already exists, don't re-add it. - exists := false - s.volMut.Lock() - if s.volStore != nil { - _, exists = s.volStore[volume.Name] - } else { - // No volumes, create volStore - s.volStore = make(map[string]*volumeCounter) - } - if !exists { - s.volStore[volume.Name] = &volumeCounter{ - volume: *volume, - count: 0, - } - } - s.volMut.Unlock() - w.WriteHeader(http.StatusCreated) - json.NewEncoder(w).Encode(volume) -} - -func (s *DockerServer) inspectVolume(w http.ResponseWriter, r *http.Request) { - s.volMut.RLock() - defer s.volMut.RUnlock() - name := mux.Vars(r)["name"] - vol, err := s.findVolume(name) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(vol.volume) -} - -func (s *DockerServer) findVolume(name string) (*volumeCounter, error) { - vol, ok := s.volStore[name] - if !ok { - return nil, errors.New("no such volume") - } - return vol, nil -} - -func (s *DockerServer) removeVolume(w http.ResponseWriter, r *http.Request) { - s.volMut.Lock() - defer s.volMut.Unlock() - name := mux.Vars(r)["name"] - vol, err := s.findVolume(name) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if vol.count != 0 { - http.Error(w, "volume in use and cannot be removed", http.StatusConflict) - return - } - s.volStore[vol.volume.Name] = nil - w.WriteHeader(http.StatusNoContent) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server_test.go deleted file mode 100644 index ddadcaab5..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server_test.go +++ /dev/null @@ -1,2103 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package testing - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "math/rand" - "net" - "net/http" - "net/http/httptest" - "os" - "reflect" - "strings" - "sync" - "testing" - "time" - - "github.com/fsouza/go-dockerclient" -) - -func TestNewServer(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.listener.Close() - conn, err := net.Dial("tcp", server.listener.Addr().String()) - if err != nil { - t.Fatal(err) - } - conn.Close() -} - -func TestServerStop(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - server.Stop() - _, err = net.Dial("tcp", server.listener.Addr().String()) - if err == nil { - t.Error("Unexpected error when dialing to stopped server") - } -} - -func TestServerStopNoListener(t *testing.T) { - server := DockerServer{} - server.Stop() -} - -func TestServerURL(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.Stop() - url := server.URL() - if expected := "http://" + server.listener.Addr().String() + "/"; url != expected { - t.Errorf("DockerServer.URL(): Want %q. Got %q.", expected, url) - } -} - -func TestServerURLNoListener(t *testing.T) { - server := DockerServer{} - url := server.URL() - if url != "" { - t.Errorf("DockerServer.URL(): Expected empty URL on handler mode, got %q.", url) - } -} - -func TestHandleWithHook(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, func(*http.Request) { called = true }) - defer server.Stop() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("ServeHTTP did not call the hook function.") - } -} - -func TestSetHook(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, nil) - defer server.Stop() - server.SetHook(func(*http.Request) { called = true }) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("ServeHTTP did not call the hook function.") - } -} - -func TestCustomHandler(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 2) - server.CustomHandler("/containers/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - fmt.Fprint(w, "Hello world") - })) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("Did not call the custom handler") - } - if got := recorder.Body.String(); got != "Hello world" { - t.Errorf("Wrong output for custom handler: want %q. Got %q.", "Hello world", got) - } -} - -func TestCustomHandlerRegexp(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 2) - server.CustomHandler("/containers/.*/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - fmt.Fprint(w, "Hello world") - })) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/.*/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("Did not call the custom handler") - } - if got := recorder.Body.String(); got != "Hello world" { - t.Errorf("Wrong output for custom handler: want %q. Got %q.", "Hello world", got) - } -} - -func TestListContainers(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListContainers: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := make([]docker.APIContainers, 2) - for i, container := range server.containers { - expected[i] = docker.APIContainers{ - ID: container.ID, - Image: container.Image, - Command: strings.Join(container.Config.Cmd, " "), - Created: container.Created.Unix(), - Status: container.State.String(), - Ports: container.NetworkSettings.PortMappingAPI(), - Names: []string{"/" + container.Name}, - } - } - var got []docker.APIContainers - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got, expected) { - t.Errorf("ListContainers. Want %#v. Got %#v.", expected, got) - } -} - -func TestListRunningContainers(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=0", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListRunningContainers: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got []docker.APIContainers - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if len(got) != 0 { - t.Errorf("ListRunningContainers: Want 0. Got %d.", len(got)) - } -} - -func TestCreateContainer(t *testing.T) { - server := DockerServer{} - server.imgIDs = map[string]string{"base": "a1234"} - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - var returned docker.Container - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Fatal(err) - } - stored := server.containers[0] - if returned.ID != stored.ID { - t.Errorf("CreateContainer: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned.ID) - } - if stored.State.Running { - t.Errorf("CreateContainer should not set container to running state.") - } - if stored.Config.User != "ubuntu" { - t.Errorf("CreateContainer: wrong config. Expected: %q. Returned: %q.", "ubuntu", stored.Config.User) - } - if stored.Config.Hostname != returned.ID[:12] { - t.Errorf("CreateContainer: wrong hostname. Expected: %q. Returned: %q.", returned.ID[:12], stored.Config.Hostname) - } - expectedBind := []string{"/var/run/docker.sock:/var/run/docker.sock:rw"} - if !reflect.DeepEqual(stored.HostConfig.Binds, expectedBind) { - t.Errorf("CreateContainer: wrong host config. Expected: %v. Returned %v.", expectedBind, stored.HostConfig.Binds) - } -} - -func TestCreateContainerWithNotifyChannel(t *testing.T) { - ch := make(chan *docker.Container, 1) - server := DockerServer{} - server.imgIDs = map[string]string{"base": "a1234"} - server.cChan = ch - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":""}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - if notified := <-ch; notified != server.containers[0] { - t.Errorf("CreateContainer: did not notify the proper container. Want %q. Got %q.", server.containers[0].ID, notified.ID) - } -} - -func TestCreateContainerInvalidBody(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader("whaaaaaat---")) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestCreateContainerDuplicateName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - server.imgIDs = map[string]string{"base": "a1234"} - addContainers(&server, 1) - server.containers[0].Name = "mycontainer" - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` - request, _ := http.NewRequest("POST", "/containers/create?name=mycontainer", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusConflict { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusConflict, recorder.Code) - } -} - -func TestCreateMultipleContainersEmptyName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - server.imgIDs = map[string]string{"base": "a1234"} - addContainers(&server, 1) - server.containers[0].Name = "" - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - var returned docker.Container - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Fatal(err) - } - stored := server.containers[1] - if returned.ID != stored.ID { - t.Errorf("CreateContainer: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned.ID) - } - if stored.State.Running { - t.Errorf("CreateContainer should not set container to running state.") - } - if stored.Config.User != "ubuntu" { - t.Errorf("CreateContainer: wrong config. Expected: %q. Returned: %q.", "ubuntu", stored.Config.User) - } - expectedBind := []string{"/var/run/docker.sock:/var/run/docker.sock:rw"} - if !reflect.DeepEqual(stored.HostConfig.Binds, expectedBind) { - t.Errorf("CreateContainer: wrong host config. Expected: %v. Returned %v.", expectedBind, stored.HostConfig.Binds) - } -} - -func TestCreateContainerInvalidName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], -"Image":"base", "Volumes":{}, "VolumesFrom":""}` - request, _ := http.NewRequest("POST", "/containers/create?name=myapp/container1", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusInternalServerError { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) - } - expectedBody := "Invalid container name\n" - if got := recorder.Body.String(); got != expectedBody { - t.Errorf("CreateContainer: wrong body. Want %q. Got %q.", expectedBody, got) - } -} - -func TestCreateContainerImageNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], -"Image":"base", "Volumes":{}, "VolumesFrom":""}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestRenameContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - newName := server.containers[0].Name + "abc" - path := fmt.Sprintf("/containers/%s/rename?name=%s", server.containers[0].ID, newName) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RenameContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - container := server.containers[0] - if container.Name != newName { - t.Errorf("RenameContainer: did not rename the container. Want %q. Got %q.", newName, container.Name) - } -} - -func TestRenameContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/containers/blabla/rename?name=something", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("RenameContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestCommitContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/commit?container="+server.containers[0].ID, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("CommitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := fmt.Sprintf(`{"ID":"%s"}`, server.images[0].ID) - if got := recorder.Body.String(); got != expected { - t.Errorf("CommitContainer: wrong response body. Want %q. Got %q.", expected, got) - } -} - -func TestCommitContainerComplete(t *testing.T) { - server := DockerServer{} - server.imgIDs = make(map[string]string) - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - queryString := "container=" + server.containers[0].ID + "&repo=tsuru/python&m=saving&author=developers" - queryString += `&run={"Cmd": ["cat", "/world"],"PortSpecs":["22"]}` - request, _ := http.NewRequest("POST", "/commit?"+queryString, nil) - server.ServeHTTP(recorder, request) - image := server.images[0] - if image.Parent != server.containers[0].Image { - t.Errorf("CommitContainer: wrong parent image. Want %q. Got %q.", server.containers[0].Image, image.Parent) - } - if image.Container != server.containers[0].ID { - t.Errorf("CommitContainer: wrong container. Want %q. Got %q.", server.containers[0].ID, image.Container) - } - message := "saving" - if image.Comment != message { - t.Errorf("CommitContainer: wrong comment (commit message). Want %q. Got %q.", message, image.Comment) - } - author := "developers" - if image.Author != author { - t.Errorf("CommitContainer: wrong author. Want %q. Got %q.", author, image.Author) - } - if id := server.imgIDs["tsuru/python"]; id != image.ID { - t.Errorf("CommitContainer: wrong ID saved for repository. Want %q. Got %q.", image.ID, id) - } - portSpecs := []string{"22"} - if !reflect.DeepEqual(image.Config.PortSpecs, portSpecs) { - t.Errorf("CommitContainer: wrong port spec in config. Want %#v. Got %#v.", portSpecs, image.Config.PortSpecs) - } - cmd := []string{"cat", "/world"} - if !reflect.DeepEqual(image.Config.Cmd, cmd) { - t.Errorf("CommitContainer: wrong cmd in config. Want %#v. Got %#v.", cmd, image.Config.Cmd) - } -} - -func TestCommitContainerWithTag(t *testing.T) { - server := DockerServer{} - server.imgIDs = make(map[string]string) - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - queryString := "container=" + server.containers[0].ID + "&repo=tsuru/python&tag=v1" - request, _ := http.NewRequest("POST", "/commit?"+queryString, nil) - server.ServeHTTP(recorder, request) - image := server.images[0] - if image.Parent != server.containers[0].Image { - t.Errorf("CommitContainer: wrong parent image. Want %q. Got %q.", server.containers[0].Image, image.Parent) - } - if image.Container != server.containers[0].ID { - t.Errorf("CommitContainer: wrong container. Want %q. Got %q.", server.containers[0].ID, image.Container) - } - if id := server.imgIDs["tsuru/python:v1"]; id != image.ID { - t.Errorf("CommitContainer: wrong ID saved for repository. Want %q. Got %q.", image.ID, id) - } -} - -func TestCommitContainerInvalidRun(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/commit?container="+server.containers[0].ID+"&run=abc---", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("CommitContainer. Wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestCommitContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/commit?container=abc123", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("CommitContainer. Wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestInspectContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/json", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("InspectContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := server.containers[0] - var got docker.Container - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got.Config, expected.Config) { - t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) - } - if !reflect.DeepEqual(got.NetworkSettings, expected.NetworkSettings) { - t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) - } - got.State.StartedAt = expected.State.StartedAt - got.State.FinishedAt = expected.State.FinishedAt - got.Config = expected.Config - got.Created = expected.Created - got.NetworkSettings = expected.NetworkSettings - if !reflect.DeepEqual(got, *expected) { - t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) - } -} - -func TestInspectContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/abc123/json", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("InspectContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestTopContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/top", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got docker.TopResult - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got.Titles, []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}) { - t.Fatalf("TopContainer: Unexpected titles, got: %#v", got.Titles) - } - if len(got.Processes) != 1 { - t.Fatalf("TopContainer: Unexpected process len, got: %d", len(got.Processes)) - } - if got.Processes[0][len(got.Processes[0])-1] != "ls -la .." { - t.Fatalf("TopContainer: Unexpected command name, got: %s", got.Processes[0][len(got.Processes[0])-1]) - } -} - -func TestTopContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/xyz/top", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestTopContainerStopped(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/top", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusInternalServerError { - t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) - } -} - -func TestStartContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - memory := int64(536870912) - hostConfig := docker.HostConfig{Memory: memory} - configBytes, err := json.Marshal(hostConfig) - if err != nil { - t.Fatal(err) - } - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, bytes.NewBuffer(configBytes)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if !server.containers[0].State.Running { - t.Error("StartContainer: did not set the container to running state") - } - if gotMemory := server.containers[0].HostConfig.Memory; gotMemory != memory { - t.Errorf("StartContainer: wrong HostConfig. Wants %d of memory. Got %d", memory, gotMemory) - } -} - -func TestStartContainerChangeNetwork(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - hostConfig := docker.HostConfig{ - PortBindings: map[docker.Port][]docker.PortBinding{ - "8888/tcp": {{HostIP: "", HostPort: "12345"}}, - }, - } - configBytes, err := json.Marshal(hostConfig) - if err != nil { - t.Fatal(err) - } - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, bytes.NewBuffer(configBytes)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if !server.containers[0].State.Running { - t.Error("StartContainer: did not set the container to running state") - } - portMapping := server.containers[0].NetworkSettings.Ports["8888/tcp"] - expected := []docker.PortBinding{{HostIP: "0.0.0.0", HostPort: "12345"}} - if !reflect.DeepEqual(portMapping, expected) { - t.Errorf("StartContainer: network not updated. Wants %#v ports. Got %#v", expected, portMapping) - } -} - -func TestStartContainerWithNotifyChannel(t *testing.T) { - ch := make(chan *docker.Container, 1) - server := DockerServer{} - server.cChan = ch - addContainers(&server, 1) - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/start", server.containers[1].ID) - request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("{}"))) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if notified := <-ch; notified != server.containers[1] { - t.Errorf("StartContainer: did not notify the proper container. Want %q. Got %q.", server.containers[1].ID, notified.ID) - } -} - -func TestStartContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/start" - request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("null"))) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestStartContainerAlreadyRunning(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("null"))) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotModified { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusNotModified, recorder.Code) - } -} - -func TestStopContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stop", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if server.containers[0].State.Running { - t.Error("StopContainer: did not stop the container") - } -} - -func TestKillContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/kill", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("KillContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if server.containers[0].State.Running { - t.Error("KillContainer: did not stop the container") - } -} - -func TestStopContainerWithNotifyChannel(t *testing.T) { - ch := make(chan *docker.Container, 1) - server := DockerServer{} - server.cChan = ch - addContainers(&server, 1) - addContainers(&server, 1) - server.containers[1].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stop", server.containers[1].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if notified := <-ch; notified != server.containers[1] { - t.Errorf("StopContainer: did not notify the proper container. Want %q. Got %q.", server.containers[1].ID, notified.ID) - } -} - -func TestStopContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/stop" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestStopContainerNotRunning(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stop", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestPauseContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/pause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if !server.containers[0].State.Paused { - t.Error("PauseContainer: did not pause the container") - } -} - -func TestPauseContainerAlreadyPaused(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Paused = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/pause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestPauseContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/pause" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestUnpauseContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Paused = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/unpause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if server.containers[0].State.Paused { - t.Error("UnpauseContainer: did not unpause the container") - } -} - -func TestUnpauseContainerNotPaused(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/unpause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestUnpauseContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/unpause" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestWaitContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/wait", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - go func() { - server.cMut.Lock() - server.containers[0].State.Running = false - server.cMut.Unlock() - }() - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("WaitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := `{"StatusCode":0}` + "\n" - if body := recorder.Body.String(); body != expected { - t.Errorf("WaitContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestWaitContainerStatus(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - server.containers[0].State.ExitCode = 63 - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/wait", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("WaitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := `{"StatusCode":63}` + "\n" - if body := recorder.Body.String(); body != expected { - t.Errorf("WaitContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestWaitContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/wait" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("WaitContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -type HijackableResponseRecorder struct { - httptest.ResponseRecorder - readCh chan []byte -} - -func (r *HijackableResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { - myConn, otherConn := net.Pipe() - r.readCh = make(chan []byte) - go func() { - data, _ := ioutil.ReadAll(myConn) - r.readCh <- data - }() - return otherConn, nil, nil -} - -func (r *HijackableResponseRecorder) HijackBuffer() string { - return string(<-r.readCh) -} - -func TestAttachContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := &HijackableResponseRecorder{} - path := fmt.Sprintf("/containers/%s/attach?logs=1", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - lines := []string{ - "\x01\x00\x00\x00\x00\x00\x00\x15Container is running", - "\x01\x00\x00\x00\x00\x00\x00\x0fWhat happened?", - "\x01\x00\x00\x00\x00\x00\x00\x13Something happened", - } - expected := strings.Join(lines, "\n") + "\n" - if body := recorder.HijackBuffer(); body != expected { - t.Errorf("AttachContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestAttachContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := &HijackableResponseRecorder{} - path := "/containers/abc123/attach?logs=1" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("AttachContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestAttachContainerWithStreamBlocks(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - path := fmt.Sprintf("/containers/%s/attach?logs=1&stdout=1&stream=1", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - done := make(chan string) - go func() { - recorder := &HijackableResponseRecorder{} - server.ServeHTTP(recorder, request) - done <- recorder.HijackBuffer() - }() - select { - case <-done: - t.Fatalf("attach stream returned before container is stopped") - case <-time.After(500 * time.Millisecond): - } - server.cMut.Lock() - server.containers[0].State.Running = false - server.cMut.Unlock() - var body string - select { - case body = <-done: - case <-time.After(5 * time.Second): - t.Fatalf("timed out waiting for attach to finish") - } - lines := []string{ - "\x01\x00\x00\x00\x00\x00\x00\x15Container is running", - "\x01\x00\x00\x00\x00\x00\x00\x0fWhat happened?", - "\x01\x00\x00\x00\x00\x00\x00\x13Something happened", - } - expected := strings.Join(lines, "\n") + "\n" - if body != expected { - t.Errorf("AttachContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestRemoveContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s", server.containers[0].ID) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.containers) > 0 { - t.Error("RemoveContainer: did not remove the container.") - } -} - -func TestRemoveContainerByName(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s", server.containers[0].Name) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.containers) > 0 { - t.Error("RemoveContainer: did not remove the container.") - } -} - -func TestRemoveContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/abc123") - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestRemoveContainerRunning(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s", server.containers[0].ID) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusInternalServerError { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) - } - if len(server.containers) < 1 { - t.Error("RemoveContainer: should not remove the container.") - } -} - -func TestRemoveContainerRunningForce(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s?%s", server.containers[0].ID, "force=1") - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.containers) > 0 { - t.Error("RemoveContainer: did not remove the container.") - } -} - -func TestPullImage(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/create?fromImage=base", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PullImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if len(server.images) != 1 { - t.Errorf("PullImage: Want 1 image. Got %d.", len(server.images)) - } - if _, ok := server.imgIDs["base"]; !ok { - t.Error("PullImage: Repository should not be empty.") - } -} - -func TestPullImageWithTag(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/create?fromImage=base&tag=tag", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PullImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if len(server.images) != 1 { - t.Errorf("PullImage: Want 1 image. Got %d.", len(server.images)) - } - if _, ok := server.imgIDs["base:tag"]; !ok { - t.Error("PullImage: Repository should not be empty.") - } -} - -func TestPushImage(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/push", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } -} - -func TestPushImageWithTag(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python:v1": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/push?tag=v1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } -} - -func TestPushImageNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/push", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestTagImage(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/tag?repo=tsuru/new-python", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - if server.imgIDs["tsuru/python"] != server.imgIDs["tsuru/new-python"] { - t.Errorf("TagImage: did not tag the image") - } -} - -func TestTagImageWithRepoAndTag(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/tag?repo=tsuru/new-python&tag=v1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - if server.imgIDs["tsuru/python"] != server.imgIDs["tsuru/new-python:v1"] { - t.Errorf("TagImage: did not tag the image") - } -} - -func TestTagImageNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/tag", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func addContainers(server *DockerServer, n int) { - server.cMut.Lock() - defer server.cMut.Unlock() - for i := 0; i < n; i++ { - date := time.Now().Add(time.Duration((rand.Int() % (i + 1))) * time.Hour) - container := docker.Container{ - Name: fmt.Sprintf("%x", rand.Int()%10000), - ID: fmt.Sprintf("%x", rand.Int()%10000), - Created: date, - Path: "ls", - Args: []string{"-la", ".."}, - Config: &docker.Config{ - Hostname: fmt.Sprintf("docker-%d", i), - AttachStdout: true, - AttachStderr: true, - Env: []string{"ME=you", fmt.Sprintf("NUMBER=%d", i)}, - Cmd: []string{"ls", "-la", ".."}, - Image: "base", - }, - State: docker.State{ - Running: false, - Pid: 400 + i, - ExitCode: 0, - StartedAt: date, - }, - Image: "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - NetworkSettings: &docker.NetworkSettings{ - IPAddress: fmt.Sprintf("10.10.10.%d", i+2), - IPPrefixLen: 24, - Gateway: "10.10.10.1", - Bridge: "docker0", - PortMapping: map[string]docker.PortMapping{ - "Tcp": {"8888": fmt.Sprintf("%d", 49600+i)}, - }, - Ports: map[docker.Port][]docker.PortBinding{ - "8888/tcp": { - {HostIP: "0.0.0.0", HostPort: fmt.Sprintf("%d", 49600+i)}, - }, - }, - }, - ResolvConfPath: "/etc/resolv.conf", - } - server.containers = append(server.containers, &container) - } -} - -func addImages(server *DockerServer, n int, repo bool) { - server.iMut.Lock() - defer server.iMut.Unlock() - if server.imgIDs == nil { - server.imgIDs = make(map[string]string) - } - for i := 0; i < n; i++ { - date := time.Now().Add(time.Duration((rand.Int() % (i + 1))) * time.Hour) - image := docker.Image{ - ID: fmt.Sprintf("%x", rand.Int()%10000), - Created: date, - } - server.images = append(server.images, image) - if repo { - repo := "docker/python-" + image.ID - server.imgIDs[repo] = image.ID - } - } -} - -func TestListImages(t *testing.T) { - server := DockerServer{} - addImages(&server, 2, true) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/images/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListImages: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := make([]docker.APIImages, 2) - for i, image := range server.images { - expected[i] = docker.APIImages{ - ID: image.ID, - Created: image.Created.Unix(), - RepoTags: []string{"docker/python-" + image.ID}, - } - } - var got []docker.APIImages - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got, expected) { - t.Errorf("ListImages. Want %#v. Got %#v.", expected, got) - } -} - -func TestRemoveImage(t *testing.T) { - server := DockerServer{} - addImages(&server, 1, false) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/images/%s", server.images[0].ID) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveImage: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.images) > 0 { - t.Error("RemoveImage: did not remove the image.") - } -} - -func TestRemoveImageByName(t *testing.T) { - server := DockerServer{} - addImages(&server, 1, true) - server.buildMuxer() - recorder := httptest.NewRecorder() - imgName := "docker/python-" + server.images[0].ID - path := "/images/" + imgName - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveImage: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.images) > 0 { - t.Error("RemoveImage: did not remove the image.") - } - _, ok := server.imgIDs[imgName] - if ok { - t.Error("RemoveImage: did not remove image tag name.") - } -} - -func TestRemoveImageWithMultipleTags(t *testing.T) { - server := DockerServer{} - addImages(&server, 1, true) - server.buildMuxer() - imgID := server.images[0].ID - imgName := "docker/python-" + imgID - server.imgIDs["docker/python-wat"] = imgID - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/images/%s", imgName) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - _, ok := server.imgIDs[imgName] - if ok { - t.Error("RemoveImage: did not remove image tag name.") - } - id, ok := server.imgIDs["docker/python-wat"] - if !ok { - t.Error("RemoveImage: removed the wrong tag name.") - } - if id != imgID { - t.Error("RemoveImage: disassociated the wrong ID from the tag") - } - if len(server.images) < 1 { - t.Fatal("RemoveImage: removed the image, but should keep it") - } - if server.images[0].ID != imgID { - t.Error("RemoveImage: changed the ID of the image!") - } -} - -func TestPrepareFailure(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - errorID := "my_error" - server.PrepareFailure(errorID, "containers/json") - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - if recorder.Body.String() != errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } -} - -func TestPrepareMultiFailures(t *testing.T) { - server := DockerServer{multiFailures: []map[string]string{}} - server.buildMuxer() - errorID := "multi error" - server.PrepareMultiFailures(errorID, "containers/json") - server.PrepareMultiFailures(errorID, "containers/json") - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - if recorder.Body.String() != errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - if recorder.Body.String() != errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if recorder.Body.String() == errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } -} - -func TestRemoveFailure(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - errorID := "my_error" - server.PrepareFailure(errorID, "containers/json") - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - server.ResetFailure(errorID) - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("RemoveFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } -} - -func TestResetMultiFailures(t *testing.T) { - server := DockerServer{multiFailures: []map[string]string{}} - server.buildMuxer() - errorID := "multi error" - server.PrepareMultiFailures(errorID, "containers/json") - server.PrepareMultiFailures(errorID, "containers/json") - if len(server.multiFailures) != 2 { - t.Errorf("PrepareMultiFailures: error adding multi failures.") - } - server.ResetMultiFailures() - if len(server.multiFailures) != 0 { - t.Errorf("ResetMultiFailures: error reseting multi failures.") - } -} - -func TestMutateContainer(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - server.containers = append(server.containers, &docker.Container{ID: "id123"}) - state := docker.State{Running: false, ExitCode: 1} - err := server.MutateContainer("id123", state) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(server.containers[0].State, state) { - t.Errorf("Wrong state after mutation.\nWant %#v.\nGot %#v.", - state, server.containers[0].State) - } -} - -func TestMutateContainerNotFound(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - state := docker.State{Running: false, ExitCode: 1} - err := server.MutateContainer("id123", state) - if err == nil { - t.Error("Unexpected error") - } - if err.Error() != "container not found" { - t.Errorf("wrong error message. Want %q. Got %q.", "container not found", err) - } -} - -func TestBuildImageWithContentTypeTar(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - imageName := "teste" - recorder := httptest.NewRecorder() - tarFile, err := os.Open("data/dockerfile.tar") - if err != nil { - t.Fatal(err) - } - defer tarFile.Close() - request, _ := http.NewRequest("POST", "/build?t=teste", tarFile) - request.Header.Add("Content-Type", "application/tar") - server.buildImage(recorder, request) - if recorder.Body.String() == "miss Dockerfile" { - t.Errorf("BuildImage: miss Dockerfile") - return - } - if _, ok := server.imgIDs[imageName]; ok == false { - t.Errorf("BuildImage: image %s not builded", imageName) - } -} - -func TestBuildImageWithRemoteDockerfile(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - imageName := "teste" - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/build?t=teste&remote=http://localhost/Dockerfile", nil) - server.buildImage(recorder, request) - if _, ok := server.imgIDs[imageName]; ok == false { - t.Errorf("BuildImage: image %s not builded", imageName) - } -} - -func TestPing(t *testing.T) { - server := DockerServer{} - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/_ping", nil) - server.pingDocker(recorder, request) - if recorder.Body.String() != "" { - t.Errorf("Ping: Unexpected body: %s", recorder.Body.String()) - } - if recorder.Code != http.StatusOK { - t.Errorf("Ping: Expected code %d, got: %d", http.StatusOK, recorder.Code) - } -} - -func TestDefaultHandler(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.listener.Close() - if server.mux != server.DefaultHandler() { - t.Fatalf("DefaultHandler: Expected to return server.mux, got: %#v", server.DefaultHandler()) - } -} - -func TestCreateExecContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - serverExec := server.execs[0] - var got docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if got.ID != serverExec.ID { - t.Errorf("CreateExec: wrong value. Want %#v. Got %#v.", serverExec.ID, got.ID) - } - - expected := docker.ExecInspect{ - ID: got.ID, - ProcessConfig: docker.ExecProcessConfig{ - EntryPoint: "bash", - Arguments: []string{"-c", "ls"}, - }, - Container: *server.containers[0], - } - - if !reflect.DeepEqual(*serverExec, expected) { - t.Errorf("InspectContainer: wrong value. Want:\n%#v\nGot:\n%#v\n", expected, *serverExec) - } -} - -func TestInspectExecContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - path = fmt.Sprintf("/exec/%s/json", got.ID) - request, _ = http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got2 docker.ExecInspect - err = json.NewDecoder(recorder.Body).Decode(&got2) - if err != nil { - t.Fatal(err) - } - expected := docker.ExecInspect{ - ID: got.ID, - ProcessConfig: docker.ExecProcessConfig{ - EntryPoint: "bash", - Arguments: []string{"-c", "ls"}, - }, - Container: *server.containers[0], - } - got2.Container.State.StartedAt = expected.Container.State.StartedAt - got2.Container.State.FinishedAt = expected.Container.State.FinishedAt - got2.Container.Config = expected.Container.Config - got2.Container.Created = expected.Container.Created - got2.Container.NetworkSettings = expected.Container.NetworkSettings - got2.Container.ExecIDs = expected.Container.ExecIDs - - if !reflect.DeepEqual(got2, expected) { - t.Errorf("InspectContainer: wrong value. Want:\n%#v\nGot:\n%#v\n", expected, got2) - } -} - -func TestStartExecContainer(t *testing.T) { - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var exec docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&exec) - if err != nil { - t.Fatal(err) - } - unleash := make(chan bool) - server.PrepareExec(exec.ID, func() { - <-unleash - }) - codes := make(chan int, 1) - sent := make(chan bool) - go func() { - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/exec/%s/start", exec.ID) - body := `{"Tty":true}` - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - close(sent) - server.ServeHTTP(recorder, request) - codes <- recorder.Code - }() - <-sent - execInfo, err := waitExec(server.URL(), exec.ID, true, 5) - if err != nil { - t.Fatal(err) - } - if !execInfo.Running { - t.Error("StartExec: expected exec to be running, but it's not running") - } - close(unleash) - if code := <-codes; code != http.StatusOK { - t.Errorf("StartExec: wrong status. Want %d. Got %d.", http.StatusOK, code) - } - execInfo, err = waitExec(server.URL(), exec.ID, false, 5) - if err != nil { - t.Fatal(err) - } - if execInfo.Running { - t.Error("StartExec: expected exec to be not running after start returns, but it's running") - } -} - -func TestStartExecContainerWildcardCallback(t *testing.T) { - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - unleash := make(chan bool) - server.PrepareExec("*", func() { - <-unleash - }) - var exec docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&exec) - if err != nil { - t.Fatal(err) - } - codes := make(chan int, 1) - sent := make(chan bool) - go func() { - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/exec/%s/start", exec.ID) - body := `{"Tty":true}` - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - close(sent) - server.ServeHTTP(recorder, request) - codes <- recorder.Code - }() - <-sent - execInfo, err := waitExec(server.URL(), exec.ID, true, 5) - if err != nil { - t.Fatal(err) - } - if !execInfo.Running { - t.Error("StartExec: expected exec to be running, but it's not running") - } - close(unleash) - if code := <-codes; code != http.StatusOK { - t.Errorf("StartExec: wrong status. Want %d. Got %d.", http.StatusOK, code) - } - execInfo, err = waitExec(server.URL(), exec.ID, false, 5) - if err != nil { - t.Fatal(err) - } - if execInfo.Running { - t.Error("StartExec: expected exec to be not running after start returns, but it's running") - } -} - -func TestStartExecContainerNotFound(t *testing.T) { - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Tty":true}` - request, _ := http.NewRequest("POST", "/exec/something-wat/start", strings.NewReader(body)) - server.ServeHTTP(recorder, request) -} - -func waitExec(url, execID string, running bool, maxTry int) (*docker.ExecInspect, error) { - client, err := docker.NewClient(url) - if err != nil { - return nil, err - } - exec, err := client.InspectExec(execID) - for i := 0; i < maxTry && exec.Running != running && err == nil; i++ { - time.Sleep(100e6) - exec, err = client.InspectExec(exec.ID) - } - return exec, err -} - -func TestStatsContainer(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.Stop() - addContainers(server, 2) - server.buildMuxer() - expected := docker.Stats{} - expected.CPUStats.CPUUsage.TotalUsage = 20 - server.PrepareStats(server.containers[0].ID, func(id string) docker.Stats { - return expected - }) - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stats?stream=false", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("StatsContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - body := recorder.Body.Bytes() - var got docker.Stats - err = json.Unmarshal(body, &got) - if err != nil { - t.Fatal(err) - } - got.Read = time.Time{} - if !reflect.DeepEqual(got, expected) { - t.Errorf("StatsContainer: wrong value. Want %#v. Got %#v.", expected, got) - } -} - -type safeWriter struct { - sync.Mutex - *httptest.ResponseRecorder -} - -func (w *safeWriter) Write(buf []byte) (int, error) { - w.Lock() - defer w.Unlock() - return w.ResponseRecorder.Write(buf) -} - -func TestStatsContainerStream(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.Stop() - addContainers(server, 2) - server.buildMuxer() - expected := docker.Stats{} - expected.CPUStats.CPUUsage.TotalUsage = 20 - server.PrepareStats(server.containers[0].ID, func(id string) docker.Stats { - time.Sleep(50 * time.Millisecond) - return expected - }) - recorder := &safeWriter{ - ResponseRecorder: httptest.NewRecorder(), - } - path := fmt.Sprintf("/containers/%s/stats?stream=true", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - go func() { - server.ServeHTTP(recorder, request) - }() - time.Sleep(200 * time.Millisecond) - recorder.Lock() - defer recorder.Unlock() - body := recorder.Body.Bytes() - parts := bytes.Split(body, []byte("\n")) - if len(parts) < 2 { - t.Errorf("StatsContainer: wrong number of parts. Want at least 2. Got %#v.", len(parts)) - } - var got docker.Stats - err = json.Unmarshal(parts[0], &got) - if err != nil { - t.Fatal(err) - } - got.Read = time.Time{} - if !reflect.DeepEqual(got, expected) { - t.Errorf("StatsContainer: wrong value. Want %#v. Got %#v.", expected, got) - } -} - -func addNetworks(server *DockerServer, n int) { - server.netMut.Lock() - defer server.netMut.Unlock() - for i := 0; i < n; i++ { - netid := fmt.Sprintf("%x", rand.Int()%10000) - network := docker.Network{ - Name: netid, - ID: fmt.Sprintf("%x", rand.Int()%10000), - Driver: "bridge", - Containers: map[string]docker.Endpoint{ - "blah": { - Name: "blah", - ID: fmt.Sprintf("%x", rand.Int()%10000), - }, - }, - } - server.networks = append(server.networks, &network) - } -} - -func TestListNetworks(t *testing.T) { - server := DockerServer{} - addNetworks(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/networks", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListNetworks: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := make([]docker.Network, 2) - for i, network := range server.networks { - expected[i] = docker.Network{ - ID: network.ID, - Name: network.Name, - Driver: network.Driver, - Containers: network.Containers, - } - } - var got []docker.Network - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got, expected) { - t.Errorf("ListNetworks. Want %#v. Got %#v.", expected, got) - } -} - -type createNetworkResponse struct { - ID string `json:"ID"` -} - -func TestCreateNetwork(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - netid := fmt.Sprintf("%x", rand.Int()%10000) - netname := fmt.Sprintf("%x", rand.Int()%10000) - body := fmt.Sprintf(`{"ID": "%s", "Name": "%s", "Type": "bridge" }`, netid, netname) - request, _ := http.NewRequest("POST", "/networks", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - - var returned createNetworkResponse - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Fatal(err) - } - stored := server.networks[0] - if returned.ID != stored.ID { - t.Errorf("CreateNetwork: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned) - } -} - -func TestCreateNetworkInvalidBody(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/networks", strings.NewReader("whaaaaaat---")) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestCreateNetworkDuplicateName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - addNetworks(&server, 1) - server.networks[0].Name = "mynetwork" - recorder := httptest.NewRecorder() - body := fmt.Sprintf(`{"ID": "%s", "Name": "mynetwork", "Type": "bridge" }`, fmt.Sprintf("%x", rand.Int()%10000)) - request, _ := http.NewRequest("POST", "/networks", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusForbidden { - t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusForbidden, recorder.Code) - } -} - -func TestListVolumes(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - expected := []docker.Volume{{ - Name: "test-vol-1", - Driver: "local", - Mountpoint: "/var/lib/docker/volumes/test-vol-1", - }} - server.volStore = make(map[string]*volumeCounter) - for _, vol := range expected { - server.volStore[vol.Name] = &volumeCounter{ - volume: vol, - count: 0, - } - } - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/volumes", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListVolumes: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - var got []docker.Volume - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got, expected) { - t.Errorf("ListVolumes. Want %#v. Got %#v.", expected, got) - } -} - -func TestCreateVolume(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Name":"test-volume"}` - request, _ := http.NewRequest("POST", "/volumes/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateVolume: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - var returned docker.Volume - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Error(err) - } - if returned.Name != "test-volume" { - t.Errorf("CreateVolume: Name mismatch. Expected: test-volume. Returned %q.", returned.Name) - } - if returned.Driver != "local" { - t.Errorf("CreateVolume: Driver mismatch. Expected: local. Returned: %q", returned.Driver) - } - if returned.Mountpoint != "/var/lib/docker/volumes/test-volume" { - t.Errorf("CreateVolume: Mountpoint mismatch. Expected: /var/lib/docker/volumes/test-volume. Returned: %q.", returned.Mountpoint) - } -} - -func TestCreateVolumeAlreadExists(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - server.volStore = make(map[string]*volumeCounter) - server.volStore["test-volume"] = &volumeCounter{ - volume: docker.Volume{ - Name: "test-volume", - Driver: "local", - Mountpoint: "/var/lib/docker/volumes/test-volume", - }, - count: 0, - } - body := `{"Name":"test-volume"}` - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/volumes/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateVolumeAlreadExists: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - var returned docker.Volume - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Error(err) - } - if returned.Name != "test-volume" { - t.Errorf("CreateVolumeAlreadExists: Name mismatch. Expected: test-volume. Returned %q.", returned.Name) - } - if returned.Driver != "local" { - t.Errorf("CreateVolumeAlreadExists: Driver mismatch. Expected: local. Returned: %q", returned.Driver) - } - if returned.Mountpoint != "/var/lib/docker/volumes/test-volume" { - t.Errorf("CreateVolumeAlreadExists: Mountpoint mismatch. Expected: /var/lib/docker/volumes/test-volume. Returned: %q.", returned.Mountpoint) - } -} - -func TestInspectVolume(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - expected := docker.Volume{ - Name: "test-volume", - Driver: "local", - Mountpoint: "/var/lib/docker/volumes/test-volume", - } - volC := &volumeCounter{ - volume: expected, - count: 0, - } - volStore := make(map[string]*volumeCounter) - volStore["test-volume"] = volC - server.volStore = volStore - request, _ := http.NewRequest("GET", "/volumes/test-volume", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("InspectVolume: wrong status. Want %d. God %d.", http.StatusOK, recorder.Code) - } - var returned docker.Volume - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Error(err) - } - if returned.Name != "test-volume" { - t.Errorf("InspectVolume: Name mismatch. Expected: test-volume. Returned %q.", returned.Name) - } - if returned.Driver != "local" { - t.Errorf("InspectVolume: Driver mismatch. Expected: local. Returned: %q", returned.Driver) - } - if returned.Mountpoint != "/var/lib/docker/volumes/test-volume" { - t.Errorf("InspectVolume: Mountpoint mismatch. Expected: /var/lib/docker/volumes/test-volume. Returned: %q.", returned.Mountpoint) - } -} - -func TestInspectVolumeNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/volumes/test-volume", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("RemoveMissingVolume: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestRemoveVolume(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - server.volStore = make(map[string]*volumeCounter) - server.volStore["test-volume"] = &volumeCounter{ - volume: docker.Volume{ - Name: "test-volume", - Driver: "local", - Mountpoint: "/var/lib/docker/volumes/test-volume", - }, - count: 0, - } - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("DELETE", "/volumes/test-volume", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveVolume: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } -} - -func TestRemoveMissingVolume(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("DELETE", "/volumes/test-volume", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("RemoveMissingVolume: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestRemoveVolumeInuse(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - server.volStore = make(map[string]*volumeCounter) - server.volStore["test-volume"] = &volumeCounter{ - volume: docker.Volume{ - Name: "test-volume", - Driver: "local", - Mountpoint: "/var/lib/docker/volumes/test-volume", - }, - count: 1, - } - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("DELETE", "/volumes/test-volume", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusConflict { - t.Errorf("RemoveVolume: wrong status. Want %d. Got %d.", http.StatusConflict, recorder.Code) - } -} - -func TestUploadToContainer(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - cont := &docker.Container{ - ID: "id123", - State: docker.State{ - Running: true, - ExitCode: 0, - }, - } - server.containers = append(server.containers, cont) - server.uploadedFiles = make(map[string]string) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("PUT", fmt.Sprintf("/containers/%s/archive?path=abcd", cont.ID), nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("UploadToContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } -} - -func TestUploadToContainerMissingContainer(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("PUT", "/containers/missing-container/archive?path=abcd", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("UploadToContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/volume_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/volume_test.go deleted file mode 100644 index e6bcca95f..000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/volume_test.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/json" - "net/http" - "net/url" - "reflect" - "testing" -) - -func TestListVolumes(t *testing.T) { - volumesData := `[ - { - "Name": "tardis", - "Driver": "local", - "Mountpoint": "/var/lib/docker/volumes/tardis" - }, - { - "Name": "foo", - "Driver": "bar", - "Mountpoint": "/var/lib/docker/volumes/bar" - } -]` - body := `{ "Volumes": ` + volumesData + ` }` - var expected []Volume - if err := json.Unmarshal([]byte(volumesData), &expected); err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - volumes, err := client.ListVolumes(ListVolumesOptions{}) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(volumes, expected) { - t.Errorf("ListVolumes: Wrong return value. Want %#v. Got %#v.", expected, volumes) - } -} - -func TestCreateVolume(t *testing.T) { - body := `{ - "Name": "tardis", - "Driver": "local", - "Mountpoint": "/var/lib/docker/volumes/tardis" - }` - var expected Volume - if err := json.Unmarshal([]byte(body), &expected); err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(fakeRT) - volume, err := client.CreateVolume( - CreateVolumeOptions{ - Name: "tardis", - Driver: "local", - DriverOpts: map[string]string{ - "foo": "bar", - }, - }, - ) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(volume, &expected) { - t.Errorf("CreateVolume: Wrong return value. Want %#v. Got %#v.", expected, volume) - } - req := fakeRT.requests[0] - expectedMethod := "POST" - if req.Method != expectedMethod { - t.Errorf("CreateVolume(): Wrong HTTP method. Want %s. Got %s.", expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/volumes/create")) - if req.URL.Path != u.Path { - t.Errorf("CreateVolume(): Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestInspectVolume(t *testing.T) { - body := `{ - "Name": "tardis", - "Driver": "local", - "Mountpoint": "/var/lib/docker/volumes/tardis" - }` - var expected Volume - if err := json.Unmarshal([]byte(body), &expected); err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(fakeRT) - name := "tardis" - volume, err := client.InspectVolume(name) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(volume, &expected) { - t.Errorf("InspectVolume: Wrong return value. Want %#v. Got %#v.", expected, volume) - } - req := fakeRT.requests[0] - expectedMethod := "GET" - if req.Method != expectedMethod { - t.Errorf("InspectVolume(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/volumes/" + name)) - if req.URL.Path != u.Path { - t.Errorf("CreateVolume(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } -} - -func TestRemoveVolume(t *testing.T) { - name := "test" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - if err := client.RemoveVolume(name); err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "DELETE" - if req.Method != expectedMethod { - t.Errorf("RemoveVolume(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/volumes/" + name)) - if req.URL.Path != u.Path { - t.Errorf("RemoveVolume(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } -} - -func TestRemoveVolumeNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such volume", status: http.StatusNotFound}) - if err := client.RemoveVolume("test:"); err != ErrNoSuchVolume { - t.Errorf("RemoveVolume: wrong error. Want %#v. Got %#v.", ErrNoSuchVolume, err) - } -} - -func TestRemoveVolumeInUse(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "volume in use and cannot be removed", status: http.StatusConflict}) - if err := client.RemoveVolume("test:"); err != ErrVolumeInUse { - t.Errorf("RemoveVolume: wrong error. Want %#v. Got %#v.", ErrVolumeInUse, err) - } -} diff --git a/Godeps/_workspace/src/github.com/ghodss/yaml/yaml_test.go b/Godeps/_workspace/src/github.com/ghodss/yaml/yaml_test.go deleted file mode 100644 index 0ae0954e9..000000000 --- a/Godeps/_workspace/src/github.com/ghodss/yaml/yaml_test.go +++ /dev/null @@ -1,271 +0,0 @@ -package yaml - -import ( - "fmt" - "math" - "reflect" - "strconv" - "testing" -) - -type MarshalTest struct { - A string - B int64 - // Would like to test float64, but it's not supported in go-yaml. - // (See https://github.com/go-yaml/yaml/issues/83.) - C float32 -} - -func TestMarshal(t *testing.T) { - f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) - s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32} - e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", math.MaxInt64, f32String)) - - y, err := Marshal(s) - if err != nil { - t.Errorf("error marshaling YAML: %v", err) - } - - if !reflect.DeepEqual(y, e) { - t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v", - string(e), string(y)) - } -} - -type UnmarshalString struct { - A string - True string -} - -type UnmarshalStringMap struct { - A map[string]string -} - -type UnmarshalNestedString struct { - A NestedString -} - -type NestedString struct { - A string -} - -type UnmarshalSlice struct { - A []NestedSlice -} - -type NestedSlice struct { - B string - C *string -} - -func TestUnmarshal(t *testing.T) { - y := []byte("a: 1") - s1 := UnmarshalString{} - e1 := UnmarshalString{A: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a: true") - s1 = UnmarshalString{} - e1 = UnmarshalString{A: "true"} - unmarshal(t, y, &s1, &e1) - - y = []byte("true: 1") - s1 = UnmarshalString{} - e1 = UnmarshalString{True: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a:\n a: 1") - s2 := UnmarshalNestedString{} - e2 := UnmarshalNestedString{NestedString{"1"}} - unmarshal(t, y, &s2, &e2) - - y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") - s3 := UnmarshalSlice{} - e3 := UnmarshalSlice{[]NestedSlice{NestedSlice{"abc", strPtr("def")}, NestedSlice{"123", strPtr("456")}}} - unmarshal(t, y, &s3, &e3) - - y = []byte("a:\n b: 1") - s4 := UnmarshalStringMap{} - e4 := UnmarshalStringMap{map[string]string{"b": "1"}} - unmarshal(t, y, &s4, &e4) -} - -func unmarshal(t *testing.T, y []byte, s, e interface{}) { - err := Unmarshal(y, s) - if err != nil { - t.Errorf("error unmarshaling YAML: %v", err) - } - - if !reflect.DeepEqual(s, e) { - t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", - e, s) - } -} - -type Case struct { - input string - output string - // By default we test that reversing the output == input. But if there is a - // difference in the reversed output, you can optionally specify it here. - reverse *string -} - -type RunType int - -const ( - RunTypeJSONToYAML RunType = iota - RunTypeYAMLToJSON -) - -func TestJSONToYAML(t *testing.T) { - cases := []Case{ - { - `{"t":"a"}`, - "t: a\n", - nil, - }, { - `{"t":null}`, - "t: null\n", - nil, - }, - } - - runCases(t, RunTypeJSONToYAML, cases) -} - -func TestYAMLToJSON(t *testing.T) { - cases := []Case{ - { - "t: a\n", - `{"t":"a"}`, - nil, - }, { - "t: \n", - `{"t":null}`, - strPtr("t: null\n"), - }, { - "t: null\n", - `{"t":null}`, - nil, - }, { - "1: a\n", - `{"1":"a"}`, - strPtr("\"1\": a\n"), - }, { - "1000000000000000000000000000000000000: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "1e+36: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "\"1e+36\": a\n", - `{"1e+36":"a"}`, - nil, - }, { - "\"1.2\": a\n", - `{"1.2":"a"}`, - nil, - }, { - "- t: a\n", - `[{"t":"a"}]`, - nil, - }, { - "- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n", - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - nil, - }, { - `[{t: a}, {t: {b: 1, c: 2}}]`, - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - strPtr("- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n"), - }, { - "- t: \n", - `[{"t":null}]`, - strPtr("- t: null\n"), - }, { - "- t: null\n", - `[{"t":null}]`, - nil, - }, - } - - // Cases that should produce errors. - _ = []Case{ - { - "~: a", - `{"null":"a"}`, - nil, - }, { - "a: !!binary gIGC\n", - "{\"a\":\"\x80\x81\x82\"}", - nil, - }, - } - - runCases(t, RunTypeYAMLToJSON, cases) -} - -func runCases(t *testing.T, runType RunType, cases []Case) { - var f func([]byte) ([]byte, error) - var invF func([]byte) ([]byte, error) - var msg string - var invMsg string - if runType == RunTypeJSONToYAML { - f = JSONToYAML - invF = YAMLToJSON - msg = "JSON to YAML" - invMsg = "YAML back to JSON" - } else { - f = YAMLToJSON - invF = JSONToYAML - msg = "YAML to JSON" - invMsg = "JSON back to YAML" - } - - for _, c := range cases { - // Convert the string. - t.Logf("converting %s\n", c.input) - output, err := f([]byte(c.input)) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", msg, c.input, err) - } - - // Check it against the expected output. - if string(output) != c.output { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - msg, c.input, c.output, string(output)) - } - - // Set the string that we will compare the reversed output to. - reverse := c.input - // If a special reverse string was specified, use that instead. - if c.reverse != nil { - reverse = *c.reverse - } - - // Reverse the output. - input, err := invF(output) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", invMsg, string(output), err) - } - - // Check the reverse is equal to the input (or to *c.reverse). - if string(input) != reverse { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - invMsg, string(output), reverse, string(input)) - } - } - -} - -// To be able to easily fill in the *Case.reverse string above. -func strPtr(s string) *string { - return &s -} diff --git a/Godeps/_workspace/src/github.com/golang/glog/glog_test.go b/Godeps/_workspace/src/github.com/golang/glog/glog_test.go deleted file mode 100644 index 0fb376e1f..000000000 --- a/Godeps/_workspace/src/github.com/golang/glog/glog_test.go +++ /dev/null @@ -1,415 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 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 glog - -import ( - "bytes" - "fmt" - stdLog "log" - "path/filepath" - "runtime" - "strconv" - "strings" - "testing" - "time" -) - -// Test that shortHostname works as advertised. -func TestShortHostname(t *testing.T) { - for hostname, expect := range map[string]string{ - "": "", - "host": "host", - "host.google.com": "host", - } { - if got := shortHostname(hostname); expect != got { - t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) - } - } -} - -// flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. -type flushBuffer struct { - bytes.Buffer -} - -func (f *flushBuffer) Flush() error { - return nil -} - -func (f *flushBuffer) Sync() error { - return nil -} - -// swap sets the log writers and returns the old array. -func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { - l.mu.Lock() - defer l.mu.Unlock() - old = l.file - for i, w := range writers { - logging.file[i] = w - } - return -} - -// newBuffers sets the log writers to all new byte buffers and returns the old array. -func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { - return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) -} - -// contents returns the specified log value as a string. -func contents(s severity) string { - return logging.file[s].(*flushBuffer).String() -} - -// contains reports whether the string is contained in the log. -func contains(s severity, str string, t *testing.T) bool { - return strings.Contains(contents(s), str) -} - -// setFlags configures the logging flags how the test expects them. -func setFlags() { - logging.toStderr = false -} - -// Test that Info works as advertised. -func TestInfo(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -func TestInfoDepth(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - - f := func() { InfoDepth(1, "depth-test1") } - - // The next three lines must stay together - _, _, wantLine, _ := runtime.Caller(0) - InfoDepth(0, "depth-test0") - f() - - msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") - if len(msgs) != 2 { - t.Fatalf("Got %d lines, expected 2", len(msgs)) - } - - for i, m := range msgs { - if !strings.HasPrefix(m, "I") { - t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) - } - w := fmt.Sprintf("depth-test%d", i) - if !strings.Contains(m, w) { - t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) - } - - // pull out the line number (between : and ]) - msg := m[strings.LastIndex(m, ":")+1:] - x := strings.Index(msg, "]") - if x < 0 { - t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) - continue - } - line, err := strconv.Atoi(msg[:x]) - if err != nil { - t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) - continue - } - wantLine++ - if wantLine != line { - t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) - } - } -} - -func init() { - CopyStandardLogTo("INFO") -} - -// Test that CopyStandardLogTo panics on bad input. -func TestCopyStandardLogToPanic(t *testing.T) { - defer func() { - if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { - t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) - } - }() - CopyStandardLogTo("LOG") -} - -// Test that using the standard log package logs to INFO. -func TestStandardLog(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - stdLog.Print("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that the header has the correct format. -func TestHeader(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer func(previous func() time.Time) { timeNow = previous }(timeNow) - timeNow = func() time.Time { - return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) - } - pid = 1234 - Info("test") - var line int - format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" - n, err := fmt.Sscanf(contents(infoLog), format, &line) - if n != 1 || err != nil { - t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) - } - // Scanf treats multiple spaces as equivalent to a single space, - // so check for correct space-padding also. - want := fmt.Sprintf(format, line) - if contents(infoLog) != want { - t.Errorf("log format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) - } -} - -// Test that an Error log goes to Warning and Info. -// Even in the Info log, the source character will be E, so the data should -// all be identical. -func TestError(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Error("test") - if !contains(errorLog, "E", t) { - t.Errorf("Error has wrong character: %q", contents(errorLog)) - } - if !contains(errorLog, "test", t) { - t.Error("Error failed") - } - str := contents(errorLog) - if !contains(warningLog, str, t) { - t.Error("Warning failed") - } - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a Warning log goes to Info. -// Even in the Info log, the source character will be W, so the data should -// all be identical. -func TestWarning(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Warning("test") - if !contains(warningLog, "W", t) { - t.Errorf("Warning has wrong character: %q", contents(warningLog)) - } - if !contains(warningLog, "test", t) { - t.Error("Warning failed") - } - str := contents(warningLog) - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a V log goes to Info. -func TestV(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.verbosity.Set("2") - defer logging.verbosity.Set("0") - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule enables a log in this file. -func TestVmoduleOn(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("glog_test=2") - defer logging.vmodule.Set("") - if !V(1) { - t.Error("V not enabled for 1") - } - if !V(2) { - t.Error("V not enabled for 2") - } - if V(3) { - t.Error("V enabled for 3") - } - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule of another file does not enable a log in this file. -func TestVmoduleOff(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("notthisfile=2") - defer logging.vmodule.Set("") - for i := 1; i <= 3; i++ { - if V(Level(i)) { - t.Errorf("V enabled for %d", i) - } - } - V(2).Info("test") - if contents(infoLog) != "" { - t.Error("V logged incorrectly") - } -} - -// vGlobs are patterns that match/don't match this file at V=2. -var vGlobs = map[string]bool{ - // Easy to test the numeric match here. - "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. - "glog_test=2": true, - "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. - // These all use 2 and check the patterns. All are true. - "*=2": true, - "?l*=2": true, - "????_*=2": true, - "??[mno]?_*t=2": true, - // These all use 2 and check the patterns. All are false. - "*x=2": false, - "m*=2": false, - "??_*=2": false, - "?[abc]?_*t=2": false, -} - -// Test that vmodule globbing works as advertised. -func testVmoduleGlob(pat string, match bool, t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer logging.vmodule.Set("") - logging.vmodule.Set(pat) - if V(2) != Verbose(match) { - t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) - } -} - -// Test that a vmodule globbing works as advertised. -func TestVmoduleGlob(t *testing.T) { - for glob, match := range vGlobs { - testVmoduleGlob(glob, match, t) - } -} - -func TestRollover(t *testing.T) { - setFlags() - var err error - defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) - logExitFunc = func(e error) { - err = e - } - defer func(previous uint64) { MaxSize = previous }(MaxSize) - MaxSize = 512 - - Info("x") // Be sure we have a file. - info, ok := logging.file[infoLog].(*syncBuffer) - if !ok { - t.Fatal("info wasn't created") - } - if err != nil { - t.Fatalf("info has initial error: %v", err) - } - fname0 := info.file.Name() - Info(strings.Repeat("x", int(MaxSize))) // force a rollover - if err != nil { - t.Fatalf("info has error after big write: %v", err) - } - - // Make sure the next log file gets a file name with a different - // time stamp. - // - // TODO: determine whether we need to support subsecond log - // rotation. C++ does not appear to handle this case (nor does it - // handle Daylight Savings Time properly). - time.Sleep(1 * time.Second) - - Info("x") // create a new file - if err != nil { - t.Fatalf("error after rotation: %v", err) - } - fname1 := info.file.Name() - if fname0 == fname1 { - t.Errorf("info.f.Name did not change: %v", fname0) - } - if info.nbytes >= MaxSize { - t.Errorf("file size was not reset: %d", info.nbytes) - } -} - -func TestLogBacktraceAt(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - // The peculiar style of this code simplifies line counting and maintenance of the - // tracing block below. - var infoLine string - setTraceLocation := func(file string, line int, ok bool, delta int) { - if !ok { - t.Fatal("could not get file:line") - } - _, file = filepath.Split(file) - infoLine = fmt.Sprintf("%s:%d", file, line+delta) - err := logging.traceLocation.Set(infoLine) - if err != nil { - t.Fatal("error setting log_backtrace_at: ", err) - } - } - { - // Start of tracing block. These lines know about each other's relative position. - _, file, line, ok := runtime.Caller(0) - setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. - Info("we want a stack trace here") - } - numAppearances := strings.Count(contents(infoLog), infoLine) - if numAppearances < 2 { - // Need 2 appearances, one in the log header and one in the trace: - // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here - // ... - // github.com/glog/glog_test.go:280 (0x41ba91) - // ... - // We could be more precise but that would require knowing the details - // of the traceback format, which may not be dependable. - t.Fatal("got no trace back; log is ", contents(infoLog)) - } -} - -func BenchmarkHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - buf, _, _ := logging.header(infoLog, 0) - logging.putBuffer(buf) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/groupcache/LICENSE b/Godeps/_workspace/src/github.com/golang/groupcache/LICENSE new file mode 100644 index 000000000..37ec93a14 --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/groupcache/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: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +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 +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/Godeps/_workspace/src/github.com/golang/groupcache/lru/lru_test.go b/Godeps/_workspace/src/github.com/golang/groupcache/lru/lru_test.go deleted file mode 100644 index 98a2656e8..000000000 --- a/Godeps/_workspace/src/github.com/golang/groupcache/lru/lru_test.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2013 Google Inc. - -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 lru - -import ( - "testing" -) - -type simpleStruct struct { - int - string -} - -type complexStruct struct { - int - simpleStruct -} - -var getTests = []struct { - name string - keyToAdd interface{} - keyToGet interface{} - expectedOk bool -}{ - {"string_hit", "myKey", "myKey", true}, - {"string_miss", "myKey", "nonsense", false}, - {"simple_struct_hit", simpleStruct{1, "two"}, simpleStruct{1, "two"}, true}, - {"simeple_struct_miss", simpleStruct{1, "two"}, simpleStruct{0, "noway"}, false}, - {"complex_struct_hit", complexStruct{1, simpleStruct{2, "three"}}, - complexStruct{1, simpleStruct{2, "three"}}, true}, -} - -func TestGet(t *testing.T) { - for _, tt := range getTests { - lru := New(0) - lru.Add(tt.keyToAdd, 1234) - val, ok := lru.Get(tt.keyToGet) - if ok != tt.expectedOk { - t.Fatalf("%s: cache hit = %v; want %v", tt.name, ok, !ok) - } else if ok && val != 1234 { - t.Fatalf("%s expected get to return 1234 but got %v", tt.name, val) - } - } -} - -func TestRemove(t *testing.T) { - lru := New(0) - lru.Add("myKey", 1234) - if val, ok := lru.Get("myKey"); !ok { - t.Fatal("TestRemove returned no match") - } else if val != 1234 { - t.Fatalf("TestRemove failed. Expected %d, got %v", 1234, val) - } - - lru.Remove("myKey") - if _, ok := lru.Get("myKey"); ok { - t.Fatal("TestRemove returned a removed entry") - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE b/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE new file mode 100644 index 000000000..1b1b1921e --- /dev/null +++ b/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE @@ -0,0 +1,31 @@ +Go support for Protocol Buffers - Google's data interchange format + +Copyright 2010 The Go Authors. All rights reserved. +https://github.com/golang/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. + * 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/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile index fb838ed2d..f1f06564a 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile @@ -39,5 +39,5 @@ test: install generate-test-pbs generate-test-pbs: make install make -C testdata - make -C proto3_proto + protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata:. proto3_proto/proto3.proto make diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go deleted file mode 100644 index 3fade175f..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2059 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "./testdata" - . "github.com/golang/protobuf/proto" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f fakeMarshaler) Marshal() ([]byte, error) { - return f.b, f.err -} - -func (f fakeMarshaler) String() string { - return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) -} - -func (f fakeMarshaler) ProtoMessage() {} - -func (f fakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - wantErr error - }{ - { - name: "Marshaler that fails", - m: fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since there's an error, nothing should be written to buffer. - want: nil, - wantErr: errors.New("some marshal err"), - }, - { - name: "Marshaler that succeeds", - m: fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - wantErr: nil, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if !reflect.DeepEqual(test.wantErr, err) { - t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - if err := o.Marshal(pb); err != ErrRepeatedHasNil { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if strings.Index(err.Error(), "Label") < 0 { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if strings.Index(err.Error(), "{Unknown}") < 0 { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - _, err := Marshal((*GoEnum)(nil)) - if err != ErrNil { - t.Errorf("Marshal: got err %v, want ErrNil", err) - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: &FloatingPoint{F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go index ae276fd77..e98ddec98 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go @@ -29,8 +29,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// Protocol buffer deep copy. -// TODO: MessageSet and RawMessage. +// Protocol buffer deep copy and merge. +// TODO: RawMessage. package proto @@ -75,12 +75,13 @@ func Merge(dst, src Message) { } func mergeStruct(out, in reflect.Value) { + sprop := GetProperties(in.Type()) for i := 0; i < in.NumField(); i++ { f := in.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } - mergeAny(out.Field(i), in.Field(i)) + mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) } if emIn, ok := in.Addr().Interface().(extendableProto); ok { @@ -98,7 +99,10 @@ func mergeStruct(out, in reflect.Value) { } } -func mergeAny(out, in reflect.Value) { +// mergeAny performs a merge between two values of the same type. +// viaPtr indicates whether the values were indirected through a pointer (implying proto2). +// prop is set if this is a struct field (it may be nil). +func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { if in.Type() == protoMessageType { if !in.IsNil() { if out.IsNil() { @@ -112,7 +116,21 @@ func mergeAny(out, in reflect.Value) { switch in.Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: + if !viaPtr && isProto3Zero(in) { + return + } out.Set(in) + case reflect.Interface: + // Probably a oneof field; copy non-nil values. + if in.IsNil() { + return + } + // Allocate destination if it is not set, or set to a different type. + // Otherwise we will merge as normal. + if out.IsNil() || out.Elem().Type() != in.Elem().Type() { + out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) + } + mergeAny(out.Elem(), in.Elem(), false, nil) case reflect.Map: if in.Len() == 0 { return @@ -127,7 +145,7 @@ func mergeAny(out, in reflect.Value) { switch elemKind { case reflect.Ptr: val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key)) + mergeAny(val, in.MapIndex(key), false, nil) case reflect.Slice: val = in.MapIndex(key) val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) @@ -143,13 +161,21 @@ func mergeAny(out, in reflect.Value) { if out.IsNil() { out.Set(reflect.New(in.Elem().Type())) } - mergeAny(out.Elem(), in.Elem()) + mergeAny(out.Elem(), in.Elem(), true, nil) case reflect.Slice: if in.IsNil() { return } if in.Type().Elem().Kind() == reflect.Uint8 { // []byte is a scalar bytes field, not a repeated field. + + // Edge case: if this is in a proto3 message, a zero length + // bytes field is considered the zero value, and should not + // be merged. + if prop != nil && prop.proto3 && in.Len() == 0 { + return + } + // Make a deep copy. // Append to []byte{} instead of []byte(nil) so that we never end up // with a nil result. @@ -167,7 +193,7 @@ func mergeAny(out, in reflect.Value) { default: for i := 0; i < n; i++ { x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i)) + mergeAny(x, in.Index(i), false, nil) out.Set(reflect.Append(out, x)) } } @@ -184,7 +210,7 @@ func mergeExtension(out, in map[int32]Extension) { eOut := Extension{desc: eIn.desc} if eIn.value != nil { v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value)) + mergeAny(v, reflect.ValueOf(eIn.value), false, nil) eOut.value = v.Interface() } if eIn.enc != nil { diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100644 index 1ac177d21..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,227 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - pb "./testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go index 88622c305..5810782fd 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go @@ -46,6 +46,10 @@ import ( // errOverflow is returned when an integer is too large to be represented. var errOverflow = errors.New("proto: integer overflow") +// ErrInternalBadWireType is returned by generated code when an incorrect +// wire type is encountered. It does not get returned to user code. +var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") + // The fundamental decoders that interpret bytes on the wire. // Those that take integer types all return uint64 and are // therefore of type valueDecoder. @@ -314,6 +318,24 @@ func UnmarshalMerge(buf []byte, pb Message) error { return NewBuffer(buf).Unmarshal(pb) } +// DecodeMessage reads a count-delimited message from the Buffer. +func (p *Buffer) DecodeMessage(pb Message) error { + enc, err := p.DecodeRawBytes(false) + if err != nil { + return err + } + return NewBuffer(enc).Unmarshal(pb) +} + +// DecodeGroup reads a tag-delimited group from the Buffer. +func (p *Buffer) DecodeGroup(pb Message) error { + typ, base, err := getbase(pb) + if err != nil { + return err + } + return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) +} + // Unmarshal parses the protocol buffer representation in the // Buffer and places the decoded result in pb. If the struct // underlying pb does not match the data in the buffer, the results can be @@ -377,6 +399,20 @@ func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group continue } } + // Maybe it's a oneof? + if prop.oneofUnmarshaler != nil { + m := structPointer_Interface(base, st).(Message) + // First return value indicates whether tag is a oneof field. + ok, err = prop.oneofUnmarshaler(m, tag, wire, o) + if err == ErrInternalBadWireType { + // Map the error to something more descriptive. + // Do the formatting here to save generated code space. + err = fmt.Errorf("bad wiretype for oneof field in %T", m) + } + if ok { + continue + } + } err = o.skipAndSave(st, tag, wire, base, prop.unrecField) continue } @@ -518,9 +554,7 @@ func (o *Buffer) dec_string(p *Properties, base structPointer) error { if err != nil { return err } - sp := new(string) - *sp = s - *structPointer_String(base, p.field) = sp + *structPointer_String(base, p.field) = &s return nil } @@ -563,9 +597,13 @@ func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error return err } nb := int(nn) // number of bytes of encoded bools + fin := o.index + nb + if fin < o.index { + return errOverflow + } y := *v - for i := 0; i < nb; i++ { + for o.index < fin { u, err := p.valDec(o) if err != nil { return err @@ -677,7 +715,7 @@ func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { oi := o.index // index at the end of this map entry o.index -= len(raw) // move buffer back to start of map entry - mptr := structPointer_Map(base, p.field, p.mtype) // *map[K]V + mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V if mptr.Elem().IsNil() { mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) } @@ -729,8 +767,14 @@ func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { return fmt.Errorf("proto: bad map data tag %d", raw[0]) } } + keyelem, valelem := keyptr.Elem(), valptr.Elem() + if !keyelem.IsValid() || !valelem.IsValid() { + // We did not decode the key or the value in the map entry. + // Either way, it's an invalid map entry. + return fmt.Errorf("proto: bad map data: missing key/val") + } - v.SetMapIndex(keyptr.Elem(), valptr.Elem()) + v.SetMapIndex(keyelem, valelem) return nil } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go index 1512d605b..231b07401 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go @@ -60,9 +60,9 @@ func (e *RequiredNotSetError) Error() string { } var ( - // ErrRepeatedHasNil is the error returned if Marshal is called with + // errRepeatedHasNil is the error returned if Marshal is called with // a struct with a repeated field containing a nil element. - ErrRepeatedHasNil = errors.New("proto: repeated field has nil element") + errRepeatedHasNil = errors.New("proto: repeated field has nil element") // ErrNil is the error returned if Marshal is called with nil. ErrNil = errors.New("proto: Marshal called with nil") @@ -105,6 +105,11 @@ func (p *Buffer) EncodeVarint(x uint64) error { return nil } +// SizeVarint returns the varint encoding size of an integer. +func SizeVarint(x uint64) int { + return sizeVarint(x) +} + func sizeVarint(x uint64) (n int) { for { n++ @@ -228,6 +233,20 @@ func Marshal(pb Message) ([]byte, error) { return p.buf, err } +// EncodeMessage writes the protocol buffer to the Buffer, +// prefixed by a varint-encoded length. +func (p *Buffer) EncodeMessage(pb Message) error { + t, base, err := getbase(pb) + if structPointer_IsNil(base) { + return ErrNil + } + if err == nil { + var state errorState + err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) + } + return err +} + // Marshal takes the protocol buffer // and encodes it into the wire format, writing the result to the // Buffer. @@ -318,7 +337,7 @@ func size_bool(p *Properties, base structPointer) int { func size_proto3_bool(p *Properties, base structPointer) int { v := *structPointer_BoolVal(base, p.field) - if !v { + if !v && !p.oneof { return 0 } return len(p.tagcode) + 1 // each bool takes exactly one byte @@ -361,7 +380,7 @@ func size_int32(p *Properties, base structPointer) (n int) { func size_proto3_int32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 { + if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) @@ -407,7 +426,7 @@ func size_uint32(p *Properties, base structPointer) (n int) { func size_proto3_uint32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := word32Val_Get(v) - if x == 0 { + if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) @@ -452,7 +471,7 @@ func size_int64(p *Properties, base structPointer) (n int) { func size_proto3_int64(p *Properties, base structPointer) (n int) { v := structPointer_Word64Val(base, p.field) x := word64Val_Get(v) - if x == 0 { + if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) @@ -495,7 +514,7 @@ func size_string(p *Properties, base structPointer) (n int) { func size_proto3_string(p *Properties, base structPointer) (n int) { v := *structPointer_StringVal(base, p.field) - if v == "" { + if v == "" && !p.oneof { return 0 } n += len(p.tagcode) @@ -529,7 +548,7 @@ func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(data) - return nil + return state.err } o.buf = append(o.buf, p.tagcode...) @@ -667,7 +686,7 @@ func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error func size_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) - if s == nil { + if s == nil && !p.oneof { return 0 } n += len(p.tagcode) @@ -677,7 +696,7 @@ func size_slice_byte(p *Properties, base structPointer) (n int) { func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) - if len(s) == 0 { + if len(s) == 0 && !p.oneof { return 0 } n += len(p.tagcode) @@ -939,7 +958,7 @@ func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) err for i := 0; i < l; i++ { structp := s.Index(i) if structPointer_IsNil(structp) { - return ErrRepeatedHasNil + return errRepeatedHasNil } // Can the object marshal itself? @@ -958,7 +977,7 @@ func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) err err := o.enc_len_struct(p.sprop, structp, &state) if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { - return ErrRepeatedHasNil + return errRepeatedHasNil } return err } @@ -1001,7 +1020,7 @@ func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error for i := 0; i < l; i++ { b := s.Index(i) if structPointer_IsNil(b) { - return ErrRepeatedHasNil + return errRepeatedHasNil } o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) @@ -1010,7 +1029,7 @@ func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { - return ErrRepeatedHasNil + return errRepeatedHasNil } return err } @@ -1084,7 +1103,7 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { repeated MapFieldEntry map_field = N; */ - v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V + v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V if v.Len() == 0 { return nil } @@ -1101,11 +1120,15 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { return nil } - keys := v.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { + // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. + for _, key := range v.MapKeys() { val := v.MapIndex(key) + // The only illegal map entry values are nil message pointers. + if val.Kind() == reflect.Ptr && val.IsNil() { + return errors.New("proto: map has nil element") + } + keycopy.Set(key) valcopy.Set(val) @@ -1118,7 +1141,7 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { } func size_new_map(p *Properties, base structPointer) int { - v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V + v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) @@ -1128,10 +1151,12 @@ func size_new_map(p *Properties, base structPointer) int { keycopy.Set(key) valcopy.Set(val) - // Tag codes are two bytes per map entry. - n += 2 - n += p.mkeyprop.size(p.mkeyprop, keybase) - n += p.mvalprop.size(p.mvalprop, valbase) + // Tag codes for key and val are the responsibility of the sub-sizer. + keysize := p.mkeyprop.size(p.mkeyprop, keybase) + valsize := p.mvalprop.size(p.mvalprop, valbase) + entry := keysize + valsize + // Add on tag code and length of map entry itself. + n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry } return n } @@ -1184,6 +1209,9 @@ func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { if p.Required && state.err == nil { state.err = &RequiredNotSetError{p.Name} } + } else if err == errRepeatedHasNil { + // Give more context to nil values in repeated fields. + return errors.New("repeated field " + p.OrigName + " has nil element") } else if !state.shouldContinue(err, p) { return err } @@ -1191,6 +1219,14 @@ func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { } } + // Do oneof fields. + if prop.oneofMarshaler != nil { + m := structPointer_Interface(base, prop.stype).(Message) + if err := prop.oneofMarshaler(m, o); err != nil { + return err + } + } + // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) @@ -1216,6 +1252,12 @@ func size_struct(prop *StructProperties, base structPointer) (n int) { n += len(v) } + // Factor in any oneof fields. + if prop.oneofSizer != nil { + m := structPointer_Interface(base, prop.stype).(Message) + n += prop.oneofSizer(m) + } + return } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go index d8673a3e9..f5db1def3 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go @@ -30,7 +30,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Protocol buffer comparison. -// TODO: MessageSet. package proto @@ -51,7 +50,9 @@ Equality is defined in this way: are equal, and extensions sets are equal. - Two set scalar fields are equal iff their values are equal. If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. + NaN != x for all x, including NaN. If the message is defined + in a proto3 .proto file, fields are not "set"; specifically, + zero length proto3 "bytes" fields are equal (nil == {}). - Two repeated fields are equal iff their lengths are the same, and their corresponding elements are equal (a "bytes" field, although represented by []byte, is not a repeated field) @@ -89,6 +90,7 @@ func Equal(a, b Message) bool { // v1 and v2 are known to have the same type. func equalStruct(v1, v2 reflect.Value) bool { + sprop := GetProperties(v1.Type()) for i := 0; i < v1.NumField(); i++ { f := v1.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { @@ -114,7 +116,7 @@ func equalStruct(v1, v2 reflect.Value) bool { } f1, f2 = f1.Elem(), f2.Elem() } - if !equalAny(f1, f2) { + if !equalAny(f1, f2, sprop.Prop[i]) { return false } } @@ -141,7 +143,8 @@ func equalStruct(v1, v2 reflect.Value) bool { } // v1 and v2 are known to have the same type. -func equalAny(v1, v2 reflect.Value) bool { +// prop may be nil. +func equalAny(v1, v2 reflect.Value, prop *Properties) bool { if v1.Type() == protoMessageType { m1, _ := v1.Interface().(Message) m2, _ := v2.Interface().(Message) @@ -154,6 +157,17 @@ func equalAny(v1, v2 reflect.Value) bool { return v1.Float() == v2.Float() case reflect.Int32, reflect.Int64: return v1.Int() == v2.Int() + case reflect.Interface: + // Probably a oneof field; compare the inner values. + n1, n2 := v1.IsNil(), v2.IsNil() + if n1 || n2 { + return n1 == n2 + } + e1, e2 := v1.Elem(), v2.Elem() + if e1.Type() != e2.Type() { + return false + } + return equalAny(e1, e2, nil) case reflect.Map: if v1.Len() != v2.Len() { return false @@ -164,16 +178,22 @@ func equalAny(v1, v2 reflect.Value) bool { // This key was not found in the second map. return false } - if !equalAny(v1.MapIndex(key), val2) { + if !equalAny(v1.MapIndex(key), val2, nil) { return false } } return true case reflect.Ptr: - return equalAny(v1.Elem(), v2.Elem()) + return equalAny(v1.Elem(), v2.Elem(), prop) case reflect.Slice: if v1.Type().Elem().Kind() == reflect.Uint8 { // short circuit: []byte + + // Edge case: if this is in a proto3 message, a zero length + // bytes field is considered the zero value. + if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { + return true + } if v1.IsNil() != v2.IsNil() { return false } @@ -184,7 +204,7 @@ func equalAny(v1, v2 reflect.Value) bool { return false } for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i)) { + if !equalAny(v1.Index(i), v2.Index(i), prop) { return false } } @@ -219,7 +239,7 @@ func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool { if m1 != nil && m2 != nil { // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) { + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { return false } continue @@ -247,7 +267,7 @@ func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool { log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) return false } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) { + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { return false } } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go deleted file mode 100644 index cc25833ca..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "testing" - - pb "./testdata" - . "github.com/golang/protobuf/proto" -) - -// Four identical base messages. -// The init function adds extensions to some of them. -var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)} - -// Two messages with non-message extensions. -var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)} -var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)} - -func init() { - ext1 := &pb.Ext{Data: String("Kirk")} - ext2 := &pb.Ext{Data: String("Picard")} - - // messageWithExtension1a has ext1, but never marshals it. - if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1a failed: " + err.Error()) - } - - // messageWithExtension1b is the unmarshaled form of messageWithExtension1a. - if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1b failed: " + err.Error()) - } - buf, err := Marshal(messageWithExtension1b) - if err != nil { - panic("Marshal of 1b failed: " + err.Error()) - } - messageWithExtension1b.Reset() - if err := Unmarshal(buf, messageWithExtension1b); err != nil { - panic("Unmarshal of 1b failed: " + err.Error()) - } - - // messageWithExtension2 has ext2. - if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil { - panic("SetExtension on 2 failed: " + err.Error()) - } - - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil { - panic("SetExtension on Int32-1 failed: " + err.Error()) - } - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil { - panic("SetExtension on Int32-2 failed: " + err.Error()) - } -} - -var EqualTests = []struct { - desc string - a, b Message - exp bool -}{ - {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false}, - {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true}, - {"nil vs nil", nil, nil, true}, - {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true}, - {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false}, - {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false}, - - {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false}, - {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false}, - {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false}, - {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true}, - - {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false}, - {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false}, - {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false}, - {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true}, - {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true}, - {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true}, - {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true}, - - { - "nested, different", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}}, - false, - }, - { - "nested, equal", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - true, - }, - - {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true}, - {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true}, - {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false}, - { - "repeated bytes", - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - true, - }, - - {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false}, - {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true}, - {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false}, - - {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true}, - {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false}, - - { - "message with group", - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - true, - }, - - { - "map same", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - true, - }, - { - "map different entry", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}}, - false, - }, - { - "map different key only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}}, - false, - }, - { - "map different value only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}}, - false, - }, -} - -func TestEqual(t *testing.T) { - for _, tc := range EqualTests { - if res := Equal(tc.a, tc.b); res != tc.exp { - t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go index f7667fab4..054f4f1df 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go @@ -37,6 +37,7 @@ package proto import ( "errors" + "fmt" "reflect" "strconv" "sync" @@ -221,7 +222,7 @@ func ClearExtension(pb extendableProto, extension *ExtensionDesc) { } // GetExtension parses and returns the given extension of pb. -// If the extension is not present it returns ErrMissingExtension. +// If the extension is not present and has no default value it returns ErrMissingExtension. func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) { if err := checkExtensionTypes(pb, extension); err != nil { return nil, err @@ -230,8 +231,11 @@ func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, er emap := pb.ExtensionMap() e, ok := emap[extension.Field] if !ok { - return nil, ErrMissingExtension + // defaultExtensionValue returns the default value or + // ErrMissingExtension if there is no default. + return defaultExtensionValue(extension) } + if e.value != nil { // Already decoded. Check the descriptor, though. if e.desc != extension { @@ -257,12 +261,46 @@ func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, er return e.value, nil } +// defaultExtensionValue returns the default value for extension. +// If no default for an extension is defined ErrMissingExtension is returned. +func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { + t := reflect.TypeOf(extension.ExtensionType) + props := extensionProperties(extension) + + sf, _, err := fieldDefault(t, props) + if err != nil { + return nil, err + } + + if sf == nil || sf.value == nil { + // There is no default value. + return nil, ErrMissingExtension + } + + if t.Kind() != reflect.Ptr { + // We do not need to return a Ptr, we can directly return sf.value. + return sf.value, nil + } + + // We need to return an interface{} that is a pointer to sf.value. + value := reflect.New(t).Elem() + value.Set(reflect.New(value.Type().Elem())) + if sf.kind == reflect.Int32 { + // We may have an int32 or an enum, but the underlying data is int32. + // Since we can't set an int32 into a non int32 reflect.value directly + // set it as a int32. + value.Elem().SetInt(int64(sf.value.(int32))) + } else { + value.Elem().Set(reflect.ValueOf(sf.value)) + } + return value.Interface(), nil +} + // decodeExtension decodes an extension encoded in b. func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { o := NewBuffer(b) t := reflect.TypeOf(extension.ExtensionType) - rep := extension.repeated() props := extensionProperties(extension) @@ -284,7 +322,7 @@ func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { return nil, err } - if !rep || o.index >= len(o.buf) { + if o.index >= len(o.buf) { break } } @@ -321,6 +359,14 @@ func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{ if typ != reflect.TypeOf(value) { return errors.New("proto: bad extension value type") } + // nil extension values need to be caught early, because the + // encoder can't distinguish an ErrNil due to a nil extension + // from an ErrNil due to a missing field. Extensions are + // always optional, so the encoder would just swallow the error + // and drop all the extensions from the encoded message. + if reflect.ValueOf(value).IsNil() { + return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) + } pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value} return nil diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go deleted file mode 100644 index 451ad871a..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "testing" - - pb "./testdata" - "github.com/golang/protobuf/proto" -) - -func TestGetExtensionsWithMissingExtensions(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Fatalf("Could not set ext1: %s", ext1) - } - exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ - pb.E_Ext_More, - pb.E_Ext_Text, - }) - if err != nil { - t.Fatalf("GetExtensions() failed: %s", err) - } - if exts[0] != ext1 { - t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) - } - if exts[1] != nil { - t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) - } -} - -func TestGetExtensionStability(t *testing.T) { - check := func(m *pb.MyMessage) bool { - ext1, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - ext2, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - return ext1 == ext2 - } - msg := &pb.MyMessage{Count: proto.Int32(4)} - ext0 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { - t.Fatalf("Could not set ext1: %s", ext0) - } - if !check(msg) { - t.Errorf("GetExtension() not stable before marshaling") - } - bb, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("Marshal() failed: %s", err) - } - msg1 := &pb.MyMessage{} - err = proto.Unmarshal(bb, msg1) - if err != nil { - t.Fatalf("Unmarshal() failed: %s", err) - } - if !check(msg1) { - t.Errorf("GetExtension() not stable after unmarshaling") - } -} - -func TestExtensionsRoundTrip(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{ - Data: proto.String("hi"), - } - ext2 := &pb.Ext{ - Data: proto.String("there"), - } - exists := proto.HasExtension(msg, pb.E_Ext_More) - if exists { - t.Error("Extension More present unexpectedly") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Error(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { - t.Error(err) - } - e, err := proto.GetExtension(msg, pb.E_Ext_More) - if err != nil { - t.Error(err) - } - x, ok := e.(*pb.Ext) - if !ok { - t.Errorf("e has type %T, expected testdata.Ext", e) - } else if *x.Data != "there" { - t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) - } - proto.ClearExtension(msg, pb.E_Ext_More) - if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { - t.Errorf("got %v, expected ErrMissingExtension", e) - } - if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { - t.Error("expected bad extension error, got nil") - } - if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { - t.Error("expected extension err") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { - t.Error("expected some sort of type mismatch error, got nil") - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go index 87c6b9d1a..0de8f8dff 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go @@ -30,171 +30,237 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* - Package proto converts data structures to and from the wire format of - protocol buffers. It works in concert with the Go source code generated - for .proto files by the protocol compiler. +Package proto converts data structures to and from the wire format of +protocol buffers. It works in concert with the Go source code generated +for .proto files by the protocol compiler. - A summary of the properties of the protocol buffer interface - for a protocol buffer variable v: +A summary of the properties of the protocol buffer interface +for a protocol buffer variable v: - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - Helpers for getting values are superseded by the - GetFoo methods and their use is deprecated. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed with the enum's type name. Enum types have - a String method, and a Enum method to assist in message construction. - - Nested groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Marshal and Unmarshal are functions to encode and decode the wire format. + - Names are turned from camel_case to CamelCase for export. + - There are no methods on v to set fields; just treat + them as structure fields. + - There are getters that return a field's value if set, + and return the field's default value if unset. + The getters work even if the receiver is a nil message. + - The zero value for a struct is its correct initialization state. + All desired fields must be set before marshaling. + - A Reset() method will restore a protobuf struct to its zero state. + - Non-repeated fields are pointers to the values; nil means unset. + That is, optional or required field int32 f becomes F *int32. + - Repeated fields are slices. + - Helper functions are available to aid the setting of fields. + msg.Foo = proto.String("hello") // set field + - Constants are defined to hold the default values of all fields that + have them. They have the form Default_StructName_FieldName. + Because the getter methods handle defaulted values, + direct use of these constants should be rare. + - Enums are given type names and maps from names to values. + Enum values are prefixed by the enclosing message's name, or by the + enum's type name if it is a top-level enum. Enum types have a String + method, and a Enum method to assist in message construction. + - Nested messages, groups and enums have type names prefixed with the name of + the surrounding message type. + - Extensions are given descriptor names that start with E_, + followed by an underscore-delimited list of the nested messages + that contain it (if any) followed by the CamelCased name of the + extension field itself. HasExtension, ClearExtension, GetExtension + and SetExtension are functions for manipulating extensions. + - Oneof field sets are given a single field in their message, + with distinguished wrapper types for each possible field value. + - Marshal and Unmarshal are functions to encode and decode the wire format. - The simplest way to describe this is to see an example. - Given file test.proto, containing +When the .proto file specifies `syntax="proto3"`, there are some differences: - package example; + - Non-repeated fields of non-message type are values instead of pointers. + - Getters are only generated for message and oneof fields. + - Enum types do not get an Enum method. - enum FOO { X = 17; }; +The simplest way to describe this is to see an example. +Given file test.proto, containing - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } + package example; + + enum FOO { X = 17; } + + message Test { + required string label = 1; + optional int32 type = 2 [default=77]; + repeated int64 reps = 3; + optional group OptionalGroup = 4 { + required string RequiredField = 5; + } + oneof union { + int32 number = 6; + string name = 7; + } + } + +The resulting file, test.pb.go, is: + + package example + + import proto "github.com/golang/protobuf/proto" + import math "math" + + type FOO int32 + const ( + FOO_X FOO = 17 + ) + var FOO_name = map[int32]string{ + 17: "X", + } + var FOO_value = map[string]int32{ + "X": 17, + } + + func (x FOO) Enum() *FOO { + p := new(FOO) + *p = x + return p + } + func (x FOO) String() string { + return proto.EnumName(FOO_name, int32(x)) + } + func (x *FOO) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FOO_value, data) + if err != nil { + return err } + *x = FOO(value) + return nil + } - The resulting file, test.pb.go, is: + type Test struct { + Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` + Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` + Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` + Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` + // Types that are valid to be assigned to Union: + // *Test_Number + // *Test_Name + Union isTest_Union `protobuf_oneof:"union"` + XXX_unrecognized []byte `json:"-"` + } + func (m *Test) Reset() { *m = Test{} } + func (m *Test) String() string { return proto.CompactTextString(m) } + func (*Test) ProtoMessage() {} - package example + type isTest_Union interface { + isTest_Union() + } - import "github.com/golang/protobuf/proto" + type Test_Number struct { + Number int32 `protobuf:"varint,6,opt,name=number"` + } + type Test_Name struct { + Name string `protobuf:"bytes,7,opt,name=name"` + } - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", + func (*Test_Number) isTest_Union() {} + func (*Test_Name) isTest_Union() {} + + func (m *Test) GetUnion() isTest_Union { + if m != nil { + return m.Union } - var FOO_value = map[string]int32{ - "X": 17, + return nil + } + const Default_Test_Type int32 = 77 + + func (m *Test) GetLabel() string { + if m != nil && m.Label != nil { + return *m.Label } + return "" + } - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p + func (m *Test) GetType() int32 { + if m != nil && m.Type != nil { + return *m.Type } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) + return Default_Test_Type + } + + func (m *Test) GetOptionalgroup() *Test_OptionalGroup { + if m != nil { + return m.Optionalgroup } + return nil + } - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` + type Test_OptionalGroup struct { + RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` + } + func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } + func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } + + func (m *Test_OptionalGroup) GetRequiredField() string { + if m != nil && m.RequiredField != nil { + return *m.RequiredField } - func (this *Test) Reset() { *this = Test{} } - func (this *Test) String() string { return proto.CompactTextString(this) } - const Default_Test_Type int32 = 77 + return "" + } - func (this *Test) GetLabel() string { - if this != nil && this.Label != nil { - return *this.Label - } - return "" + func (m *Test) GetNumber() int32 { + if x, ok := m.GetUnion().(*Test_Number); ok { + return x.Number } + return 0 + } - func (this *Test) GetType() int32 { - if this != nil && this.Type != nil { - return *this.Type - } - return Default_Test_Type + func (m *Test) GetName() string { + if x, ok := m.GetUnion().(*Test_Name); ok { + return x.Name } + return "" + } - func (this *Test) GetOptionalgroup() *Test_OptionalGroup { - if this != nil { - return this.Optionalgroup - } - return nil + func init() { + proto.RegisterEnum("example.FOO", FOO_name, FOO_value) + } + +To create and play with a Test object: + + package main + + import ( + "log" + + "github.com/golang/protobuf/proto" + pb "./example.pb" + ) + + func main() { + test := &pb.Test{ + Label: proto.String("hello"), + Type: proto.Int32(17), + Reps: []int64{1, 2, 3}, + Optionalgroup: &pb.Test_OptionalGroup{ + RequiredField: proto.String("good bye"), + }, + Union: &pb.Test_Name{"fred"}, } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` + data, err := proto.Marshal(test) + if err != nil { + log.Fatal("marshaling error: ", err) } - func (this *Test_OptionalGroup) Reset() { *this = Test_OptionalGroup{} } - func (this *Test_OptionalGroup) String() string { return proto.CompactTextString(this) } - - func (this *Test_OptionalGroup) GetRequiredField() string { - if this != nil && this.RequiredField != nil { - return *this.RequiredField - } - return "" + newTest := &pb.Test{} + err = proto.Unmarshal(data, newTest) + if err != nil { + log.Fatal("unmarshaling error: ", err) } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) + // Now test and newTest contain the same data. + if test.GetLabel() != newTest.GetLabel() { + log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } - - To create and play with a Test object: - - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - "./example.pb" - ) - - func main() { - test := &example.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Optionalgroup: &example.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := new(example.Test) - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // etc. + // Use a type switch to determine which oneof was set. + switch u := test.Union.(type) { + case *pb.Test_Number: // u.Number contains the number. + case *pb.Test_Name: // u.Name contains the string. } + // etc. + } */ package proto @@ -203,6 +269,7 @@ import ( "fmt" "log" "reflect" + "sort" "strconv" "sync" ) @@ -377,13 +444,13 @@ func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, // DebugPrint dumps the encoded data in b in a debugging format with a header // including the string s. Used in testing but made available for general debugging. -func (o *Buffer) DebugPrint(s string, b []byte) { +func (p *Buffer) DebugPrint(s string, b []byte) { var u uint64 - obuf := o.buf - index := o.index - o.buf = b - o.index = 0 + obuf := p.buf + index := p.index + p.buf = b + p.index = 0 depth := 0 fmt.Printf("\n--- %s ---\n", s) @@ -394,12 +461,12 @@ out: fmt.Print(" ") } - index := o.index - if index == len(o.buf) { + index := p.index + if index == len(p.buf) { break } - op, err := o.DecodeVarint() + op, err := p.DecodeVarint() if err != nil { fmt.Printf("%3d: fetching op err %v\n", index, err) break out @@ -416,7 +483,7 @@ out: case WireBytes: var r []byte - r, err = o.DecodeRawBytes(false) + r, err = p.DecodeRawBytes(false) if err != nil { break out } @@ -437,7 +504,7 @@ out: fmt.Printf("\n") case WireFixed32: - u, err = o.DecodeFixed32() + u, err = p.DecodeFixed32() if err != nil { fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) break out @@ -445,16 +512,15 @@ out: fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) case WireFixed64: - u, err = o.DecodeFixed64() + u, err = p.DecodeFixed64() if err != nil { fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - break case WireVarint: - u, err = o.DecodeVarint() + u, err = p.DecodeVarint() if err != nil { fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) break out @@ -462,30 +528,22 @@ out: fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) case WireStartGroup: - if err != nil { - fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err) - break out - } fmt.Printf("%3d: t=%3d start\n", index, tag) depth++ case WireEndGroup: depth-- - if err != nil { - fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err) - break out - } fmt.Printf("%3d: t=%3d end\n", index, tag) } } if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", o.index, depth) + fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) } fmt.Printf("\n") - o.buf = obuf - o.index = index + p.buf = obuf + p.index = index } // SetDefaults sets unset protocol buffer fields to their default values. @@ -599,13 +657,15 @@ func setDefaults(v reflect.Value, recur, zeros bool) { for _, ni := range dm.nested { f := v.Field(ni) - if f.IsNil() { - continue - } - // f is *T or []*T - if f.Kind() == reflect.Ptr { + // f is *T or []*T or map[T]*T + switch f.Kind() { + case reflect.Ptr: + if f.IsNil() { + continue + } setDefaults(f, recur, zeros) - } else { + + case reflect.Slice: for i := 0; i < f.Len(); i++ { e := f.Index(i) if e.IsNil() { @@ -613,6 +673,15 @@ func setDefaults(v reflect.Value, recur, zeros bool) { } setDefaults(e, recur, zeros) } + + case reflect.Map: + for _, k := range f.MapKeys() { + e := f.MapIndex(k) + if e.IsNil() { + continue + } + setDefaults(e, recur, zeros) + } } } } @@ -638,10 +707,6 @@ type scalarField struct { value interface{} // the proto-declared default value, or nil } -func ptrToStruct(t reflect.Type) bool { - return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct -} - // t is a struct type. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { sprop := GetProperties(t) @@ -653,99 +718,177 @@ func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { } ft := t.Field(fi).Type - // nested messages - if ptrToStruct(ft) || (ft.Kind() == reflect.Slice && ptrToStruct(ft.Elem())) { + sf, nested, err := fieldDefault(ft, prop) + switch { + case err != nil: + log.Print(err) + case nested: dm.nested = append(dm.nested, fi) - continue + case sf != nil: + sf.index = fi + dm.scalars = append(dm.scalars, *sf) } - - sf := scalarField{ - index: fi, - kind: ft.Elem().Kind(), - } - - // scalar fields without defaults - if !prop.HasDefault { - dm.scalars = append(dm.scalars, sf) - continue - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - log.Printf("proto: bad default bool %q: %v", prop.Default, err) - continue - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - log.Printf("proto: bad default float32 %q: %v", prop.Default, err) - continue - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - log.Printf("proto: bad default float64 %q: %v", prop.Default, err) - continue - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - log.Printf("proto: bad default int32 %q: %v", prop.Default, err) - continue - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - log.Printf("proto: bad default int64 %q: %v", prop.Default, err) - continue - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - log.Printf("proto: bad default uint32 %q: %v", prop.Default, err) - continue - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - log.Printf("proto: bad default uint64 %q: %v", prop.Default, err) - continue - } - sf.value = x - default: - log.Printf("proto: unhandled def kind %v", ft.Elem().Kind()) - continue - } - - dm.scalars = append(dm.scalars, sf) } return dm } +// fieldDefault returns the scalarField for field type ft. +// sf will be nil if the field can not have a default. +// nestedMessage will be true if this is a nested message. +// Note that sf.index is not set on return. +func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { + var canHaveDefault bool + switch ft.Kind() { + case reflect.Ptr: + if ft.Elem().Kind() == reflect.Struct { + nestedMessage = true + } else { + canHaveDefault = true // proto2 scalar field + } + + case reflect.Slice: + switch ft.Elem().Kind() { + case reflect.Ptr: + nestedMessage = true // repeated message + case reflect.Uint8: + canHaveDefault = true // bytes field + } + + case reflect.Map: + if ft.Elem().Kind() == reflect.Ptr { + nestedMessage = true // map with message values + } + } + + if !canHaveDefault { + if nestedMessage { + return nil, true, nil + } + return nil, false, nil + } + + // We now know that ft is a pointer or slice. + sf = &scalarField{kind: ft.Elem().Kind()} + + // scalar fields without defaults + if !prop.HasDefault { + return sf, false, nil + } + + // a scalar field: either *T or []byte + switch ft.Elem().Kind() { + case reflect.Bool: + x, err := strconv.ParseBool(prop.Default) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Float32: + x, err := strconv.ParseFloat(prop.Default, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) + } + sf.value = float32(x) + case reflect.Float64: + x, err := strconv.ParseFloat(prop.Default, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Int32: + x, err := strconv.ParseInt(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) + } + sf.value = int32(x) + case reflect.Int64: + x, err := strconv.ParseInt(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.String: + sf.value = prop.Default + case reflect.Uint8: + // []byte (not *uint8) + sf.value = []byte(prop.Default) + case reflect.Uint32: + x, err := strconv.ParseUint(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) + } + sf.value = uint32(x) + case reflect.Uint64: + x, err := strconv.ParseUint(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) + } + sf.value = x + default: + return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) + } + + return sf, false, nil +} + // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. -type mapKeys []reflect.Value +func mapKeys(vs []reflect.Value) sort.Interface { + s := mapKeySorter{ + vs: vs, + // default Less function: textual comparison + less: func(a, b reflect.Value) bool { + return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) + }, + } -func (s mapKeys) Len() int { return len(s) } -func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s mapKeys) Less(i, j int) bool { - return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) + // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; + // numeric keys are sorted numerically. + if len(vs) == 0 { + return s + } + switch vs[0].Kind() { + case reflect.Int32, reflect.Int64: + s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } + case reflect.Uint32, reflect.Uint64: + s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } + } + + return s } + +type mapKeySorter struct { + vs []reflect.Value + less func(a, b reflect.Value) bool +} + +func (s mapKeySorter) Len() int { return len(s.vs) } +func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } +func (s mapKeySorter) Less(i, j int) bool { + return s.less(s.vs[i], s.vs[j]) +} + +// isProto3Zero reports whether v is a zero proto3 value. +func isProto3Zero(v reflect.Value) bool { + switch v.Kind() { + case reflect.Bool: + return !v.Bool() + case reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint32, reflect.Uint64: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.String: + return v.String() == "" + } + return false +} + +// ProtoPackageIsVersion1 is referenced from generated protocol buffer files +// to assert that that code is compatible with this version of the proto package. +const ProtoPackageIsVersion1 = true diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go index 9d912bce1..e25e01e63 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go @@ -44,11 +44,11 @@ import ( "sort" ) -// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID. +// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. // A message type ID is required for storing a protocol buffer in a message set. -var ErrNoMessageTypeId = errors.New("proto does not have a message type ID") +var errNoMessageTypeID = errors.New("proto does not have a message type ID") -// The first two types (_MessageSet_Item and MessageSet) +// The first two types (_MessageSet_Item and messageSet) // model what the protocol compiler produces for the following protocol message: // message MessageSet { // repeated group Item = 1 { @@ -58,27 +58,20 @@ var ErrNoMessageTypeId = errors.New("proto does not have a message type ID") // } // That is the MessageSet wire format. We can't use a proto to generate these // because that would introduce a circular dependency between it and this package. -// -// When a proto1 proto has a field that looks like: -// optional message info = 3; -// the protocol compiler produces a field in the generated struct that looks like: -// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"` -// The package is automatically inserted so there is no need for that proto file to -// import this package. type _MessageSet_Item struct { TypeId *int32 `protobuf:"varint,2,req,name=type_id"` Message []byte `protobuf:"bytes,3,req,name=message"` } -type MessageSet struct { +type messageSet struct { Item []*_MessageSet_Item `protobuf:"group,1,rep"` XXX_unrecognized []byte // TODO: caching? } -// Make sure MessageSet is a Message. -var _ Message = (*MessageSet)(nil) +// Make sure messageSet is a Message. +var _ Message = (*messageSet)(nil) // messageTypeIder is an interface satisfied by a protocol buffer type // that may be stored in a MessageSet. @@ -86,7 +79,7 @@ type messageTypeIder interface { MessageTypeId() int32 } -func (ms *MessageSet) find(pb Message) *_MessageSet_Item { +func (ms *messageSet) find(pb Message) *_MessageSet_Item { mti, ok := pb.(messageTypeIder) if !ok { return nil @@ -100,24 +93,24 @@ func (ms *MessageSet) find(pb Message) *_MessageSet_Item { return nil } -func (ms *MessageSet) Has(pb Message) bool { +func (ms *messageSet) Has(pb Message) bool { if ms.find(pb) != nil { return true } return false } -func (ms *MessageSet) Unmarshal(pb Message) error { +func (ms *messageSet) Unmarshal(pb Message) error { if item := ms.find(pb); item != nil { return Unmarshal(item.Message, pb) } if _, ok := pb.(messageTypeIder); !ok { - return ErrNoMessageTypeId + return errNoMessageTypeID } return nil // TODO: return error instead? } -func (ms *MessageSet) Marshal(pb Message) error { +func (ms *messageSet) Marshal(pb Message) error { msg, err := Marshal(pb) if err != nil { return err @@ -130,7 +123,7 @@ func (ms *MessageSet) Marshal(pb Message) error { mti, ok := pb.(messageTypeIder) if !ok { - return ErrNoMessageTypeId + return errNoMessageTypeID } mtid := mti.MessageTypeId() @@ -141,9 +134,9 @@ func (ms *MessageSet) Marshal(pb Message) error { return nil } -func (ms *MessageSet) Reset() { *ms = MessageSet{} } -func (ms *MessageSet) String() string { return CompactTextString(ms) } -func (*MessageSet) ProtoMessage() {} +func (ms *messageSet) Reset() { *ms = messageSet{} } +func (ms *messageSet) String() string { return CompactTextString(ms) } +func (*messageSet) ProtoMessage() {} // Support for the message_set_wire_format message option. @@ -169,7 +162,7 @@ func MarshalMessageSet(m map[int32]Extension) ([]byte, error) { } sort.Ints(ids) - ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))} + ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))} for _, id := range ids { e := m[int32(id)] // Remove the wire type and field number varint, as well as the length varint. @@ -186,7 +179,7 @@ func MarshalMessageSet(m map[int32]Extension) ([]byte, error) { // UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. // It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error { - ms := new(MessageSet) + ms := new(messageSet) if err := Unmarshal(buf, ms); err != nil { return err } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100644 index 7c29bccf4..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &MessageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - m := make(map[int32]Extension) - if err := UnmarshalMessageSet(b, m); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := m[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", m) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go index 93259a3d6..749919d25 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build appengine,!appenginevm +// +build appengine // This file contains an implementation of proto field accesses using package reflect. // It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can @@ -144,8 +144,8 @@ func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return structPointer_ifield(p, f).(*map[int32]Extension) } -// Map returns the reflect.Value for the address of a map field in the struct. -func structPointer_Map(p structPointer, f field, typ reflect.Type) reflect.Value { +// NewAt returns the reflect.Value for a pointer to a field in the struct. +func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { return structPointer_field(p, f).Addr() } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go index c52db1ca5..e9be0fe92 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build !appengine appenginevm +// +build !appengine // This file contains the implementation of the proto field accesses using package unsafe. @@ -130,8 +130,8 @@ func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) } -// Map returns the reflect.Value for the address of a map field in the struct. -func structPointer_Map(p structPointer, f field, typ reflect.Type) reflect.Value { +// NewAt returns the reflect.Value for a pointer to a field in the struct. +func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go index 730a59579..d4531c056 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go @@ -37,6 +37,7 @@ package proto import ( "fmt" + "log" "os" "reflect" "sort" @@ -84,6 +85,15 @@ type decoder func(p *Buffer, prop *Properties, base structPointer) error // A valueDecoder decodes a single integer in a particular encoding. type valueDecoder func(o *Buffer) (x uint64, err error) +// A oneofMarshaler does the marshaling for all oneof fields in a message. +type oneofMarshaler func(Message, *Buffer) error + +// A oneofUnmarshaler does the unmarshaling for a oneof field in a message. +type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error) + +// A oneofSizer does the sizing for all oneof fields in a message. +type oneofSizer func(Message) int + // tagMap is an optimization over map[int]int for typical protocol buffer // use-cases. Encoded protocol buffers are often in tag order with small tag // numbers. @@ -132,6 +142,22 @@ type StructProperties struct { order []int // list of struct field numbers in tag order unrecField field // field id of the XXX_unrecognized []byte field extendable bool // is this an extendable proto + + oneofMarshaler oneofMarshaler + oneofUnmarshaler oneofUnmarshaler + oneofSizer oneofSizer + stype reflect.Type + + // OneofTypes contains information about the oneof fields in this message. + // It is keyed by the original name of a field. + OneofTypes map[string]*OneofProperties +} + +// OneofProperties represents information about a specific field in a oneof. +type OneofProperties struct { + Type reflect.Type // pointer to generated struct type for this oneof field + Field int // struct field number of the containing oneof in the message + Prop *Properties } // Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. @@ -156,6 +182,7 @@ type Properties struct { Packed bool // relevant for repeated primitives only Enum string // set for enum types only proto3 bool // whether this is known to be a proto3 field; set for []byte only + oneof bool // whether this is a oneof field Default string // default value HasDefault bool // whether an explicit default was provided @@ -208,6 +235,9 @@ func (p *Properties) String() string { if p.proto3 { s += ",proto3" } + if p.oneof { + s += ",oneof" + } if len(p.Enum) > 0 { s += ",enum=" + p.Enum } @@ -284,6 +314,8 @@ func (p *Properties) Parse(s string) { p.Enum = f[5:] case f == "proto3": p.proto3 = true + case f == "oneof": + p.oneof = true case strings.HasPrefix(f, "def="): p.HasDefault = true p.Default = f[4:] // rest of string @@ -440,7 +472,12 @@ func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lock p.enc = (*Buffer).enc_slice_byte p.dec = (*Buffer).dec_slice_byte p.size = size_slice_byte - if p.proto3 { + // This is a []byte, which is either a bytes field, + // or the value of a map field. In the latter case, + // we always encode an empty []byte, so we should not + // use the proto3 enc/size funcs. + // f == nil iff this is the key/value of a map field. + if p.proto3 && f != nil { p.enc = (*Buffer).enc_proto3_slice_byte p.size = size_proto3_slice_byte } @@ -595,7 +632,7 @@ func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructF } var ( - mutex sync.Mutex + propertiesMu sync.RWMutex propertiesMap = make(map[reflect.Type]*StructProperties) ) @@ -605,13 +642,26 @@ func GetProperties(t reflect.Type) *StructProperties { if t.Kind() != reflect.Struct { panic("proto: type must have kind struct") } - mutex.Lock() - sprop := getPropertiesLocked(t) - mutex.Unlock() + + // Most calls to GetProperties in a long-running program will be + // retrieving details for types we have seen before. + propertiesMu.RLock() + sprop, ok := propertiesMap[t] + propertiesMu.RUnlock() + if ok { + if collectStats { + stats.Chit++ + } + return sprop + } + + propertiesMu.Lock() + sprop = getPropertiesLocked(t) + propertiesMu.Unlock() return sprop } -// getPropertiesLocked requires that mutex is held. +// getPropertiesLocked requires that propertiesMu is held. func getPropertiesLocked(t reflect.Type) *StructProperties { if prop, ok := propertiesMap[t]; ok { if collectStats { @@ -647,6 +697,7 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { if f.Name == "XXX_unrecognized" { // special case prop.unrecField = toField(&f) } + oneof := f.Tag.Get("protobuf_oneof") != "" // special case prop.Prop[i] = p prop.order[i] = i if debug { @@ -656,7 +707,7 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { } print("\n") } - if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") { + if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && !oneof { fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") } } @@ -664,6 +715,41 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { // Re-order prop.order. sort.Sort(prop) + type oneofMessage interface { + XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) + } + if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { + var oots []interface{} + prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs() + prop.stype = t + + // Interpret oneof metadata. + prop.OneofTypes = make(map[string]*OneofProperties) + for _, oot := range oots { + oop := &OneofProperties{ + Type: reflect.ValueOf(oot).Type(), // *T + Prop: new(Properties), + } + sft := oop.Type.Elem().Field(0) + oop.Prop.Name = sft.Name + oop.Prop.Parse(sft.Tag.Get("protobuf")) + // There will be exactly one interface field that + // this new value is assignable to. + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Type.Kind() != reflect.Interface { + continue + } + if !oop.Type.AssignableTo(f.Type) { + continue + } + oop.Field = i + break + } + prop.OneofTypes[oop.Prop.OrigName] = oop + } + } + // build required counts // build tags reqCount := 0 @@ -722,3 +808,35 @@ func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[ } enumValueMaps[typeName] = valueMap } + +// EnumValueMap returns the mapping from names to integers of the +// enum type enumType, or a nil if not found. +func EnumValueMap(enumType string) map[string]int32 { + return enumValueMaps[enumType] +} + +// A registry of all linked message types. +// The string is a fully-qualified proto name ("pkg.Message"). +var ( + protoTypes = make(map[string]reflect.Type) + revProtoTypes = make(map[reflect.Type]string) +) + +// RegisterType is called from generated code and maps from the fully qualified +// proto name to the type (pointer to struct) of the protocol buffer. +func RegisterType(x Message, name string) { + if _, ok := protoTypes[name]; ok { + // TODO: Some day, make this a panic. + log.Printf("proto: duplicate proto type registered: %s", name) + return + } + t := reflect.TypeOf(x) + protoTypes[name] = t + revProtoTypes[t] = name +} + +// MessageName returns the fully-qualified proto name for the given message type. +func MessageName(x Message) string { return revProtoTypes[reflect.TypeOf(x)] } + +// MessageType returns the message type (pointer to struct) for a named message. +func MessageType(name string) reflect.Type { return protoTypes[name] } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/Makefile deleted file mode 100644 index 75144b582..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2014 The Go Authors. All rights reserved. -# https://github.com/golang/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. -# * 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. - - -include ../../Make.protobuf - -all: regenerate - -regenerate: - rm -f proto3.pb.go - make proto3.pb.go - -# The following rules are just aids to development. Not needed for typical testing. - -diff: regenerate - git diff proto3.pb.go diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto deleted file mode 100644 index 3e327ded1..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto +++ /dev/null @@ -1,58 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -syntax = "proto3"; - -package proto3_proto; - -message Message { - enum Humour { - UNKNOWN = 0; - PUNS = 1; - SLAPSTICK = 2; - BILL_BAILEY = 3; - } - - string name = 1; - Humour hilarity = 2; - uint32 height_in_cm = 3; - bytes data = 4; - int64 result_count = 7; - bool true_scotsman = 8; - float score = 9; - - repeated uint64 key = 5; - Nested nested = 6; -} - -message Nested { - string bunny = 1; -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100644 index d4c96a9e7..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "testing" - - pb "./proto3_proto" - "github.com/golang/protobuf/proto" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go deleted file mode 100644 index e5f92d6b9..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "log" - "testing" - - proto3pb "./proto3_proto" - pb "./testdata" - . "github.com/golang/protobuf/proto" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile deleted file mode 100644 index fc288628a..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/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. -# * 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. - - -include ../../Make.protobuf - -all: regenerate - -regenerate: - rm -f test.pb.go - make test.pb.go - -# The following rules are just aids to development. Not needed for typical testing. - -diff: regenerate - git diff test.pb.go - -restore: - cp test.pb.go.golden test.pb.go - -preserve: - cp test.pb.go test.pb.go.golden diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go deleted file mode 100644 index 7172d0e96..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -// Verify that the compiler output for test.proto is unchanged. - -package testdata - -import ( - "crypto/sha1" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "testing" -) - -// sum returns in string form (for easy comparison) the SHA-1 hash of the named file. -func sum(t *testing.T, name string) string { - data, err := ioutil.ReadFile(name) - if err != nil { - t.Fatal(err) - } - t.Logf("sum(%q): length is %d", name, len(data)) - hash := sha1.New() - _, err = hash.Write(data) - if err != nil { - t.Fatal(err) - } - return fmt.Sprintf("% x", hash.Sum(nil)) -} - -func run(t *testing.T, name string, args ...string) { - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err := cmd.Run() - if err != nil { - t.Fatal(err) - } -} - -func TestGolden(t *testing.T) { - // Compute the original checksum. - goldenSum := sum(t, "test.pb.go") - // Run the proto compiler. - run(t, "protoc", "--go_out="+os.TempDir(), "test.proto") - newFile := filepath.Join(os.TempDir(), "test.pb.go") - defer os.Remove(newFile) - // Compute the new checksum. - newSum := sum(t, newFile) - // Verify - if newSum != goldenSum { - run(t, "diff", "-u", "test.pb.go", newFile) - t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go deleted file mode 100644 index f47d9e0e3..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go +++ /dev/null @@ -1,2389 +0,0 @@ -// Code generated by protoc-gen-go. -// source: test.proto -// DO NOT EDIT! - -/* -Package testdata is a generated protocol buffer package. - -It is generated from these files: - test.proto - -It has these top-level messages: - GoEnum - GoTestField - GoTest - GoSkipTest - NonPackedTest - PackedTest - MaxTag - OldMessage - NewMessage - InnerMessage - OtherMessage - MyMessage - Ext - MyMessageSet - Empty - MessageList - Strings - Defaults - SubDefaults - RepeatedEnum - MoreRepeated - GroupOld - GroupNew - FloatingPoint - MessageWithMap -*/ -package testdata - -import proto "github.com/golang/protobuf/proto" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = math.Inf - -type FOO int32 - -const ( - FOO_FOO1 FOO = 1 -) - -var FOO_name = map[int32]string{ - 1: "FOO1", -} -var FOO_value = map[string]int32{ - "FOO1": 1, -} - -func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p -} -func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) -} -func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") - if err != nil { - return err - } - *x = FOO(value) - return nil -} - -// An enum, for completeness. -type GoTest_KIND int32 - -const ( - GoTest_VOID GoTest_KIND = 0 - // Basic types - GoTest_BOOL GoTest_KIND = 1 - GoTest_BYTES GoTest_KIND = 2 - GoTest_FINGERPRINT GoTest_KIND = 3 - GoTest_FLOAT GoTest_KIND = 4 - GoTest_INT GoTest_KIND = 5 - GoTest_STRING GoTest_KIND = 6 - GoTest_TIME GoTest_KIND = 7 - // Groupings - GoTest_TUPLE GoTest_KIND = 8 - GoTest_ARRAY GoTest_KIND = 9 - GoTest_MAP GoTest_KIND = 10 - // Table types - GoTest_TABLE GoTest_KIND = 11 - // Functions - GoTest_FUNCTION GoTest_KIND = 12 -) - -var GoTest_KIND_name = map[int32]string{ - 0: "VOID", - 1: "BOOL", - 2: "BYTES", - 3: "FINGERPRINT", - 4: "FLOAT", - 5: "INT", - 6: "STRING", - 7: "TIME", - 8: "TUPLE", - 9: "ARRAY", - 10: "MAP", - 11: "TABLE", - 12: "FUNCTION", -} -var GoTest_KIND_value = map[string]int32{ - "VOID": 0, - "BOOL": 1, - "BYTES": 2, - "FINGERPRINT": 3, - "FLOAT": 4, - "INT": 5, - "STRING": 6, - "TIME": 7, - "TUPLE": 8, - "ARRAY": 9, - "MAP": 10, - "TABLE": 11, - "FUNCTION": 12, -} - -func (x GoTest_KIND) Enum() *GoTest_KIND { - p := new(GoTest_KIND) - *p = x - return p -} -func (x GoTest_KIND) String() string { - return proto.EnumName(GoTest_KIND_name, int32(x)) -} -func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") - if err != nil { - return err - } - *x = GoTest_KIND(value) - return nil -} - -type MyMessage_Color int32 - -const ( - MyMessage_RED MyMessage_Color = 0 - MyMessage_GREEN MyMessage_Color = 1 - MyMessage_BLUE MyMessage_Color = 2 -) - -var MyMessage_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var MyMessage_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x MyMessage_Color) Enum() *MyMessage_Color { - p := new(MyMessage_Color) - *p = x - return p -} -func (x MyMessage_Color) String() string { - return proto.EnumName(MyMessage_Color_name, int32(x)) -} -func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") - if err != nil { - return err - } - *x = MyMessage_Color(value) - return nil -} - -type Defaults_Color int32 - -const ( - Defaults_RED Defaults_Color = 0 - Defaults_GREEN Defaults_Color = 1 - Defaults_BLUE Defaults_Color = 2 -) - -var Defaults_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Defaults_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Defaults_Color) Enum() *Defaults_Color { - p := new(Defaults_Color) - *p = x - return p -} -func (x Defaults_Color) String() string { - return proto.EnumName(Defaults_Color_name, int32(x)) -} -func (x *Defaults_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") - if err != nil { - return err - } - *x = Defaults_Color(value) - return nil -} - -type RepeatedEnum_Color int32 - -const ( - RepeatedEnum_RED RepeatedEnum_Color = 1 -) - -var RepeatedEnum_Color_name = map[int32]string{ - 1: "RED", -} -var RepeatedEnum_Color_value = map[string]int32{ - "RED": 1, -} - -func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { - p := new(RepeatedEnum_Color) - *p = x - return p -} -func (x RepeatedEnum_Color) String() string { - return proto.EnumName(RepeatedEnum_Color_name, int32(x)) -} -func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") - if err != nil { - return err - } - *x = RepeatedEnum_Color(value) - return nil -} - -type GoEnum struct { - Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoEnum) Reset() { *m = GoEnum{} } -func (m *GoEnum) String() string { return proto.CompactTextString(m) } -func (*GoEnum) ProtoMessage() {} - -func (m *GoEnum) GetFoo() FOO { - if m != nil && m.Foo != nil { - return *m.Foo - } - return FOO_FOO1 -} - -type GoTestField struct { - Label *string `protobuf:"bytes,1,req" json:"Label,omitempty"` - Type *string `protobuf:"bytes,2,req" json:"Type,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTestField) Reset() { *m = GoTestField{} } -func (m *GoTestField) String() string { return proto.CompactTextString(m) } -func (*GoTestField) ProtoMessage() {} - -func (m *GoTestField) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" -} - -func (m *GoTestField) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -type GoTest struct { - // Some typical parameters - Kind *GoTest_KIND `protobuf:"varint,1,req,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` - Table *string `protobuf:"bytes,2,opt" json:"Table,omitempty"` - Param *int32 `protobuf:"varint,3,opt" json:"Param,omitempty"` - // Required, repeated and optional foreign fields. - RequiredField *GoTestField `protobuf:"bytes,4,req" json:"RequiredField,omitempty"` - RepeatedField []*GoTestField `protobuf:"bytes,5,rep" json:"RepeatedField,omitempty"` - OptionalField *GoTestField `protobuf:"bytes,6,opt" json:"OptionalField,omitempty"` - // Required fields of all basic types - F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required" json:"F_Bool_required,omitempty"` - F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required" json:"F_Int32_required,omitempty"` - F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required" json:"F_Int64_required,omitempty"` - F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required" json:"F_Fixed32_required,omitempty"` - F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required" json:"F_Fixed64_required,omitempty"` - F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required" json:"F_Uint32_required,omitempty"` - F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required" json:"F_Uint64_required,omitempty"` - F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required" json:"F_Float_required,omitempty"` - F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required" json:"F_Double_required,omitempty"` - F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required" json:"F_String_required,omitempty"` - F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required" json:"F_Bytes_required,omitempty"` - F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required" json:"F_Sint32_required,omitempty"` - F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required" json:"F_Sint64_required,omitempty"` - // Repeated fields of all basic types - F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated" json:"F_Bool_repeated,omitempty"` - F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated" json:"F_Int32_repeated,omitempty"` - F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated" json:"F_Int64_repeated,omitempty"` - F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated" json:"F_Fixed32_repeated,omitempty"` - F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated" json:"F_Fixed64_repeated,omitempty"` - F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated" json:"F_Uint32_repeated,omitempty"` - F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated" json:"F_Uint64_repeated,omitempty"` - F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated" json:"F_Float_repeated,omitempty"` - F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated" json:"F_Double_repeated,omitempty"` - F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated" json:"F_String_repeated,omitempty"` - F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated" json:"F_Bytes_repeated,omitempty"` - F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated" json:"F_Sint32_repeated,omitempty"` - F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated" json:"F_Sint64_repeated,omitempty"` - // Optional fields of all basic types - F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional" json:"F_Bool_optional,omitempty"` - F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional" json:"F_Int32_optional,omitempty"` - F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional" json:"F_Int64_optional,omitempty"` - F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional" json:"F_Fixed32_optional,omitempty"` - F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional" json:"F_Fixed64_optional,omitempty"` - F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional" json:"F_Uint32_optional,omitempty"` - F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional" json:"F_Uint64_optional,omitempty"` - F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional" json:"F_Float_optional,omitempty"` - F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional" json:"F_Double_optional,omitempty"` - F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional" json:"F_String_optional,omitempty"` - F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional" json:"F_Bytes_optional,omitempty"` - F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional" json:"F_Sint32_optional,omitempty"` - F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional" json:"F_Sint64_optional,omitempty"` - // Default-valued fields of all basic types - F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,def=1" json:"F_Bool_defaulted,omitempty"` - F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,def=32" json:"F_Int32_defaulted,omitempty"` - F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,def=64" json:"F_Int64_defaulted,omitempty"` - F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` - F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` - F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` - F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` - F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,def=314159" json:"F_Float_defaulted,omitempty"` - F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,def=271828" json:"F_Double_defaulted,omitempty"` - F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` - F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` - F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` - F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` - // Packed repeated fields (no string or bytes). - F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed" json:"F_Bool_repeated_packed,omitempty"` - F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed" json:"F_Int32_repeated_packed,omitempty"` - F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed" json:"F_Int64_repeated_packed,omitempty"` - F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed" json:"F_Fixed32_repeated_packed,omitempty"` - F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed" json:"F_Fixed64_repeated_packed,omitempty"` - F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed" json:"F_Uint32_repeated_packed,omitempty"` - F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed" json:"F_Uint64_repeated_packed,omitempty"` - F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed" json:"F_Float_repeated_packed,omitempty"` - F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed" json:"F_Double_repeated_packed,omitempty"` - F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed" json:"F_Sint32_repeated_packed,omitempty"` - F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed" json:"F_Sint64_repeated_packed,omitempty"` - Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup" json:"requiredgroup,omitempty"` - Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup" json:"repeatedgroup,omitempty"` - Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest) Reset() { *m = GoTest{} } -func (m *GoTest) String() string { return proto.CompactTextString(m) } -func (*GoTest) ProtoMessage() {} - -const Default_GoTest_F_BoolDefaulted bool = true -const Default_GoTest_F_Int32Defaulted int32 = 32 -const Default_GoTest_F_Int64Defaulted int64 = 64 -const Default_GoTest_F_Fixed32Defaulted uint32 = 320 -const Default_GoTest_F_Fixed64Defaulted uint64 = 640 -const Default_GoTest_F_Uint32Defaulted uint32 = 3200 -const Default_GoTest_F_Uint64Defaulted uint64 = 6400 -const Default_GoTest_F_FloatDefaulted float32 = 314159 -const Default_GoTest_F_DoubleDefaulted float64 = 271828 -const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" - -var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") - -const Default_GoTest_F_Sint32Defaulted int32 = -32 -const Default_GoTest_F_Sint64Defaulted int64 = -64 - -func (m *GoTest) GetKind() GoTest_KIND { - if m != nil && m.Kind != nil { - return *m.Kind - } - return GoTest_VOID -} - -func (m *GoTest) GetTable() string { - if m != nil && m.Table != nil { - return *m.Table - } - return "" -} - -func (m *GoTest) GetParam() int32 { - if m != nil && m.Param != nil { - return *m.Param - } - return 0 -} - -func (m *GoTest) GetRequiredField() *GoTestField { - if m != nil { - return m.RequiredField - } - return nil -} - -func (m *GoTest) GetRepeatedField() []*GoTestField { - if m != nil { - return m.RepeatedField - } - return nil -} - -func (m *GoTest) GetOptionalField() *GoTestField { - if m != nil { - return m.OptionalField - } - return nil -} - -func (m *GoTest) GetF_BoolRequired() bool { - if m != nil && m.F_BoolRequired != nil { - return *m.F_BoolRequired - } - return false -} - -func (m *GoTest) GetF_Int32Required() int32 { - if m != nil && m.F_Int32Required != nil { - return *m.F_Int32Required - } - return 0 -} - -func (m *GoTest) GetF_Int64Required() int64 { - if m != nil && m.F_Int64Required != nil { - return *m.F_Int64Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Required() uint32 { - if m != nil && m.F_Fixed32Required != nil { - return *m.F_Fixed32Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Required() uint64 { - if m != nil && m.F_Fixed64Required != nil { - return *m.F_Fixed64Required - } - return 0 -} - -func (m *GoTest) GetF_Uint32Required() uint32 { - if m != nil && m.F_Uint32Required != nil { - return *m.F_Uint32Required - } - return 0 -} - -func (m *GoTest) GetF_Uint64Required() uint64 { - if m != nil && m.F_Uint64Required != nil { - return *m.F_Uint64Required - } - return 0 -} - -func (m *GoTest) GetF_FloatRequired() float32 { - if m != nil && m.F_FloatRequired != nil { - return *m.F_FloatRequired - } - return 0 -} - -func (m *GoTest) GetF_DoubleRequired() float64 { - if m != nil && m.F_DoubleRequired != nil { - return *m.F_DoubleRequired - } - return 0 -} - -func (m *GoTest) GetF_StringRequired() string { - if m != nil && m.F_StringRequired != nil { - return *m.F_StringRequired - } - return "" -} - -func (m *GoTest) GetF_BytesRequired() []byte { - if m != nil { - return m.F_BytesRequired - } - return nil -} - -func (m *GoTest) GetF_Sint32Required() int32 { - if m != nil && m.F_Sint32Required != nil { - return *m.F_Sint32Required - } - return 0 -} - -func (m *GoTest) GetF_Sint64Required() int64 { - if m != nil && m.F_Sint64Required != nil { - return *m.F_Sint64Required - } - return 0 -} - -func (m *GoTest) GetF_BoolRepeated() []bool { - if m != nil { - return m.F_BoolRepeated - } - return nil -} - -func (m *GoTest) GetF_Int32Repeated() []int32 { - if m != nil { - return m.F_Int32Repeated - } - return nil -} - -func (m *GoTest) GetF_Int64Repeated() []int64 { - if m != nil { - return m.F_Int64Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed32Repeated() []uint32 { - if m != nil { - return m.F_Fixed32Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed64Repeated() []uint64 { - if m != nil { - return m.F_Fixed64Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint32Repeated() []uint32 { - if m != nil { - return m.F_Uint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint64Repeated() []uint64 { - if m != nil { - return m.F_Uint64Repeated - } - return nil -} - -func (m *GoTest) GetF_FloatRepeated() []float32 { - if m != nil { - return m.F_FloatRepeated - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeated() []float64 { - if m != nil { - return m.F_DoubleRepeated - } - return nil -} - -func (m *GoTest) GetF_StringRepeated() []string { - if m != nil { - return m.F_StringRepeated - } - return nil -} - -func (m *GoTest) GetF_BytesRepeated() [][]byte { - if m != nil { - return m.F_BytesRepeated - } - return nil -} - -func (m *GoTest) GetF_Sint32Repeated() []int32 { - if m != nil { - return m.F_Sint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Sint64Repeated() []int64 { - if m != nil { - return m.F_Sint64Repeated - } - return nil -} - -func (m *GoTest) GetF_BoolOptional() bool { - if m != nil && m.F_BoolOptional != nil { - return *m.F_BoolOptional - } - return false -} - -func (m *GoTest) GetF_Int32Optional() int32 { - if m != nil && m.F_Int32Optional != nil { - return *m.F_Int32Optional - } - return 0 -} - -func (m *GoTest) GetF_Int64Optional() int64 { - if m != nil && m.F_Int64Optional != nil { - return *m.F_Int64Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Optional() uint32 { - if m != nil && m.F_Fixed32Optional != nil { - return *m.F_Fixed32Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Optional() uint64 { - if m != nil && m.F_Fixed64Optional != nil { - return *m.F_Fixed64Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint32Optional() uint32 { - if m != nil && m.F_Uint32Optional != nil { - return *m.F_Uint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint64Optional() uint64 { - if m != nil && m.F_Uint64Optional != nil { - return *m.F_Uint64Optional - } - return 0 -} - -func (m *GoTest) GetF_FloatOptional() float32 { - if m != nil && m.F_FloatOptional != nil { - return *m.F_FloatOptional - } - return 0 -} - -func (m *GoTest) GetF_DoubleOptional() float64 { - if m != nil && m.F_DoubleOptional != nil { - return *m.F_DoubleOptional - } - return 0 -} - -func (m *GoTest) GetF_StringOptional() string { - if m != nil && m.F_StringOptional != nil { - return *m.F_StringOptional - } - return "" -} - -func (m *GoTest) GetF_BytesOptional() []byte { - if m != nil { - return m.F_BytesOptional - } - return nil -} - -func (m *GoTest) GetF_Sint32Optional() int32 { - if m != nil && m.F_Sint32Optional != nil { - return *m.F_Sint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Sint64Optional() int64 { - if m != nil && m.F_Sint64Optional != nil { - return *m.F_Sint64Optional - } - return 0 -} - -func (m *GoTest) GetF_BoolDefaulted() bool { - if m != nil && m.F_BoolDefaulted != nil { - return *m.F_BoolDefaulted - } - return Default_GoTest_F_BoolDefaulted -} - -func (m *GoTest) GetF_Int32Defaulted() int32 { - if m != nil && m.F_Int32Defaulted != nil { - return *m.F_Int32Defaulted - } - return Default_GoTest_F_Int32Defaulted -} - -func (m *GoTest) GetF_Int64Defaulted() int64 { - if m != nil && m.F_Int64Defaulted != nil { - return *m.F_Int64Defaulted - } - return Default_GoTest_F_Int64Defaulted -} - -func (m *GoTest) GetF_Fixed32Defaulted() uint32 { - if m != nil && m.F_Fixed32Defaulted != nil { - return *m.F_Fixed32Defaulted - } - return Default_GoTest_F_Fixed32Defaulted -} - -func (m *GoTest) GetF_Fixed64Defaulted() uint64 { - if m != nil && m.F_Fixed64Defaulted != nil { - return *m.F_Fixed64Defaulted - } - return Default_GoTest_F_Fixed64Defaulted -} - -func (m *GoTest) GetF_Uint32Defaulted() uint32 { - if m != nil && m.F_Uint32Defaulted != nil { - return *m.F_Uint32Defaulted - } - return Default_GoTest_F_Uint32Defaulted -} - -func (m *GoTest) GetF_Uint64Defaulted() uint64 { - if m != nil && m.F_Uint64Defaulted != nil { - return *m.F_Uint64Defaulted - } - return Default_GoTest_F_Uint64Defaulted -} - -func (m *GoTest) GetF_FloatDefaulted() float32 { - if m != nil && m.F_FloatDefaulted != nil { - return *m.F_FloatDefaulted - } - return Default_GoTest_F_FloatDefaulted -} - -func (m *GoTest) GetF_DoubleDefaulted() float64 { - if m != nil && m.F_DoubleDefaulted != nil { - return *m.F_DoubleDefaulted - } - return Default_GoTest_F_DoubleDefaulted -} - -func (m *GoTest) GetF_StringDefaulted() string { - if m != nil && m.F_StringDefaulted != nil { - return *m.F_StringDefaulted - } - return Default_GoTest_F_StringDefaulted -} - -func (m *GoTest) GetF_BytesDefaulted() []byte { - if m != nil && m.F_BytesDefaulted != nil { - return m.F_BytesDefaulted - } - return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) -} - -func (m *GoTest) GetF_Sint32Defaulted() int32 { - if m != nil && m.F_Sint32Defaulted != nil { - return *m.F_Sint32Defaulted - } - return Default_GoTest_F_Sint32Defaulted -} - -func (m *GoTest) GetF_Sint64Defaulted() int64 { - if m != nil && m.F_Sint64Defaulted != nil { - return *m.F_Sint64Defaulted - } - return Default_GoTest_F_Sint64Defaulted -} - -func (m *GoTest) GetF_BoolRepeatedPacked() []bool { - if m != nil { - return m.F_BoolRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { - if m != nil { - return m.F_Int32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { - if m != nil { - return m.F_Int64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Fixed32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Fixed64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Uint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Uint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { - if m != nil { - return m.F_FloatRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { - if m != nil { - return m.F_DoubleRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { - if m != nil { - return m.F_Sint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { - if m != nil { - return m.F_Sint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { - if m != nil { - return m.Requiredgroup - } - return nil -} - -func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { - if m != nil { - return m.Repeatedgroup - } - return nil -} - -func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil -} - -// Required, repeated, and optional groups. -type GoTest_RequiredGroup struct { - RequiredField *string `protobuf:"bytes,71,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } -func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RequiredGroup) ProtoMessage() {} - -func (m *GoTest_RequiredGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_RepeatedGroup struct { - RequiredField *string `protobuf:"bytes,81,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } -func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RepeatedGroup) ProtoMessage() {} - -func (m *GoTest_RepeatedGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,91,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } -func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_OptionalGroup) ProtoMessage() {} - -func (m *GoTest_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -type GoSkipTest struct { - SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32" json:"skip_int32,omitempty"` - SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32" json:"skip_fixed32,omitempty"` - SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64" json:"skip_fixed64,omitempty"` - SkipString *string `protobuf:"bytes,14,req,name=skip_string" json:"skip_string,omitempty"` - Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup" json:"skipgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } -func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest) ProtoMessage() {} - -func (m *GoSkipTest) GetSkipInt32() int32 { - if m != nil && m.SkipInt32 != nil { - return *m.SkipInt32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed32() uint32 { - if m != nil && m.SkipFixed32 != nil { - return *m.SkipFixed32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed64() uint64 { - if m != nil && m.SkipFixed64 != nil { - return *m.SkipFixed64 - } - return 0 -} - -func (m *GoSkipTest) GetSkipString() string { - if m != nil && m.SkipString != nil { - return *m.SkipString - } - return "" -} - -func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { - if m != nil { - return m.Skipgroup - } - return nil -} - -type GoSkipTest_SkipGroup struct { - GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32" json:"group_int32,omitempty"` - GroupString *string `protobuf:"bytes,17,req,name=group_string" json:"group_string,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } -func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest_SkipGroup) ProtoMessage() {} - -func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { - if m != nil && m.GroupInt32 != nil { - return *m.GroupInt32 - } - return 0 -} - -func (m *GoSkipTest_SkipGroup) GetGroupString() string { - if m != nil && m.GroupString != nil { - return *m.GroupString - } - return "" -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -type NonPackedTest struct { - A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } -func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } -func (*NonPackedTest) ProtoMessage() {} - -func (m *NonPackedTest) GetA() []int32 { - if m != nil { - return m.A - } - return nil -} - -type PackedTest struct { - B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PackedTest) Reset() { *m = PackedTest{} } -func (m *PackedTest) String() string { return proto.CompactTextString(m) } -func (*PackedTest) ProtoMessage() {} - -func (m *PackedTest) GetB() []int32 { - if m != nil { - return m.B - } - return nil -} - -type MaxTag struct { - // Maximum possible tag number. - LastField *string `protobuf:"bytes,536870911,opt,name=last_field" json:"last_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MaxTag) Reset() { *m = MaxTag{} } -func (m *MaxTag) String() string { return proto.CompactTextString(m) } -func (*MaxTag) ProtoMessage() {} - -func (m *MaxTag) GetLastField() string { - if m != nil && m.LastField != nil { - return *m.LastField - } - return "" -} - -type OldMessage struct { - Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage) Reset() { *m = OldMessage{} } -func (m *OldMessage) String() string { return proto.CompactTextString(m) } -func (*OldMessage) ProtoMessage() {} - -func (m *OldMessage) GetNested() *OldMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *OldMessage) GetNum() int32 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type OldMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } -func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*OldMessage_Nested) ProtoMessage() {} - -func (m *OldMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -type NewMessage struct { - Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - // This is an int32 in OldMessage. - Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage) Reset() { *m = NewMessage{} } -func (m *NewMessage) String() string { return proto.CompactTextString(m) } -func (*NewMessage) ProtoMessage() {} - -func (m *NewMessage) GetNested() *NewMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *NewMessage) GetNum() int64 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type NewMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - FoodGroup *string `protobuf:"bytes,2,opt,name=food_group" json:"food_group,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } -func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*NewMessage_Nested) ProtoMessage() {} - -func (m *NewMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *NewMessage_Nested) GetFoodGroup() string { - if m != nil && m.FoodGroup != nil { - return *m.FoodGroup - } - return "" -} - -type InnerMessage struct { - Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` - Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` - Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *InnerMessage) Reset() { *m = InnerMessage{} } -func (m *InnerMessage) String() string { return proto.CompactTextString(m) } -func (*InnerMessage) ProtoMessage() {} - -const Default_InnerMessage_Port int32 = 4000 - -func (m *InnerMessage) GetHost() string { - if m != nil && m.Host != nil { - return *m.Host - } - return "" -} - -func (m *InnerMessage) GetPort() int32 { - if m != nil && m.Port != nil { - return *m.Port - } - return Default_InnerMessage_Port -} - -func (m *InnerMessage) GetConnected() bool { - if m != nil && m.Connected != nil { - return *m.Connected - } - return false -} - -type OtherMessage struct { - Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` - Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OtherMessage) Reset() { *m = OtherMessage{} } -func (m *OtherMessage) String() string { return proto.CompactTextString(m) } -func (*OtherMessage) ProtoMessage() {} - -func (m *OtherMessage) GetKey() int64 { - if m != nil && m.Key != nil { - return *m.Key - } - return 0 -} - -func (m *OtherMessage) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *OtherMessage) GetWeight() float32 { - if m != nil && m.Weight != nil { - return *m.Weight - } - return 0 -} - -func (m *OtherMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -type MyMessage struct { - Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` - Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` - Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` - Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` - Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` - Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` - RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner" json:"rep_inner,omitempty"` - Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` - Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"` - // This field becomes [][]byte in the generated code. - RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes" json:"rep_bytes,omitempty"` - Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage) Reset() { *m = MyMessage{} } -func (m *MyMessage) String() string { return proto.CompactTextString(m) } -func (*MyMessage) ProtoMessage() {} - -var extRange_MyMessage = []proto.ExtensionRange{ - {100, 536870911}, -} - -func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessage -} -func (m *MyMessage) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -func (m *MyMessage) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *MyMessage) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MyMessage) GetQuote() string { - if m != nil && m.Quote != nil { - return *m.Quote - } - return "" -} - -func (m *MyMessage) GetPet() []string { - if m != nil { - return m.Pet - } - return nil -} - -func (m *MyMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -func (m *MyMessage) GetOthers() []*OtherMessage { - if m != nil { - return m.Others - } - return nil -} - -func (m *MyMessage) GetRepInner() []*InnerMessage { - if m != nil { - return m.RepInner - } - return nil -} - -func (m *MyMessage) GetBikeshed() MyMessage_Color { - if m != nil && m.Bikeshed != nil { - return *m.Bikeshed - } - return MyMessage_RED -} - -func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { - if m != nil { - return m.Somegroup - } - return nil -} - -func (m *MyMessage) GetRepBytes() [][]byte { - if m != nil { - return m.RepBytes - } - return nil -} - -func (m *MyMessage) GetBigfloat() float64 { - if m != nil && m.Bigfloat != nil { - return *m.Bigfloat - } - return 0 -} - -type MyMessage_SomeGroup struct { - GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } -func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } -func (*MyMessage_SomeGroup) ProtoMessage() {} - -func (m *MyMessage_SomeGroup) GetGroupField() int32 { - if m != nil && m.GroupField != nil { - return *m.GroupField - } - return 0 -} - -type Ext struct { - Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Ext) Reset() { *m = Ext{} } -func (m *Ext) String() string { return proto.CompactTextString(m) } -func (*Ext) ProtoMessage() {} - -func (m *Ext) GetData() string { - if m != nil && m.Data != nil { - return *m.Data - } - return "" -} - -var E_Ext_More = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*Ext)(nil), - Field: 103, - Name: "testdata.Ext.more", - Tag: "bytes,103,opt,name=more", -} - -var E_Ext_Text = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*string)(nil), - Field: 104, - Name: "testdata.Ext.text", - Tag: "bytes,104,opt,name=text", -} - -var E_Ext_Number = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 105, - Name: "testdata.Ext.number", - Tag: "varint,105,opt,name=number", -} - -type MyMessageSet struct { - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } -func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } -func (*MyMessageSet) ProtoMessage() {} - -func (m *MyMessageSet) Marshal() ([]byte, error) { - return proto.MarshalMessageSet(m.ExtensionMap()) -} -func (m *MyMessageSet) Unmarshal(buf []byte) error { - return proto.UnmarshalMessageSet(buf, m.ExtensionMap()) -} -func (m *MyMessageSet) MarshalJSON() ([]byte, error) { - return proto.MarshalMessageSetJSON(m.XXX_extensions) -} -func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { - return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions) -} - -// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler -var _ proto.Marshaler = (*MyMessageSet)(nil) -var _ proto.Unmarshaler = (*MyMessageSet)(nil) - -var extRange_MyMessageSet = []proto.ExtensionRange{ - {100, 2147483646}, -} - -func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessageSet -} -func (m *MyMessageSet) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -type Empty struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} - -type MessageList struct { - Message []*MessageList_Message `protobuf:"group,1,rep" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList) Reset() { *m = MessageList{} } -func (m *MessageList) String() string { return proto.CompactTextString(m) } -func (*MessageList) ProtoMessage() {} - -func (m *MessageList) GetMessage() []*MessageList_Message { - if m != nil { - return m.Message - } - return nil -} - -type MessageList_Message struct { - Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` - Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } -func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } -func (*MessageList_Message) ProtoMessage() {} - -func (m *MessageList_Message) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MessageList_Message) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -type Strings struct { - StringField *string `protobuf:"bytes,1,opt,name=string_field" json:"string_field,omitempty"` - BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field" json:"bytes_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Strings) Reset() { *m = Strings{} } -func (m *Strings) String() string { return proto.CompactTextString(m) } -func (*Strings) ProtoMessage() {} - -func (m *Strings) GetStringField() string { - if m != nil && m.StringField != nil { - return *m.StringField - } - return "" -} - -func (m *Strings) GetBytesField() []byte { - if m != nil { - return m.BytesField - } - return nil -} - -type Defaults struct { - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - F_Bool *bool `protobuf:"varint,1,opt,def=1" json:"F_Bool,omitempty"` - F_Int32 *int32 `protobuf:"varint,2,opt,def=32" json:"F_Int32,omitempty"` - F_Int64 *int64 `protobuf:"varint,3,opt,def=64" json:"F_Int64,omitempty"` - F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,def=320" json:"F_Fixed32,omitempty"` - F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,def=640" json:"F_Fixed64,omitempty"` - F_Uint32 *uint32 `protobuf:"varint,6,opt,def=3200" json:"F_Uint32,omitempty"` - F_Uint64 *uint64 `protobuf:"varint,7,opt,def=6400" json:"F_Uint64,omitempty"` - F_Float *float32 `protobuf:"fixed32,8,opt,def=314159" json:"F_Float,omitempty"` - F_Double *float64 `protobuf:"fixed64,9,opt,def=271828" json:"F_Double,omitempty"` - F_String *string `protobuf:"bytes,10,opt,def=hello, \"world!\"\n" json:"F_String,omitempty"` - F_Bytes []byte `protobuf:"bytes,11,opt,def=Bignose" json:"F_Bytes,omitempty"` - F_Sint32 *int32 `protobuf:"zigzag32,12,opt,def=-32" json:"F_Sint32,omitempty"` - F_Sint64 *int64 `protobuf:"zigzag64,13,opt,def=-64" json:"F_Sint64,omitempty"` - F_Enum *Defaults_Color `protobuf:"varint,14,opt,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` - // More fields with crazy defaults. - F_Pinf *float32 `protobuf:"fixed32,15,opt,def=inf" json:"F_Pinf,omitempty"` - F_Ninf *float32 `protobuf:"fixed32,16,opt,def=-inf" json:"F_Ninf,omitempty"` - F_Nan *float32 `protobuf:"fixed32,17,opt,def=nan" json:"F_Nan,omitempty"` - // Sub-message. - Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` - // Redundant but explicit defaults. - StrZero *string `protobuf:"bytes,19,opt,name=str_zero,def=" json:"str_zero,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Defaults) Reset() { *m = Defaults{} } -func (m *Defaults) String() string { return proto.CompactTextString(m) } -func (*Defaults) ProtoMessage() {} - -const Default_Defaults_F_Bool bool = true -const Default_Defaults_F_Int32 int32 = 32 -const Default_Defaults_F_Int64 int64 = 64 -const Default_Defaults_F_Fixed32 uint32 = 320 -const Default_Defaults_F_Fixed64 uint64 = 640 -const Default_Defaults_F_Uint32 uint32 = 3200 -const Default_Defaults_F_Uint64 uint64 = 6400 -const Default_Defaults_F_Float float32 = 314159 -const Default_Defaults_F_Double float64 = 271828 -const Default_Defaults_F_String string = "hello, \"world!\"\n" - -var Default_Defaults_F_Bytes []byte = []byte("Bignose") - -const Default_Defaults_F_Sint32 int32 = -32 -const Default_Defaults_F_Sint64 int64 = -64 -const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN - -var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) -var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) -var Default_Defaults_F_Nan float32 = float32(math.NaN()) - -func (m *Defaults) GetF_Bool() bool { - if m != nil && m.F_Bool != nil { - return *m.F_Bool - } - return Default_Defaults_F_Bool -} - -func (m *Defaults) GetF_Int32() int32 { - if m != nil && m.F_Int32 != nil { - return *m.F_Int32 - } - return Default_Defaults_F_Int32 -} - -func (m *Defaults) GetF_Int64() int64 { - if m != nil && m.F_Int64 != nil { - return *m.F_Int64 - } - return Default_Defaults_F_Int64 -} - -func (m *Defaults) GetF_Fixed32() uint32 { - if m != nil && m.F_Fixed32 != nil { - return *m.F_Fixed32 - } - return Default_Defaults_F_Fixed32 -} - -func (m *Defaults) GetF_Fixed64() uint64 { - if m != nil && m.F_Fixed64 != nil { - return *m.F_Fixed64 - } - return Default_Defaults_F_Fixed64 -} - -func (m *Defaults) GetF_Uint32() uint32 { - if m != nil && m.F_Uint32 != nil { - return *m.F_Uint32 - } - return Default_Defaults_F_Uint32 -} - -func (m *Defaults) GetF_Uint64() uint64 { - if m != nil && m.F_Uint64 != nil { - return *m.F_Uint64 - } - return Default_Defaults_F_Uint64 -} - -func (m *Defaults) GetF_Float() float32 { - if m != nil && m.F_Float != nil { - return *m.F_Float - } - return Default_Defaults_F_Float -} - -func (m *Defaults) GetF_Double() float64 { - if m != nil && m.F_Double != nil { - return *m.F_Double - } - return Default_Defaults_F_Double -} - -func (m *Defaults) GetF_String() string { - if m != nil && m.F_String != nil { - return *m.F_String - } - return Default_Defaults_F_String -} - -func (m *Defaults) GetF_Bytes() []byte { - if m != nil && m.F_Bytes != nil { - return m.F_Bytes - } - return append([]byte(nil), Default_Defaults_F_Bytes...) -} - -func (m *Defaults) GetF_Sint32() int32 { - if m != nil && m.F_Sint32 != nil { - return *m.F_Sint32 - } - return Default_Defaults_F_Sint32 -} - -func (m *Defaults) GetF_Sint64() int64 { - if m != nil && m.F_Sint64 != nil { - return *m.F_Sint64 - } - return Default_Defaults_F_Sint64 -} - -func (m *Defaults) GetF_Enum() Defaults_Color { - if m != nil && m.F_Enum != nil { - return *m.F_Enum - } - return Default_Defaults_F_Enum -} - -func (m *Defaults) GetF_Pinf() float32 { - if m != nil && m.F_Pinf != nil { - return *m.F_Pinf - } - return Default_Defaults_F_Pinf -} - -func (m *Defaults) GetF_Ninf() float32 { - if m != nil && m.F_Ninf != nil { - return *m.F_Ninf - } - return Default_Defaults_F_Ninf -} - -func (m *Defaults) GetF_Nan() float32 { - if m != nil && m.F_Nan != nil { - return *m.F_Nan - } - return Default_Defaults_F_Nan -} - -func (m *Defaults) GetSub() *SubDefaults { - if m != nil { - return m.Sub - } - return nil -} - -func (m *Defaults) GetStrZero() string { - if m != nil && m.StrZero != nil { - return *m.StrZero - } - return "" -} - -type SubDefaults struct { - N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SubDefaults) Reset() { *m = SubDefaults{} } -func (m *SubDefaults) String() string { return proto.CompactTextString(m) } -func (*SubDefaults) ProtoMessage() {} - -const Default_SubDefaults_N int64 = 7 - -func (m *SubDefaults) GetN() int64 { - if m != nil && m.N != nil { - return *m.N - } - return Default_SubDefaults_N -} - -type RepeatedEnum struct { - Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } -func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } -func (*RepeatedEnum) ProtoMessage() {} - -func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { - if m != nil { - return m.Color - } - return nil -} - -type MoreRepeated struct { - Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` - BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed" json:"bools_packed,omitempty"` - Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` - IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed" json:"ints_packed,omitempty"` - Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed" json:"int64s_packed,omitempty"` - Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` - Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } -func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } -func (*MoreRepeated) ProtoMessage() {} - -func (m *MoreRepeated) GetBools() []bool { - if m != nil { - return m.Bools - } - return nil -} - -func (m *MoreRepeated) GetBoolsPacked() []bool { - if m != nil { - return m.BoolsPacked - } - return nil -} - -func (m *MoreRepeated) GetInts() []int32 { - if m != nil { - return m.Ints - } - return nil -} - -func (m *MoreRepeated) GetIntsPacked() []int32 { - if m != nil { - return m.IntsPacked - } - return nil -} - -func (m *MoreRepeated) GetInt64SPacked() []int64 { - if m != nil { - return m.Int64SPacked - } - return nil -} - -func (m *MoreRepeated) GetStrings() []string { - if m != nil { - return m.Strings - } - return nil -} - -func (m *MoreRepeated) GetFixeds() []uint32 { - if m != nil { - return m.Fixeds - } - return nil -} - -type GroupOld struct { - G *GroupOld_G `protobuf:"group,101,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld) Reset() { *m = GroupOld{} } -func (m *GroupOld) String() string { return proto.CompactTextString(m) } -func (*GroupOld) ProtoMessage() {} - -func (m *GroupOld) GetG() *GroupOld_G { - if m != nil { - return m.G - } - return nil -} - -type GroupOld_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } -func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } -func (*GroupOld_G) ProtoMessage() {} - -func (m *GroupOld_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -type GroupNew struct { - G *GroupNew_G `protobuf:"group,101,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew) Reset() { *m = GroupNew{} } -func (m *GroupNew) String() string { return proto.CompactTextString(m) } -func (*GroupNew) ProtoMessage() {} - -func (m *GroupNew) GetG() *GroupNew_G { - if m != nil { - return m.G - } - return nil -} - -type GroupNew_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } -func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } -func (*GroupNew_G) ProtoMessage() {} - -func (m *GroupNew_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -func (m *GroupNew_G) GetY() int32 { - if m != nil && m.Y != nil { - return *m.Y - } - return 0 -} - -type FloatingPoint struct { - F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } -func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } -func (*FloatingPoint) ProtoMessage() {} - -func (m *FloatingPoint) GetF() float64 { - if m != nil && m.F != nil { - return *m.F - } - return 0 -} - -type MessageWithMap struct { - NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } -func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } -func (*MessageWithMap) ProtoMessage() {} - -func (m *MessageWithMap) GetNameMapping() map[int32]string { - if m != nil { - return m.NameMapping - } - return nil -} - -func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { - if m != nil { - return m.MsgMapping - } - return nil -} - -func (m *MessageWithMap) GetByteMapping() map[bool][]byte { - if m != nil { - return m.ByteMapping - } - return nil -} - -var E_Greeting = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: ([]string)(nil), - Field: 106, - Name: "testdata.greeting", - Tag: "bytes,106,rep,name=greeting", -} - -var E_X201 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 201, - Name: "testdata.x201", - Tag: "bytes,201,opt,name=x201", -} - -var E_X202 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 202, - Name: "testdata.x202", - Tag: "bytes,202,opt,name=x202", -} - -var E_X203 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 203, - Name: "testdata.x203", - Tag: "bytes,203,opt,name=x203", -} - -var E_X204 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 204, - Name: "testdata.x204", - Tag: "bytes,204,opt,name=x204", -} - -var E_X205 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 205, - Name: "testdata.x205", - Tag: "bytes,205,opt,name=x205", -} - -var E_X206 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 206, - Name: "testdata.x206", - Tag: "bytes,206,opt,name=x206", -} - -var E_X207 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 207, - Name: "testdata.x207", - Tag: "bytes,207,opt,name=x207", -} - -var E_X208 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 208, - Name: "testdata.x208", - Tag: "bytes,208,opt,name=x208", -} - -var E_X209 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 209, - Name: "testdata.x209", - Tag: "bytes,209,opt,name=x209", -} - -var E_X210 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 210, - Name: "testdata.x210", - Tag: "bytes,210,opt,name=x210", -} - -var E_X211 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 211, - Name: "testdata.x211", - Tag: "bytes,211,opt,name=x211", -} - -var E_X212 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 212, - Name: "testdata.x212", - Tag: "bytes,212,opt,name=x212", -} - -var E_X213 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 213, - Name: "testdata.x213", - Tag: "bytes,213,opt,name=x213", -} - -var E_X214 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 214, - Name: "testdata.x214", - Tag: "bytes,214,opt,name=x214", -} - -var E_X215 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 215, - Name: "testdata.x215", - Tag: "bytes,215,opt,name=x215", -} - -var E_X216 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 216, - Name: "testdata.x216", - Tag: "bytes,216,opt,name=x216", -} - -var E_X217 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 217, - Name: "testdata.x217", - Tag: "bytes,217,opt,name=x217", -} - -var E_X218 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 218, - Name: "testdata.x218", - Tag: "bytes,218,opt,name=x218", -} - -var E_X219 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 219, - Name: "testdata.x219", - Tag: "bytes,219,opt,name=x219", -} - -var E_X220 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 220, - Name: "testdata.x220", - Tag: "bytes,220,opt,name=x220", -} - -var E_X221 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 221, - Name: "testdata.x221", - Tag: "bytes,221,opt,name=x221", -} - -var E_X222 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 222, - Name: "testdata.x222", - Tag: "bytes,222,opt,name=x222", -} - -var E_X223 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 223, - Name: "testdata.x223", - Tag: "bytes,223,opt,name=x223", -} - -var E_X224 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 224, - Name: "testdata.x224", - Tag: "bytes,224,opt,name=x224", -} - -var E_X225 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 225, - Name: "testdata.x225", - Tag: "bytes,225,opt,name=x225", -} - -var E_X226 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 226, - Name: "testdata.x226", - Tag: "bytes,226,opt,name=x226", -} - -var E_X227 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 227, - Name: "testdata.x227", - Tag: "bytes,227,opt,name=x227", -} - -var E_X228 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 228, - Name: "testdata.x228", - Tag: "bytes,228,opt,name=x228", -} - -var E_X229 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 229, - Name: "testdata.x229", - Tag: "bytes,229,opt,name=x229", -} - -var E_X230 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 230, - Name: "testdata.x230", - Tag: "bytes,230,opt,name=x230", -} - -var E_X231 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 231, - Name: "testdata.x231", - Tag: "bytes,231,opt,name=x231", -} - -var E_X232 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 232, - Name: "testdata.x232", - Tag: "bytes,232,opt,name=x232", -} - -var E_X233 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 233, - Name: "testdata.x233", - Tag: "bytes,233,opt,name=x233", -} - -var E_X234 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 234, - Name: "testdata.x234", - Tag: "bytes,234,opt,name=x234", -} - -var E_X235 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 235, - Name: "testdata.x235", - Tag: "bytes,235,opt,name=x235", -} - -var E_X236 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 236, - Name: "testdata.x236", - Tag: "bytes,236,opt,name=x236", -} - -var E_X237 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 237, - Name: "testdata.x237", - Tag: "bytes,237,opt,name=x237", -} - -var E_X238 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 238, - Name: "testdata.x238", - Tag: "bytes,238,opt,name=x238", -} - -var E_X239 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 239, - Name: "testdata.x239", - Tag: "bytes,239,opt,name=x239", -} - -var E_X240 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 240, - Name: "testdata.x240", - Tag: "bytes,240,opt,name=x240", -} - -var E_X241 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 241, - Name: "testdata.x241", - Tag: "bytes,241,opt,name=x241", -} - -var E_X242 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 242, - Name: "testdata.x242", - Tag: "bytes,242,opt,name=x242", -} - -var E_X243 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 243, - Name: "testdata.x243", - Tag: "bytes,243,opt,name=x243", -} - -var E_X244 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 244, - Name: "testdata.x244", - Tag: "bytes,244,opt,name=x244", -} - -var E_X245 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 245, - Name: "testdata.x245", - Tag: "bytes,245,opt,name=x245", -} - -var E_X246 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 246, - Name: "testdata.x246", - Tag: "bytes,246,opt,name=x246", -} - -var E_X247 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 247, - Name: "testdata.x247", - Tag: "bytes,247,opt,name=x247", -} - -var E_X248 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 248, - Name: "testdata.x248", - Tag: "bytes,248,opt,name=x248", -} - -var E_X249 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 249, - Name: "testdata.x249", - Tag: "bytes,249,opt,name=x249", -} - -var E_X250 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 250, - Name: "testdata.x250", - Tag: "bytes,250,opt,name=x250", -} - -func init() { - proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) - proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) - proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) - proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) - proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) - proto.RegisterExtension(E_Ext_More) - proto.RegisterExtension(E_Ext_Text) - proto.RegisterExtension(E_Ext_Number) - proto.RegisterExtension(E_Greeting) - proto.RegisterExtension(E_X201) - proto.RegisterExtension(E_X202) - proto.RegisterExtension(E_X203) - proto.RegisterExtension(E_X204) - proto.RegisterExtension(E_X205) - proto.RegisterExtension(E_X206) - proto.RegisterExtension(E_X207) - proto.RegisterExtension(E_X208) - proto.RegisterExtension(E_X209) - proto.RegisterExtension(E_X210) - proto.RegisterExtension(E_X211) - proto.RegisterExtension(E_X212) - proto.RegisterExtension(E_X213) - proto.RegisterExtension(E_X214) - proto.RegisterExtension(E_X215) - proto.RegisterExtension(E_X216) - proto.RegisterExtension(E_X217) - proto.RegisterExtension(E_X218) - proto.RegisterExtension(E_X219) - proto.RegisterExtension(E_X220) - proto.RegisterExtension(E_X221) - proto.RegisterExtension(E_X222) - proto.RegisterExtension(E_X223) - proto.RegisterExtension(E_X224) - proto.RegisterExtension(E_X225) - proto.RegisterExtension(E_X226) - proto.RegisterExtension(E_X227) - proto.RegisterExtension(E_X228) - proto.RegisterExtension(E_X229) - proto.RegisterExtension(E_X230) - proto.RegisterExtension(E_X231) - proto.RegisterExtension(E_X232) - proto.RegisterExtension(E_X233) - proto.RegisterExtension(E_X234) - proto.RegisterExtension(E_X235) - proto.RegisterExtension(E_X236) - proto.RegisterExtension(E_X237) - proto.RegisterExtension(E_X238) - proto.RegisterExtension(E_X239) - proto.RegisterExtension(E_X240) - proto.RegisterExtension(E_X241) - proto.RegisterExtension(E_X242) - proto.RegisterExtension(E_X243) - proto.RegisterExtension(E_X244) - proto.RegisterExtension(E_X245) - proto.RegisterExtension(E_X246) - proto.RegisterExtension(E_X247) - proto.RegisterExtension(E_X248) - proto.RegisterExtension(E_X249) - proto.RegisterExtension(E_X250) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto deleted file mode 100644 index 6cc755bae..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto +++ /dev/null @@ -1,434 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -// A feature-rich test file for the protocol compiler and libraries. - -syntax = "proto2"; - -package testdata; - -enum FOO { FOO1 = 1; }; - -message GoEnum { - required FOO foo = 1; -} - -message GoTestField { - required string Label = 1; - required string Type = 2; -} - -message GoTest { - // An enum, for completeness. - enum KIND { - VOID = 0; - - // Basic types - BOOL = 1; - BYTES = 2; - FINGERPRINT = 3; - FLOAT = 4; - INT = 5; - STRING = 6; - TIME = 7; - - // Groupings - TUPLE = 8; - ARRAY = 9; - MAP = 10; - - // Table types - TABLE = 11; - - // Functions - FUNCTION = 12; // last tag - }; - - // Some typical parameters - required KIND Kind = 1; - optional string Table = 2; - optional int32 Param = 3; - - // Required, repeated and optional foreign fields. - required GoTestField RequiredField = 4; - repeated GoTestField RepeatedField = 5; - optional GoTestField OptionalField = 6; - - // Required fields of all basic types - required bool F_Bool_required = 10; - required int32 F_Int32_required = 11; - required int64 F_Int64_required = 12; - required fixed32 F_Fixed32_required = 13; - required fixed64 F_Fixed64_required = 14; - required uint32 F_Uint32_required = 15; - required uint64 F_Uint64_required = 16; - required float F_Float_required = 17; - required double F_Double_required = 18; - required string F_String_required = 19; - required bytes F_Bytes_required = 101; - required sint32 F_Sint32_required = 102; - required sint64 F_Sint64_required = 103; - - // Repeated fields of all basic types - repeated bool F_Bool_repeated = 20; - repeated int32 F_Int32_repeated = 21; - repeated int64 F_Int64_repeated = 22; - repeated fixed32 F_Fixed32_repeated = 23; - repeated fixed64 F_Fixed64_repeated = 24; - repeated uint32 F_Uint32_repeated = 25; - repeated uint64 F_Uint64_repeated = 26; - repeated float F_Float_repeated = 27; - repeated double F_Double_repeated = 28; - repeated string F_String_repeated = 29; - repeated bytes F_Bytes_repeated = 201; - repeated sint32 F_Sint32_repeated = 202; - repeated sint64 F_Sint64_repeated = 203; - - // Optional fields of all basic types - optional bool F_Bool_optional = 30; - optional int32 F_Int32_optional = 31; - optional int64 F_Int64_optional = 32; - optional fixed32 F_Fixed32_optional = 33; - optional fixed64 F_Fixed64_optional = 34; - optional uint32 F_Uint32_optional = 35; - optional uint64 F_Uint64_optional = 36; - optional float F_Float_optional = 37; - optional double F_Double_optional = 38; - optional string F_String_optional = 39; - optional bytes F_Bytes_optional = 301; - optional sint32 F_Sint32_optional = 302; - optional sint64 F_Sint64_optional = 303; - - // Default-valued fields of all basic types - optional bool F_Bool_defaulted = 40 [default=true]; - optional int32 F_Int32_defaulted = 41 [default=32]; - optional int64 F_Int64_defaulted = 42 [default=64]; - optional fixed32 F_Fixed32_defaulted = 43 [default=320]; - optional fixed64 F_Fixed64_defaulted = 44 [default=640]; - optional uint32 F_Uint32_defaulted = 45 [default=3200]; - optional uint64 F_Uint64_defaulted = 46 [default=6400]; - optional float F_Float_defaulted = 47 [default=314159.]; - optional double F_Double_defaulted = 48 [default=271828.]; - optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; - optional sint32 F_Sint32_defaulted = 402 [default = -32]; - optional sint64 F_Sint64_defaulted = 403 [default = -64]; - - // Packed repeated fields (no string or bytes). - repeated bool F_Bool_repeated_packed = 50 [packed=true]; - repeated int32 F_Int32_repeated_packed = 51 [packed=true]; - repeated int64 F_Int64_repeated_packed = 52 [packed=true]; - repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; - repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; - repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; - repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; - repeated float F_Float_repeated_packed = 57 [packed=true]; - repeated double F_Double_repeated_packed = 58 [packed=true]; - repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; - repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; - - // Required, repeated, and optional groups. - required group RequiredGroup = 70 { - required string RequiredField = 71; - }; - - repeated group RepeatedGroup = 80 { - required string RequiredField = 81; - }; - - optional group OptionalGroup = 90 { - required string RequiredField = 91; - }; -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -message GoSkipTest { - required int32 skip_int32 = 11; - required fixed32 skip_fixed32 = 12; - required fixed64 skip_fixed64 = 13; - required string skip_string = 14; - required group SkipGroup = 15 { - required int32 group_int32 = 16; - required string group_string = 17; - } -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -message NonPackedTest { - repeated int32 a = 1; -} - -message PackedTest { - repeated int32 b = 1 [packed=true]; -} - -message MaxTag { - // Maximum possible tag number. - optional string last_field = 536870911; -} - -message OldMessage { - message Nested { - optional string name = 1; - } - optional Nested nested = 1; - - optional int32 num = 2; -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -message NewMessage { - message Nested { - optional string name = 1; - optional string food_group = 2; - } - optional Nested nested = 1; - - // This is an int32 in OldMessage. - optional int64 num = 2; -} - -// Smaller tests for ASCII formatting. - -message InnerMessage { - required string host = 1; - optional int32 port = 2 [default=4000]; - optional bool connected = 3; -} - -message OtherMessage { - optional int64 key = 1; - optional bytes value = 2; - optional float weight = 3; - optional InnerMessage inner = 4; -} - -message MyMessage { - required int32 count = 1; - optional string name = 2; - optional string quote = 3; - repeated string pet = 4; - optional InnerMessage inner = 5; - repeated OtherMessage others = 6; - repeated InnerMessage rep_inner = 12; - - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - }; - optional Color bikeshed = 7; - - optional group SomeGroup = 8 { - optional int32 group_field = 9; - } - - // This field becomes [][]byte in the generated code. - repeated bytes rep_bytes = 10; - - optional double bigfloat = 11; - - extensions 100 to max; -} - -message Ext { - extend MyMessage { - optional Ext more = 103; - optional string text = 104; - optional int32 number = 105; - } - - optional string data = 1; -} - -extend MyMessage { - repeated string greeting = 106; -} - -message MyMessageSet { - option message_set_wire_format = true; - extensions 100 to max; -} - -message Empty { -} - -extend MyMessageSet { - optional Empty x201 = 201; - optional Empty x202 = 202; - optional Empty x203 = 203; - optional Empty x204 = 204; - optional Empty x205 = 205; - optional Empty x206 = 206; - optional Empty x207 = 207; - optional Empty x208 = 208; - optional Empty x209 = 209; - optional Empty x210 = 210; - optional Empty x211 = 211; - optional Empty x212 = 212; - optional Empty x213 = 213; - optional Empty x214 = 214; - optional Empty x215 = 215; - optional Empty x216 = 216; - optional Empty x217 = 217; - optional Empty x218 = 218; - optional Empty x219 = 219; - optional Empty x220 = 220; - optional Empty x221 = 221; - optional Empty x222 = 222; - optional Empty x223 = 223; - optional Empty x224 = 224; - optional Empty x225 = 225; - optional Empty x226 = 226; - optional Empty x227 = 227; - optional Empty x228 = 228; - optional Empty x229 = 229; - optional Empty x230 = 230; - optional Empty x231 = 231; - optional Empty x232 = 232; - optional Empty x233 = 233; - optional Empty x234 = 234; - optional Empty x235 = 235; - optional Empty x236 = 236; - optional Empty x237 = 237; - optional Empty x238 = 238; - optional Empty x239 = 239; - optional Empty x240 = 240; - optional Empty x241 = 241; - optional Empty x242 = 242; - optional Empty x243 = 243; - optional Empty x244 = 244; - optional Empty x245 = 245; - optional Empty x246 = 246; - optional Empty x247 = 247; - optional Empty x248 = 248; - optional Empty x249 = 249; - optional Empty x250 = 250; -} - -message MessageList { - repeated group Message = 1 { - required string name = 2; - required int32 count = 3; - } -} - -message Strings { - optional string string_field = 1; - optional bytes bytes_field = 2; -} - -message Defaults { - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - } - - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - optional bool F_Bool = 1 [default=true]; - optional int32 F_Int32 = 2 [default=32]; - optional int64 F_Int64 = 3 [default=64]; - optional fixed32 F_Fixed32 = 4 [default=320]; - optional fixed64 F_Fixed64 = 5 [default=640]; - optional uint32 F_Uint32 = 6 [default=3200]; - optional uint64 F_Uint64 = 7 [default=6400]; - optional float F_Float = 8 [default=314159.]; - optional double F_Double = 9 [default=271828.]; - optional string F_String = 10 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes = 11 [default="Bignose"]; - optional sint32 F_Sint32 = 12 [default=-32]; - optional sint64 F_Sint64 = 13 [default=-64]; - optional Color F_Enum = 14 [default=GREEN]; - - // More fields with crazy defaults. - optional float F_Pinf = 15 [default=inf]; - optional float F_Ninf = 16 [default=-inf]; - optional float F_Nan = 17 [default=nan]; - - // Sub-message. - optional SubDefaults sub = 18; - - // Redundant but explicit defaults. - optional string str_zero = 19 [default=""]; -} - -message SubDefaults { - optional int64 n = 1 [default=7]; -} - -message RepeatedEnum { - enum Color { - RED = 1; - } - repeated Color color = 1; -} - -message MoreRepeated { - repeated bool bools = 1; - repeated bool bools_packed = 2 [packed=true]; - repeated int32 ints = 3; - repeated int32 ints_packed = 4 [packed=true]; - repeated int64 int64s_packed = 7 [packed=true]; - repeated string strings = 5; - repeated fixed32 fixeds = 6; -} - -// GroupOld and GroupNew have the same wire format. -// GroupNew has a new field inside a group. - -message GroupOld { - optional group G = 101 { - optional int32 x = 2; - } -} - -message GroupNew { - optional group G = 101 { - optional int32 x = 2; - optional int32 y = 3; - } -} - -message FloatingPoint { - required double f = 1; -} - -message MessageWithMap { - map name_mapping = 1; - map msg_mapping = 2; - map byte_mapping = 3; -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go index 720eac470..2336b144c 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go @@ -37,11 +37,11 @@ import ( "bufio" "bytes" "encoding" + "errors" "fmt" "io" "log" "math" - "os" "reflect" "sort" "strings" @@ -170,20 +170,12 @@ func writeName(w *textWriter, props *Properties) error { return nil } -var ( - messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem() -) - // raw is the interface satisfied by RawMessage. type raw interface { Bytes() []byte } func writeStruct(w *textWriter, sv reflect.Value) error { - if sv.Type() == messageSetType { - return writeMessageSet(w, sv.Addr().Interface().(*MessageSet)) - } - st := sv.Type() sprops := GetProperties(st) for i := 0; i < sv.NumField(); i++ { @@ -246,7 +238,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error { } if fv.Kind() == reflect.Map { // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() // TODO: should we sort these for deterministic output? + keys := fv.MapKeys() sort.Sort(mapKeys(keys)) for _, key := range keys { val := fv.MapIndex(key) @@ -283,20 +275,23 @@ func writeStruct(w *textWriter, sv reflect.Value) error { if err := w.WriteByte('\n'); err != nil { return err } - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { + // nil values aren't legal, but we can avoid panicking because of them. + if val.Kind() != reflect.Ptr || !val.IsNil() { + // value + if _, err := w.WriteString("value:"); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := writeAny(w, val, props.mvalprop); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { return err } - } - if err := writeAny(w, val, props.mvalprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err } // close struct w.unindent() @@ -315,26 +310,34 @@ func writeStruct(w *textWriter, sv reflect.Value) error { } if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { // proto3 non-repeated scalar field; skip if zero value - switch fv.Kind() { - case reflect.Bool: - if !fv.Bool() { + if isProto3Zero(fv) { + continue + } + } + + if fv.Kind() == reflect.Interface { + // Check if it is a oneof. + if st.Field(i).Tag.Get("protobuf_oneof") != "" { + // fv is nil, or holds a pointer to generated struct. + // That generated struct has exactly one field, + // which has a protobuf struct tag. + if fv.IsNil() { continue } - case reflect.Int32, reflect.Int64: - if fv.Int() == 0 { - continue - } - case reflect.Uint32, reflect.Uint64: - if fv.Uint() == 0 { - continue - } - case reflect.Float32, reflect.Float64: - if fv.Float() == 0 { - continue - } - case reflect.String: - if fv.String() == "" { - continue + inner := fv.Elem().Elem() // interface -> *T -> T + tag := inner.Type().Field(0).Tag.Get("protobuf") + props = new(Properties) // Overwrite the outer props var, but not its pointee. + props.Parse(tag) + // Write the value in the oneof, not the oneof itself. + fv = inner.Field(0) + + // Special case to cope with malformed messages gracefully: + // If the value in the oneof is a nil pointer, don't panic + // in writeAny. + if fv.Kind() == reflect.Ptr && fv.IsNil() { + // Use errors.New so writeAny won't render quotes. + msg := errors.New("/* nil */") + fv = reflect.ValueOf(&msg).Elem() } } } @@ -514,44 +517,6 @@ func writeString(w *textWriter, s string) error { return w.WriteByte('"') } -func writeMessageSet(w *textWriter, ms *MessageSet) error { - for _, item := range ms.Item { - id := *item.TypeId - if msd, ok := messageSetMap[id]; ok { - // Known message set type. - if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil { - return err - } - w.indent() - - pb := reflect.New(msd.t.Elem()) - if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil { - if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil { - return err - } - } else { - if err := writeStruct(w, pb.Elem()); err != nil { - return err - } - } - } else { - // Unknown type. - if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil { - return err - } - w.indent() - if err := writeUnknownStruct(w, item.Message); err != nil { - return err - } - } - w.unindent() - if _, err := w.Write(gtNewline); err != nil { - return err - } - } - return nil -} - func writeUnknownStruct(w *textWriter, data []byte) (err error) { if !w.compact { if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { @@ -666,10 +631,7 @@ func writeExtensions(w *textWriter, pv reflect.Value) error { pb, err := GetExtension(ep, desc) if err != nil { - if _, err := fmt.Fprintln(os.Stderr, "proto: failed getting extension: ", err); err != nil { - return err - } - continue + return fmt.Errorf("failed getting extension: %v", err) } // Repeated extensions will appear as a slice. diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go index ddd9579cd..451323262 100644 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go +++ b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go @@ -119,6 +119,14 @@ func isWhitespace(c byte) bool { return false } +func isQuote(c byte) bool { + switch c { + case '"', '\'': + return true + } + return false +} + func (p *textParser) skipWhitespace() { i := 0 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { @@ -174,7 +182,7 @@ func (p *textParser) advance() { } unq, err := unquoteC(p.s[1:i], rune(p.s[0])) if err != nil { - p.errorf("invalid quoted string %v", p.s[0:i+1]) + p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) return } p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] @@ -333,13 +341,13 @@ func (p *textParser) next() *token { p.advance() if p.done { p.cur.value = "" - } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' { + } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { // Look for multiple quoted strings separated by whitespace, // and concatenate them. cat := p.cur for { p.skipWhitespace() - if p.done || p.s[0] != '"' { + if p.done || !isQuote(p.s[0]) { break } p.advance() @@ -385,8 +393,7 @@ func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSet } // Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) { - sprops := GetProperties(st) +func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { i, ok := sprops.decoderOrigNames[name] if ok { return i, sprops.Prop[i], true @@ -438,7 +445,8 @@ func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseEr func (p *textParser) readStruct(sv reflect.Value, terminator string) error { st := sv.Type() - reqCount := GetProperties(st).reqCount + sprops := GetProperties(st) + reqCount := sprops.reqCount var reqFieldErr error fieldSet := make(map[string]bool) // A struct is a sequence of "name: value", terminated by one of @@ -520,99 +528,113 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { sl = reflect.Append(sl, ext) SetExtension(ep, desc, sl.Interface()) } - } else { - // This is a normal, non-extension field. - name := tok.value - fi, props, ok := structFieldByName(st, name) - if !ok { - return p.errorf("unknown field name %q in %v", name, st) + if err := p.consumeOptionalSeparator(); err != nil { + return err } + continue + } - dst := sv.Field(fi) + // This is a normal, non-extension field. + name := tok.value + var dst reflect.Value + fi, props, ok := structFieldByName(sprops, name) + if ok { + dst = sv.Field(fi) + } else if oop, ok := sprops.OneofTypes[name]; ok { + // It is a oneof. + props = oop.Prop + nv := reflect.New(oop.Type.Elem()) + dst = nv.Elem().Field(0) + sv.Field(oop.Field).Set(nv) + } + if !dst.IsValid() { + return p.errorf("unknown field name %q in %v", name, st) + } - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // Technically the "key" and "value" could come in any order, - // but in practice they won't. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - if err := p.consumeToken("key"); err != nil { - return err - } - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.mkeyprop); err != nil { - return err - } - if err := p.consumeToken("value"); err != nil { - return err - } - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(val, props.mvalprop); err != nil { - return err - } - if err := p.consumeToken(terminator); err != nil { - return err - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, st.Field(fi).Type); err != nil { + if dst.Kind() == reflect.Map { + // Consume any colon. + if err := p.checkForColon(props, dst.Type()); err != nil { return err } - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } else if props.Required { - reqCount-- + // Construct the map if it doesn't already exist. + if dst.IsNil() { + dst.Set(reflect.MakeMap(dst.Type())) } + key := reflect.New(dst.Type().Key()).Elem() + val := reflect.New(dst.Type().Elem()).Elem() + + // The map entry should be this sequence of tokens: + // < key : KEY value : VALUE > + // Technically the "key" and "value" could come in any order, + // but in practice they won't. + + tok := p.next() + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + if err := p.consumeToken("key"); err != nil { + return err + } + if err := p.consumeToken(":"); err != nil { + return err + } + if err := p.readAny(key, props.mkeyprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + if err := p.consumeToken("value"); err != nil { + return err + } + if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { + return err + } + if err := p.readAny(val, props.mvalprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + if err := p.consumeToken(terminator); err != nil { + return err + } + + dst.SetMapIndex(key, val) + continue } - // For backward compatibility, permit a semicolon or comma after a field. - tok = p.next() - if tok.err != nil { - return tok.err + // Check that it's not already set if it's not a repeated field. + if !props.Repeated && fieldSet[name] { + return p.errorf("non-repeated field %q was repeated", name) } - if tok.value != ";" && tok.value != "," { - p.back() + + if err := p.checkForColon(props, dst.Type()); err != nil { + return err } + + // Parse into the field. + fieldSet[name] = true + if err := p.readAny(dst, props); err != nil { + if _, ok := err.(*RequiredNotSetError); !ok { + return err + } + reqFieldErr = err + } else if props.Required { + reqCount-- + } + + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + } if reqCount > 0 { @@ -621,6 +643,19 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { return reqFieldErr } +// consumeOptionalSeparator consumes an optional semicolon or comma. +// It is used in readStruct to provide backward compatibility. +func (p *textParser) consumeOptionalSeparator() error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ";" && tok.value != "," { + p.back() + } + return nil +} + func (p *textParser) readAny(v reflect.Value, props *Properties) error { tok := p.next() if tok.err != nil { @@ -645,18 +680,32 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { fv.Set(reflect.ValueOf(bytes)) return nil } - // Repeated field. May already exist. - flen := fv.Len() - if flen == fv.Cap() { - nav := reflect.MakeSlice(at, flen, 2*flen+1) - reflect.Copy(nav, fv) - fv.Set(nav) + // Repeated field. + if tok.value == "[" { + // Repeated field with list notation, like [1,2,3]. + for { + fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) + err := p.readAny(fv.Index(fv.Len()-1), props) + if err != nil { + return err + } + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == "]" { + break + } + if tok.value != "," { + return p.errorf("Expected ']' or ',' found %q", tok.value) + } + } + return nil } - fv.SetLen(flen + 1) - - // Read one. + // One value of the repeated field. p.back() - return p.readAny(fv.Index(flen), props) + fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) + return p.readAny(fv.Index(fv.Len()-1), props) case reflect.Bool: // Either "true", "false", 1 or 0. switch tok.value { diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100644 index e5ee8b922..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,509 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - proto3pb "./proto3_proto" - . "./testdata" - . "github.com/golang/protobuf/proto" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0"`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:>` + - `byte_mapping:` - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go deleted file mode 100644 index 707bedd00..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,436 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/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. -// * 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. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "./proto3_proto" - pb "./testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; current map format is the same as a repeated struct - { - &pb.MessageWithMap{NameMapping: map[int32]string{1234: "Feist"}}, - `name_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/LICENSE b/Godeps/_workspace/src/github.com/google/cadvisor/LICENSE new file mode 100644 index 000000000..97cec18e8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/google/cadvisor/LICENSE @@ -0,0 +1,190 @@ + Copyright 2014 The cAdvisor 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. + + 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 diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container.go b/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container.go index bb4fc322e..6e7e65897 100644 --- a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container.go +++ b/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container.go @@ -23,6 +23,8 @@ type CpuSpec struct { Limit uint64 `json:"limit"` MaxLimit uint64 `json:"max_limit"` Mask string `json:"mask,omitempty"` + Quota uint64 `json:"quota,omitempty"` + Period uint64 `json:"period,omitempty"` } type MemorySpec struct { @@ -397,6 +399,9 @@ type FsStats struct { // The block device name associated with the filesystem. Device string `json:"device,omitempty"` + // Type of the filesytem. + Type string `json:"type"` + // Number of bytes that can be consumed by the container on this filesystem. Limit uint64 `json:"capacity"` @@ -410,6 +415,9 @@ type FsStats struct { // Number of bytes available for non-root user. Available uint64 `json:"available"` + // Number of available Inodes + InodesFree uint64 `json:"inodes_free"` + // Number of reads completed // This is the total number of reads completed successfully. ReadsCompleted uint64 `json:"reads_completed"` diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container_test.go deleted file mode 100644 index 58dc79e39..000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container_test.go +++ /dev/null @@ -1,79 +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. - -package v1 - -import ( - "testing" - "time" -) - -func TestStatsStartTime(t *testing.T) { - N := 10 - stats := make([]*ContainerStats, 0, N) - ct := time.Now() - for i := 0; i < N; i++ { - s := &ContainerStats{ - Timestamp: ct.Add(time.Duration(i) * time.Second), - } - stats = append(stats, s) - } - cinfo := &ContainerInfo{ - ContainerReference: ContainerReference{ - Name: "/some/container", - }, - Stats: stats, - } - ref := ct.Add(time.Duration(N-1) * time.Second) - end := cinfo.StatsEndTime() - - if !ref.Equal(end) { - t.Errorf("end time is %v; should be %v", end, ref) - } -} - -func TestStatsEndTime(t *testing.T) { - N := 10 - stats := make([]*ContainerStats, 0, N) - ct := time.Now() - for i := 0; i < N; i++ { - s := &ContainerStats{ - Timestamp: ct.Add(time.Duration(i) * time.Second), - } - stats = append(stats, s) - } - cinfo := &ContainerInfo{ - ContainerReference: ContainerReference{ - Name: "/some/container", - }, - Stats: stats, - } - ref := ct - start := cinfo.StatsStartTime() - - if !ref.Equal(start) { - t.Errorf("start time is %v; should be %v", start, ref) - } -} - -func createStats(cpuUsage, memUsage uint64, timestamp time.Time) *ContainerStats { - stats := &ContainerStats{} - stats.Cpu.Usage.PerCpu = []uint64{cpuUsage} - stats.Cpu.Usage.Total = cpuUsage - stats.Cpu.Usage.System = 0 - stats.Cpu.Usage.User = cpuUsage - stats.Memory.Usage = memUsage - stats.Timestamp = timestamp - return stats -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/machine.go b/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/machine.go index f26291c11..74a5df49c 100644 --- a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/machine.go +++ b/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/machine.go @@ -20,6 +20,12 @@ type FsInfo struct { // Total number of bytes available on the filesystem. Capacity uint64 `json:"capacity"` + + // Type of device. + Type string `json:"type"` + + // Total number of inodes available on the filesystem. + Inodes uint64 `json:"inodes"` } type Node struct { @@ -115,10 +121,11 @@ type NetInfo struct { type CloudProvider string const ( - GCE CloudProvider = "GCE" - AWS = "AWS" - Baremetal = "Baremetal" - UnkownProvider = "Unknown" + GCE CloudProvider = "GCE" + AWS = "AWS" + Azure = "Azure" + Baremetal = "Baremetal" + UnknownProvider = "Unknown" ) type InstanceType string @@ -128,6 +135,12 @@ const ( UnknownInstance = "Unknown" ) +type InstanceID string + +const ( + UnNamedInstance InstanceID = "None" +) + type MachineInfo struct { // The number of cores in this machine. NumCores int `json:"num_cores"` @@ -165,6 +178,9 @@ type MachineInfo struct { // Type of cloud instance (e.g. GCE standard) the machine is. InstanceType InstanceType `json:"instance_type"` + + // ID of cloud instance (e.g. instance-1) given to it by the cloud provider. + InstanceID InstanceID `json:"instance_id"` } type VersionInfo struct { diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/test/datagen.go b/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/test/datagen.go deleted file mode 100644 index 42a0526d4..000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/test/datagen.go +++ /dev/null @@ -1,81 +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. - -package test - -import ( - "fmt" - "math/rand" - "time" - - info "github.com/google/cadvisor/info/v1" -) - -func GenerateRandomStats(numStats, numCores int, duration time.Duration) []*info.ContainerStats { - ret := make([]*info.ContainerStats, numStats) - perCoreUsages := make([]uint64, numCores) - currentTime := time.Now() - for i := range perCoreUsages { - perCoreUsages[i] = uint64(rand.Int63n(1000)) - } - for i := 0; i < numStats; i++ { - stats := new(info.ContainerStats) - stats.Timestamp = currentTime - currentTime = currentTime.Add(duration) - - percore := make([]uint64, numCores) - for i := range perCoreUsages { - perCoreUsages[i] += uint64(rand.Int63n(1000)) - percore[i] = perCoreUsages[i] - stats.Cpu.Usage.Total += percore[i] - } - stats.Cpu.Usage.PerCpu = percore - stats.Cpu.Usage.User = stats.Cpu.Usage.Total - stats.Cpu.Usage.System = 0 - stats.Memory.Usage = uint64(rand.Int63n(4096)) - stats.Memory.Cache = uint64(rand.Int63n(4096)) - stats.Memory.RSS = uint64(rand.Int63n(4096)) - ret[i] = stats - } - return ret -} - -func GenerateRandomContainerSpec(numCores int) info.ContainerSpec { - ret := info.ContainerSpec{ - CreationTime: time.Now(), - HasCpu: true, - Cpu: info.CpuSpec{}, - HasMemory: true, - Memory: info.MemorySpec{}, - } - ret.Cpu.Limit = uint64(1000 + rand.Int63n(2000)) - ret.Cpu.MaxLimit = uint64(1000 + rand.Int63n(2000)) - ret.Cpu.Mask = fmt.Sprintf("0-%d", numCores-1) - ret.Memory.Limit = uint64(4096 + rand.Int63n(4096)) - return ret -} - -func GenerateRandomContainerInfo(containerName string, numCores int, query *info.ContainerInfoRequest, duration time.Duration) *info.ContainerInfo { - stats := GenerateRandomStats(query.NumStats, numCores, duration) - spec := GenerateRandomContainerSpec(numCores) - - ret := &info.ContainerInfo{ - ContainerReference: info.ContainerReference{ - Name: containerName, - }, - Spec: spec, - Stats: stats, - } - return ret -} diff --git a/Godeps/_workspace/src/github.com/google/gofuzz/example_test.go b/Godeps/_workspace/src/github.com/google/gofuzz/example_test.go deleted file mode 100644 index 792707a3a..000000000 --- a/Godeps/_workspace/src/github.com/google/gofuzz/example_test.go +++ /dev/null @@ -1,225 +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. -*/ - -package fuzz_test - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/google/gofuzz" -) - -func ExampleSimple() { - type MyType struct { - A string - B string - C int - D struct { - E float64 - } - } - - f := fuzz.New() - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 1000; i++ { - f.Fuzz(&object) - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 1000 unique objects. -} - -func ExampleCustom() { - type MyType struct { - A int - B string - } - - counter := 0 - f := fuzz.New().Funcs( - func(i *int, c fuzz.Continue) { - *i = counter - counter++ - }, - ) - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 100; i++ { - f.Fuzz(&object) - if object.A != i { - fmt.Printf("Unexpected value: %#v\n", object) - } - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 100 unique objects. -} - -func ExampleComplex() { - type OtherType struct { - A string - B string - } - type MyType struct { - Pointer *OtherType - Map map[string]OtherType - PointerMap *map[string]OtherType - Slice []OtherType - SlicePointer []*OtherType - PointerSlicePointer *[]*OtherType - } - - f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs( - func(o *OtherType, c fuzz.Continue) { - o.A = "Foo" - o.B = "Bar" - }, - func(op **OtherType, c fuzz.Continue) { - *op = &OtherType{"A", "B"} - }, - func(m map[string]OtherType, c fuzz.Continue) { - m["Works Because"] = OtherType{ - "Fuzzer", - "Preallocated", - } - }, - ) - object := MyType{} - f.Fuzz(&object) - bytes, err := json.MarshalIndent(&object, "", " ") - if err != nil { - fmt.Printf("error: %v\n", err) - } - fmt.Printf("%s\n", string(bytes)) - // Output: - // { - // "Pointer": { - // "A": "A", - // "B": "B" - // }, - // "Map": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "PointerMap": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "Slice": [ - // { - // "A": "Foo", - // "B": "Bar" - // } - // ], - // "SlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ], - // "PointerSlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ] - // } -} - -func ExampleMap() { - f := fuzz.New().NilChance(0).NumElements(1, 1) - var myMap map[struct{ A, B, C int }]string - f.Fuzz(&myMap) - fmt.Printf("myMap has %v element(s).\n", len(myMap)) - // Output: - // myMap has 1 element(s). -} - -func ExampleSingle() { - f := fuzz.New() - var i int - f.Fuzz(&i) - - // Technically, we'd expect this to fail one out of 2 billion attempts... - fmt.Printf("(i == 0) == %v", i == 0) - // Output: - // (i == 0) == false -} - -func ExampleEnum() { - type MyEnum string - const ( - A MyEnum = "A" - B MyEnum = "B" - ) - type MyInfo struct { - Type MyEnum - AInfo *string - BInfo *string - } - - f := fuzz.New().NilChance(0).Funcs( - func(e *MyInfo, c fuzz.Continue) { - // Note c's embedded Rand allows for direct use. - // We could also use c.RandBool() here. - switch c.Intn(2) { - case 0: - e.Type = A - c.Fuzz(&e.AInfo) - case 1: - e.Type = B - c.Fuzz(&e.BInfo) - } - }, - ) - - for i := 0; i < 100; i++ { - var myObject MyInfo - f.Fuzz(&myObject) - switch myObject.Type { - case A: - if myObject.AInfo == nil { - fmt.Println("AInfo should have been set!") - } - if myObject.BInfo != nil { - fmt.Println("BInfo should NOT have been set!") - } - case B: - if myObject.BInfo == nil { - fmt.Println("BInfo should have been set!") - } - if myObject.AInfo != nil { - fmt.Println("AInfo should NOT have been set!") - } - default: - fmt.Println("Invalid enum value!") - } - } - // Output: -} diff --git a/Godeps/_workspace/src/github.com/google/gofuzz/fuzz_test.go b/Godeps/_workspace/src/github.com/google/gofuzz/fuzz_test.go deleted file mode 100644 index 12abc8f65..000000000 --- a/Godeps/_workspace/src/github.com/google/gofuzz/fuzz_test.go +++ /dev/null @@ -1,384 +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. -*/ - -package fuzz - -import ( - "reflect" - "testing" - "time" -) - -func TestFuzz_basic(t *testing.T) { - obj := &struct { - I int - I8 int8 - I16 int16 - I32 int32 - I64 int64 - U uint - U8 uint8 - U16 uint16 - U32 uint32 - U64 uint64 - Uptr uintptr - S string - B bool - T time.Time - }{} - - failed := map[string]int{} - for i := 0; i < 10; i++ { - New().Fuzz(obj) - - if n, v := "i", obj.I; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i8", obj.I8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i16", obj.I16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i32", obj.I32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i64", obj.I64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u", obj.U; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u8", obj.U8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u16", obj.U16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u32", obj.U32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u64", obj.U64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "uptr", obj.Uptr; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "s", obj.S; v == "" { - failed[n] = failed[n] + 1 - } - if n, v := "b", obj.B; v == false { - failed[n] = failed[n] + 1 - } - if n, v := "t", obj.T; v.IsZero() { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -func checkFailed(t *testing.T, failed map[string]int) { - for k, v := range failed { - if v > 8 { - t.Errorf("%v seems to not be getting set, was zero value %v times", k, v) - } - } -} - -func TestFuzz_structptr(t *testing.T) { - obj := &struct { - A *struct { - S string - } - }{} - - f := New().NilChance(.5) - failed := map[string]int{} - for i := 0; i < 10; i++ { - f.Fuzz(obj) - - if n, v := "a not nil", obj.A; v == nil { - failed[n] = failed[n] + 1 - } - if n, v := "a nil", obj.A; v != nil { - failed[n] = failed[n] + 1 - } - if n, v := "as", obj.A; v == nil || v.S == "" { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -// tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest -// stage it ever got to. -func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) { - maxStage := 0 - for i := 0; i < 20; i++ { - f.Fuzz(obj) - stage, passed := check() - if stage > maxStage { - maxStage = stage - } - if passed { - return - } - } - t.Errorf("Only ever got to stage %v", maxStage) -} - -func TestFuzz_structmap(t *testing.T) { - obj := &struct { - A map[struct { - S string - }]struct { - S2 string - } - B map[string]string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for k, v := range obj.A { - if k.S == "" { - return 3, false - } - if v.S2 == "" { - return 4, false - } - } - - if obj.B == nil { - return 5, false - } - if len(obj.B) == 0 { - return 6, false - } - for k, v := range obj.B { - if k == "" { - return 7, false - } - if v == "" { - return 8, false - } - } - return 9, true - }) -} - -func TestFuzz_structslice(t *testing.T) { - obj := &struct { - A []struct { - S string - } - B []string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for _, v := range obj.A { - if v.S == "" { - return 3, false - } - } - - if obj.B == nil { - return 4, false - } - if len(obj.B) == 0 { - return 5, false - } - for _, v := range obj.B { - if v == "" { - return 6, false - } - } - return 7, true - }) -} - -func TestFuzz_custom(t *testing.T) { - obj := &struct { - A string - B *string - C map[string]string - D *map[string]string - }{} - - testPhrase := "gotcalled" - testMap := map[string]string{"C": "D"} - f := New().Funcs( - func(s *string, c Continue) { - *s = testPhrase - }, - func(m map[string]string, c Continue) { - m["C"] = "D" - }, - ) - - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A != testPhrase { - return 1, false - } - if obj.B == nil { - return 2, false - } - if *obj.B != testPhrase { - return 3, false - } - if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) { - return 4, false - } - if obj.D == nil { - return 5, false - } - if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) { - return 6, false - } - return 7, true - }) -} - -type SelfFuzzer string - -// Implement fuzz.Interface. -func (sf *SelfFuzzer) Fuzz(c Continue) { - *sf = selfFuzzerTestPhrase -} - -const selfFuzzerTestPhrase = "was fuzzed" - -func TestFuzz_interface(t *testing.T) { - f := New() - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != selfFuzzerTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != selfFuzzerTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_interfaceAndFunc(t *testing.T) { - const privateTestPhrase = "private phrase" - f := New().Funcs( - // This should take precedence over SelfFuzzer.Fuzz(). - func(s *SelfFuzzer, c Continue) { - *s = privateTestPhrase - }, - ) - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != privateTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != privateTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_noCustom(t *testing.T) { - type Inner struct { - Str string - } - type Outer struct { - Str string - In Inner - } - - testPhrase := "gotcalled" - f := New().Funcs( - func(outer *Outer, c Continue) { - outer.Str = testPhrase - c.Fuzz(&outer.In) - }, - func(inner *Inner, c Continue) { - inner.Str = testPhrase - }, - ) - c := Continue{f: f, Rand: f.r} - - // Fuzzer.Fuzz() - obj1 := Outer{} - f.Fuzz(&obj1) - if obj1.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj1.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.Fuzz() - obj2 := Outer{} - c.Fuzz(&obj2) - if obj2.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj2.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Fuzzer.FuzzNoCustom() - obj3 := Outer{} - f.FuzzNoCustom(&obj3) - if obj3.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj3.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.FuzzNoCustom() - obj4 := Outer{} - c.FuzzNoCustom(&obj4) - if obj4.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj4.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } -} diff --git a/Godeps/_workspace/src/github.com/imdario/mergo/mergo_test.go b/Godeps/_workspace/src/github.com/imdario/mergo/mergo_test.go deleted file mode 100644 index 072bddb79..000000000 --- a/Godeps/_workspace/src/github.com/imdario/mergo/mergo_test.go +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// 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 mergo - -import ( - "gopkg.in/yaml.v1" - "io/ioutil" - "reflect" - "testing" -) - -type simpleTest struct { - Value int -} - -type complexTest struct { - St simpleTest - sz int - Id string -} - -type moreComplextText struct { - Ct complexTest - St simpleTest - Nt simpleTest -} - -type pointerTest struct { - C *simpleTest -} - -type sliceTest struct { - S []int -} - -func TestNil(t *testing.T) { - if err := Merge(nil, nil); err != ErrNilArguments { - t.Fail() - } -} - -func TestDifferentTypes(t *testing.T) { - a := simpleTest{42} - b := 42 - if err := Merge(&a, b); err != ErrDifferentArgumentsTypes { - t.Fail() - } -} - -func TestSimpleStruct(t *testing.T) { - a := simpleTest{} - b := simpleTest{42} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in a properly: a.Value(%d) != b.Value(%d)", a.Value, b.Value) - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -func TestComplexStruct(t *testing.T) { - a := complexTest{} - a.Id = "athing" - b := complexTest{simpleTest{42}, 1, "bthing"} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.St.Value != 42 { - t.Fatalf("b not merged in a properly: a.St.Value(%d) != b.St.Value(%d)", a.St.Value, b.St.Value) - } - if a.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: a.sz(%d) == b.sz(%d)", a.sz, b.sz) - } - if a.Id != b.Id { - t.Fatalf("a's field Id not merged properly: a.Id(%s) != b.Id(%s)", a.Id, b.Id) - } -} - -func TestPointerStruct(t *testing.T) { - s1 := simpleTest{} - s2 := simpleTest{19} - a := pointerTest{&s1} - b := pointerTest{&s2} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - //t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -func TestPointerStructNil(t *testing.T) { - a := pointerTest{nil} - b := pointerTest{&simpleTest{19}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -func TestSliceStruct(t *testing.T) { - a := sliceTest{} - b := sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(b.S) != 3 { - t.FailNow() - } - if len(a.S) != len(b.S) { - t.Fatalf("b not merged in a properly %d != %d", len(a.S), len(b.S)) - } - - a = sliceTest{[]int{1}} - b = sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(b.S) != 3 { - t.FailNow() - } - if len(a.S) != len(b.S) { - t.Fatalf("b not merged in a properly %d != %d", len(a.S), len(b.S)) - } -} - -func TestMaps(t *testing.T) { - m := map[string]simpleTest{ - "a": simpleTest{}, - "b": simpleTest{42}, - } - n := map[string]simpleTest{ - "a": simpleTest{16}, - "b": simpleTest{}, - "c": simpleTest{12}, - } - if err := Merge(&m, n); err != nil { - t.Fatalf(err.Error()) - } - if len(m) != 3 { - t.Fatalf(`n not merged in m properly, m must have 3 elements instead of %d`, len(m)) - } - if m["a"].Value != 0 { - t.Fatalf(`n merged in m because I solved non-addressable map values TODO: m["a"].Value(%d) != n["a"].Value(%d)`, m["a"].Value, n["a"].Value) - } - if m["b"].Value != 42 { - t.Fatalf(`n wrongly merged in m: m["b"].Value(%d) != n["b"].Value(%d)`, m["b"].Value, n["b"].Value) - } - if m["c"].Value != 12 { - t.Fatalf(`n not merged in m: m["c"].Value(%d) != n["c"].Value(%d)`, m["c"].Value, n["c"].Value) - } -} - -func TestYAMLMaps(t *testing.T) { - thing := loadYAML("testdata/thing.yml") - license := loadYAML("testdata/license.yml") - ft := thing["fields"].(map[interface{}]interface{}) - fl := license["fields"].(map[interface{}]interface{}) - expectedLength := len(ft) + len(fl) - if err := Merge(&license, thing); err != nil { - t.Fatal(err.Error()) - } - currentLength := len(license["fields"].(map[interface{}]interface{})) - if currentLength != expectedLength { - t.Fatalf(`thing not merged in license properly, license must have %d elements instead of %d`, expectedLength, currentLength) - } - fields := license["fields"].(map[interface{}]interface{}) - if _, ok := fields["id"]; !ok { - t.Fatalf(`thing not merged in license properly, license must have a new id field from thing`) - } -} - -func TestTwoPointerValues(t *testing.T) { - a := &simpleTest{} - b := &simpleTest{42} - if err := Merge(a, b); err != nil { - t.Fatalf(`Boom. You crossed the streams: %s`, err) - } -} - -func TestMap(t *testing.T) { - a := complexTest{} - a.Id = "athing" - c := moreComplextText{a, simpleTest{}, simpleTest{}} - b := map[string]interface{}{ - "ct": map[string]interface{}{ - "st": map[string]interface{}{ - "value": 42, - }, - "sz": 1, - "id": "bthing", - }, - "st": &simpleTest{144}, // Mapping a reference - "zt": simpleTest{299}, // Mapping a missing field (zt doesn't exist) - "nt": simpleTest{3}, - } - if err := Map(&c, b); err != nil { - t.FailNow() - } - m := b["ct"].(map[string]interface{}) - n := m["st"].(map[string]interface{}) - o := b["st"].(*simpleTest) - p := b["nt"].(simpleTest) - if c.Ct.St.Value != 42 { - t.Fatalf("b not merged in a properly: c.Ct.St.Value(%d) != b.Ct.St.Value(%d)", c.Ct.St.Value, n["value"]) - } - if c.St.Value != 144 { - t.Fatalf("b not merged in a properly: c.St.Value(%d) != b.St.Value(%d)", c.St.Value, o.Value) - } - if c.Nt.Value != 3 { - t.Fatalf("b not merged in a properly: c.Nt.Value(%d) != b.Nt.Value(%d)", c.St.Value, p.Value) - } - if c.Ct.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: c.Ct.sz(%d) == b.Ct.sz(%d)", c.Ct.sz, m["sz"]) - } - if c.Ct.Id != m["id"] { - t.Fatalf("a's field Id not merged properly: c.Ct.Id(%s) != b.Ct.Id(%s)", c.Ct.Id, m["id"]) - } -} - -func TestSimpleMap(t *testing.T) { - a := simpleTest{} - b := map[string]interface{}{ - "value": 42, - } - if err := Map(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in a properly: a.Value(%d) != b.Value(%v)", a.Value, b["value"]) - } -} - -type pointerMapTest struct { - A int - hidden int - B *simpleTest -} - -func TestBackAndForth(t *testing.T) { - pt := pointerMapTest{42, 1, &simpleTest{66}} - m := make(map[string]interface{}) - if err := Map(&m, pt); err != nil { - t.FailNow() - } - var ( - v interface{} - ok bool - ) - if v, ok = m["a"]; v.(int) != pt.A || !ok { - t.Fatalf("pt not merged properly: m[`a`](%d) != pt.A(%d)", v, pt.A) - } - if v, ok = m["b"]; !ok { - t.Fatalf("pt not merged properly: B is missing in m") - } - var st *simpleTest - if st = v.(*simpleTest); st.Value != 66 { - t.Fatalf("something went wrong while mapping pt on m, B wasn't copied") - } - bpt := pointerMapTest{} - if err := Map(&bpt, m); err != nil { - t.Fatal(err) - } - if bpt.A != pt.A { - t.Fatalf("pt not merged properly: bpt.A(%d) != pt.A(%d)", bpt.A, pt.A) - } - if bpt.hidden == pt.hidden { - t.Fatalf("pt unexpectedly merged: bpt.hidden(%d) == pt.hidden(%d)", bpt.hidden, pt.hidden) - } - if bpt.B.Value != pt.B.Value { - t.Fatalf("pt not merged properly: bpt.B.Value(%d) != pt.B.Value(%d)", bpt.B.Value, pt.B.Value) - } -} - -func loadYAML(path string) (m map[string]interface{}) { - m = make(map[string]interface{}) - raw, _ := ioutil.ReadFile(path) - _ = yaml.Unmarshal(raw, &m) - return -} diff --git a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/license.yml b/Godeps/_workspace/src/github.com/imdario/mergo/testdata/license.yml deleted file mode 100644 index 62fdb61ec..000000000 --- a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/license.yml +++ /dev/null @@ -1,3 +0,0 @@ -import: ../../../../fossene/db/schema/thing.yml -fields: - site: string diff --git a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/thing.yml b/Godeps/_workspace/src/github.com/imdario/mergo/testdata/thing.yml deleted file mode 100644 index c28eab0d0..000000000 --- a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/thing.yml +++ /dev/null @@ -1,5 +0,0 @@ -fields: - id: int - name: string - parent: ref "datu:thing" - status: enum(draft, public, private) diff --git a/Godeps/_workspace/src/github.com/juju/ratelimit/ratelimit_test.go b/Godeps/_workspace/src/github.com/juju/ratelimit/ratelimit_test.go deleted file mode 100644 index 62d88ded0..000000000 --- a/Godeps/_workspace/src/github.com/juju/ratelimit/ratelimit_test.go +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright 2014 Canonical Ltd. -// Licensed under the LGPLv3 with static-linking exception. -// See LICENCE file for details. - -package ratelimit - -import ( - "math" - "testing" - "time" - - gc "gopkg.in/check.v1" -) - -func TestPackage(t *testing.T) { - gc.TestingT(t) -} - -type rateLimitSuite struct{} - -var _ = gc.Suite(rateLimitSuite{}) - -type takeReq struct { - time time.Duration - count int64 - expectWait time.Duration -} - -var takeTests = []struct { - about string - fillInterval time.Duration - capacity int64 - reqs []takeReq -}{{ - about: "serial requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 0, - expectWait: 0, - }, { - time: 0, - count: 10, - expectWait: 0, - }, { - time: 0, - count: 1, - expectWait: 250 * time.Millisecond, - }, { - time: 250 * time.Millisecond, - count: 1, - expectWait: 250 * time.Millisecond, - }}, -}, { - about: "concurrent requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 10, - expectWait: 0, - }, { - time: 0, - count: 2, - expectWait: 500 * time.Millisecond, - }, { - time: 0, - count: 2, - expectWait: 1000 * time.Millisecond, - }, { - time: 0, - count: 1, - expectWait: 1250 * time.Millisecond, - }}, -}, { - about: "more than capacity", - fillInterval: 1 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 10, - expectWait: 0, - }, { - time: 20 * time.Millisecond, - count: 15, - expectWait: 5 * time.Millisecond, - }}, -}, { - about: "sub-quantum time", - fillInterval: 10 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 10, - expectWait: 0, - }, { - time: 7 * time.Millisecond, - count: 1, - expectWait: 3 * time.Millisecond, - }, { - time: 8 * time.Millisecond, - count: 1, - expectWait: 12 * time.Millisecond, - }}, -}, { - about: "within capacity", - fillInterval: 10 * time.Millisecond, - capacity: 5, - reqs: []takeReq{{ - time: 0, - count: 5, - expectWait: 0, - }, { - time: 60 * time.Millisecond, - count: 5, - expectWait: 0, - }, { - time: 60 * time.Millisecond, - count: 1, - expectWait: 10 * time.Millisecond, - }, { - time: 80 * time.Millisecond, - count: 2, - expectWait: 10 * time.Millisecond, - }}, -}} - -var availTests = []struct { - about string - capacity int64 - fillInterval time.Duration - take int64 - sleep time.Duration - - expectCountAfterTake int64 - expectCountAfterSleep int64 -}{{ - about: "should fill tokens after interval", - capacity: 5, - fillInterval: time.Second, - take: 5, - sleep: time.Second, - expectCountAfterTake: 0, - expectCountAfterSleep: 1, -}, { - about: "should fill tokens plus existing count", - capacity: 2, - fillInterval: time.Second, - take: 1, - sleep: time.Second, - expectCountAfterTake: 1, - expectCountAfterSleep: 2, -}, { - about: "shouldn't fill before interval", - capacity: 2, - fillInterval: 2 * time.Second, - take: 1, - sleep: time.Second, - expectCountAfterTake: 1, - expectCountAfterSleep: 1, -}, { - about: "should fill only once after 1*interval before 2*interval", - capacity: 2, - fillInterval: 2 * time.Second, - take: 1, - sleep: 3 * time.Second, - expectCountAfterTake: 1, - expectCountAfterSleep: 2, -}} - -func (rateLimitSuite) TestTake(c *gc.C) { - for i, test := range takeTests { - tb := NewBucket(test.fillInterval, test.capacity) - for j, req := range test.reqs { - d, ok := tb.take(tb.startTime.Add(req.time), req.count, infinityDuration) - c.Assert(ok, gc.Equals, true) - if d != req.expectWait { - c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) - } - } - } -} - -func (rateLimitSuite) TestTakeMaxDuration(c *gc.C) { - for i, test := range takeTests { - tb := NewBucket(test.fillInterval, test.capacity) - for j, req := range test.reqs { - if req.expectWait > 0 { - d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait-1) - c.Assert(ok, gc.Equals, false) - c.Assert(d, gc.Equals, time.Duration(0)) - } - d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait) - c.Assert(ok, gc.Equals, true) - if d != req.expectWait { - c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) - } - } - } -} - -type takeAvailableReq struct { - time time.Duration - count int64 - expect int64 -} - -var takeAvailableTests = []struct { - about string - fillInterval time.Duration - capacity int64 - reqs []takeAvailableReq -}{{ - about: "serial requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeAvailableReq{{ - time: 0, - count: 0, - expect: 0, - }, { - time: 0, - count: 10, - expect: 10, - }, { - time: 0, - count: 1, - expect: 0, - }, { - time: 250 * time.Millisecond, - count: 1, - expect: 1, - }}, -}, { - about: "concurrent requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeAvailableReq{{ - time: 0, - count: 5, - expect: 5, - }, { - time: 0, - count: 2, - expect: 2, - }, { - time: 0, - count: 5, - expect: 3, - }, { - time: 0, - count: 1, - expect: 0, - }}, -}, { - about: "more than capacity", - fillInterval: 1 * time.Millisecond, - capacity: 10, - reqs: []takeAvailableReq{{ - time: 0, - count: 10, - expect: 10, - }, { - time: 20 * time.Millisecond, - count: 15, - expect: 10, - }}, -}, { - about: "within capacity", - fillInterval: 10 * time.Millisecond, - capacity: 5, - reqs: []takeAvailableReq{{ - time: 0, - count: 5, - expect: 5, - }, { - time: 60 * time.Millisecond, - count: 5, - expect: 5, - }, { - time: 70 * time.Millisecond, - count: 1, - expect: 1, - }}, -}} - -func (rateLimitSuite) TestTakeAvailable(c *gc.C) { - for i, test := range takeAvailableTests { - tb := NewBucket(test.fillInterval, test.capacity) - for j, req := range test.reqs { - d := tb.takeAvailable(tb.startTime.Add(req.time), req.count) - if d != req.expect { - c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expect) - } - } - } -} - -func (rateLimitSuite) TestPanics(c *gc.C) { - c.Assert(func() { NewBucket(0, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") - c.Assert(func() { NewBucket(-2, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") - c.Assert(func() { NewBucket(1, 0) }, gc.PanicMatches, "token bucket capacity is not > 0") - c.Assert(func() { NewBucket(1, -2) }, gc.PanicMatches, "token bucket capacity is not > 0") -} - -func isCloseTo(x, y, tolerance float64) bool { - return math.Abs(x-y)/y < tolerance -} - -func (rateLimitSuite) TestRate(c *gc.C) { - tb := NewBucket(1, 1) - if !isCloseTo(tb.Rate(), 1e9, 0.00001) { - c.Fatalf("got %v want 1e9", tb.Rate()) - } - tb = NewBucket(2*time.Second, 1) - if !isCloseTo(tb.Rate(), 0.5, 0.00001) { - c.Fatalf("got %v want 0.5", tb.Rate()) - } - tb = NewBucketWithQuantum(100*time.Millisecond, 1, 5) - if !isCloseTo(tb.Rate(), 50, 0.00001) { - c.Fatalf("got %v want 50", tb.Rate()) - } -} - -func checkRate(c *gc.C, rate float64) { - tb := NewBucketWithRate(rate, 1<<62) - if !isCloseTo(tb.Rate(), rate, rateMargin) { - c.Fatalf("got %g want %v", tb.Rate(), rate) - } - d, ok := tb.take(tb.startTime, 1<<62, infinityDuration) - c.Assert(ok, gc.Equals, true) - c.Assert(d, gc.Equals, time.Duration(0)) - - // Check that the actual rate is as expected by - // asking for a not-quite multiple of the bucket's - // quantum and checking that the wait time - // correct. - d, ok = tb.take(tb.startTime, tb.quantum*2-tb.quantum/2, infinityDuration) - c.Assert(ok, gc.Equals, true) - expectTime := 1e9 * float64(tb.quantum) * 2 / rate - if !isCloseTo(float64(d), expectTime, rateMargin) { - c.Fatalf("rate %g: got %g want %v", rate, float64(d), expectTime) - } -} - -func (rateLimitSuite) TestNewWithRate(c *gc.C) { - for rate := float64(1); rate < 1e6; rate += 7 { - checkRate(c, rate) - } - for _, rate := range []float64{ - 1024 * 1024 * 1024, - 1e-5, - 0.9e-5, - 0.5, - 0.9, - 0.9e8, - 3e12, - 4e18, - } { - checkRate(c, rate) - checkRate(c, rate/3) - checkRate(c, rate*1.3) - } -} - -func TestAvailable(t *testing.T) { - for i, tt := range availTests { - tb := NewBucket(tt.fillInterval, tt.capacity) - if c := tb.takeAvailable(tb.startTime, tt.take); c != tt.take { - t.Fatalf("#%d: %s, take = %d, want = %d", i, tt.about, c, tt.take) - } - if c := tb.available(tb.startTime); c != tt.expectCountAfterTake { - t.Fatalf("#%d: %s, after take, available = %d, want = %d", i, tt.about, c, tt.expectCountAfterTake) - } - if c := tb.available(tb.startTime.Add(tt.sleep)); c != tt.expectCountAfterSleep { - t.Fatalf("#%d: %s, after some time it should fill in new tokens, available = %d, want = %d", - i, tt.about, c, tt.expectCountAfterSleep) - } - } - -} - -func BenchmarkWait(b *testing.B) { - tb := NewBucket(1, 16*1024) - for i := b.N - 1; i >= 0; i-- { - tb.Wait(1) - } -} diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/LICENSE b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/LICENSE new file mode 100644 index 000000000..13f15dfce --- /dev/null +++ b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/LICENSE @@ -0,0 +1,201 @@ + 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 2013 Matt T. Proud + + 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/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go deleted file mode 100644 index 094156e66..000000000 --- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2013 Matt T. Proud -// -// 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 pbutil - -import ( - "bytes" - "math/rand" - "reflect" - "testing" - "testing/quick" - - "github.com/matttproud/golang_protobuf_extensions/pbtest" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -func TestWriteDelimited(t *testing.T) { - for _, test := range []struct { - msg Message - buf []byte - n int - err error - }{ - { - msg: &Empty{}, - n: 1, - buf: []byte{0}, - }, - { - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - n: 3, - buf: []byte{2, 8, 1}, - }, - { - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - }, - } { - var buf bytes.Buffer - if n, err := WriteDelimited(&buf, test.msg); n != test.n || err != test.err { - t.Fatalf("WriteDelimited(buf, %#v) = %v, %v; want %v, %v", test.msg, n, err, test.n, test.err) - } - if out := buf.Bytes(); !bytes.Equal(out, test.buf) { - t.Fatalf("WriteDelimited(buf, %#v); buf = %v; want %v", test.msg, out, test.buf) - } - } -} - -func TestReadDelimited(t *testing.T) { - for _, test := range []struct { - buf []byte - msg Message - n int - err error - }{ - { - buf: []byte{0}, - msg: &Empty{}, - n: 1, - }, - { - n: 3, - buf: []byte{2, 8, 1}, - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - }, - { - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - }, - } { - msg := Clone(test.msg) - msg.Reset() - if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err { - t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err) - } - if !Equal(msg, test.msg) { - t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg) - } - } -} - -func TestEndToEndValid(t *testing.T) { - for _, test := range [][]Message{ - {&Empty{}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}}, - {&Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }}, - } { - var buf bytes.Buffer - var written int - for i, msg := range test { - n, err := WriteDelimited(&buf, msg) - if err != nil { - // Assumption: TestReadDelimited and TestWriteDelimited are sufficient - // and inputs for this test are explicitly exercised there. - t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", test, i, err) - } - written += n - } - var read int - for i, msg := range test { - out := Clone(msg) - out.Reset() - n, _ := ReadDelimited(&buf, out) - // Decide to do EOF checking? - read += n - if !Equal(out, msg) { - t.Fatalf("out = %v; want %v[%d] = %#v", out, test, i, msg) - } - } - if read != written { - t.Fatalf("%v read = %d; want %d", test, read, written) - } - } -} - -// rndMessage generates a random valid Protocol Buffer message. -func rndMessage(r *rand.Rand) Message { - var t reflect.Type - switch v := rand.Intn(23); v { - // TODO(br): Uncomment the elements below once fix is incorporated, except - // for the elements marked as patently incompatible. - // case 0: - // t = reflect.TypeOf(&GoEnum{}) - // break - // case 1: - // t = reflect.TypeOf(&GoTestField{}) - // break - case 2: - t = reflect.TypeOf(&GoTest{}) - break - // case 3: - // t = reflect.TypeOf(&GoSkipTest{}) - // break - // case 4: - // t = reflect.TypeOf(&NonPackedTest{}) - // break - // case 5: - // t = reflect.TypeOf(&PackedTest{}) - // break - case 6: - t = reflect.TypeOf(&MaxTag{}) - break - case 7: - t = reflect.TypeOf(&OldMessage{}) - break - case 8: - t = reflect.TypeOf(&NewMessage{}) - break - case 9: - t = reflect.TypeOf(&InnerMessage{}) - break - case 10: - t = reflect.TypeOf(&OtherMessage{}) - break - case 11: - // PATENTLY INVALID FOR FUZZ GENERATION - // t = reflect.TypeOf(&MyMessage{}) - break - // case 12: - // t = reflect.TypeOf(&Ext{}) - // break - case 13: - // PATENTLY INVALID FOR FUZZ GENERATION - // t = reflect.TypeOf(&MyMessageSet{}) - break - // case 14: - // t = reflect.TypeOf(&Empty{}) - // break - // case 15: - // t = reflect.TypeOf(&MessageList{}) - // break - // case 16: - // t = reflect.TypeOf(&Strings{}) - // break - // case 17: - // t = reflect.TypeOf(&Defaults{}) - // break - // case 17: - // t = reflect.TypeOf(&SubDefaults{}) - // break - // case 18: - // t = reflect.TypeOf(&RepeatedEnum{}) - // break - case 19: - t = reflect.TypeOf(&MoreRepeated{}) - break - // case 20: - // t = reflect.TypeOf(&GroupOld{}) - // break - // case 21: - // t = reflect.TypeOf(&GroupNew{}) - // break - case 22: - t = reflect.TypeOf(&FloatingPoint{}) - break - default: - // TODO(br): Replace with an unreachable once fixed. - t = reflect.TypeOf(&GoTest{}) - break - } - if t == nil { - t = reflect.TypeOf(&GoTest{}) - } - v, ok := quick.Value(t, r) - if !ok { - panic("attempt to generate illegal item; consult item 11") - } - if err := pbtest.SanitizeGenerated(v.Interface().(Message)); err != nil { - panic(err) - } - return v.Interface().(Message) -} - -// rndMessages generates several random Protocol Buffer messages. -func rndMessages(r *rand.Rand) []Message { - n := r.Intn(128) - out := make([]Message, 0, n) - for i := 0; i < n; i++ { - out = append(out, rndMessage(r)) - } - return out -} - -func TestFuzz(t *testing.T) { - rnd := rand.New(rand.NewSource(42)) - check := func() bool { - messages := rndMessages(rnd) - var buf bytes.Buffer - var written int - for i, msg := range messages { - n, err := WriteDelimited(&buf, msg) - if err != nil { - t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", messages, i, err) - } - written += n - } - var read int - for i, msg := range messages { - out := Clone(msg) - out.Reset() - n, _ := ReadDelimited(&buf, out) - read += n - if !Equal(out, msg) { - t.Fatalf("out = %v; want %v[%d] = %#v", out, messages, i, msg) - } - } - if read != written { - t.Fatalf("%v read = %d; want %d", messages, read, written) - } - return true - } - if err := quick.Check(check, nil); err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go deleted file mode 100644 index d6d9b2559..000000000 --- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// http://github.com/golang/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. -// * 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. - -package pbutil - -import ( - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -// FROM https://github.com/golang/protobuf/blob/master/proto/all_test.go. - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/LICENSE b/Godeps/_workspace/src/github.com/opencontainers/runc/LICENSE new file mode 100644 index 000000000..27448585a --- /dev/null +++ b/Godeps/_workspace/src/github.com/opencontainers/runc/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 2014 Docker, Inc. + + 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/Godeps/_workspace/src/github.com/opencontainers/runc/NOTICE b/Godeps/_workspace/src/github.com/opencontainers/runc/NOTICE new file mode 100644 index 000000000..5c97abce4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/opencontainers/runc/NOTICE @@ -0,0 +1,17 @@ +runc + +Copyright 2012-2015 Docker, Inc. + +This product includes software developed at Docker, Inc. (http://www.docker.com). + +The following is courtesy of our legal counsel: + + +Use and transfer of Docker may be subject to certain restrictions by the +United States and other governments. +It is your responsibility to ensure that your use and/or transfer does not +violate applicable laws. + +For more information, please see http://www.bis.doc.gov + +See also http://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_test.go deleted file mode 100644 index 2f702bc2e..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_test.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build linux - -package cgroups - -import ( - "testing" -) - -func TestParseCgroups(t *testing.T) { - cgroups, err := ParseCgroupFile("/proc/self/cgroup") - if err != nil { - t.Fatal(err) - } - - if _, ok := cgroups["cpu"]; !ok { - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio_test.go deleted file mode 100644 index 695739204..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio_test.go +++ /dev/null @@ -1,636 +0,0 @@ -// +build linux - -package fs - -import ( - "strconv" - "testing" - - "github.com/opencontainers/runc/libcontainer/cgroups" - "github.com/opencontainers/runc/libcontainer/configs" -) - -const ( - sectorsRecursiveContents = `8:0 1024` - serviceBytesRecursiveContents = `8:0 Read 100 -8:0 Write 200 -8:0 Sync 300 -8:0 Async 500 -8:0 Total 500 -Total 500` - servicedRecursiveContents = `8:0 Read 10 -8:0 Write 40 -8:0 Sync 20 -8:0 Async 30 -8:0 Total 50 -Total 50` - queuedRecursiveContents = `8:0 Read 1 -8:0 Write 4 -8:0 Sync 2 -8:0 Async 3 -8:0 Total 5 -Total 5` - serviceTimeRecursiveContents = `8:0 Read 173959 -8:0 Write 0 -8:0 Sync 0 -8:0 Async 173959 -8:0 Total 17395 -Total 17395` - waitTimeRecursiveContents = `8:0 Read 15571 -8:0 Write 0 -8:0 Sync 0 -8:0 Async 15571 -8:0 Total 15571` - mergedRecursiveContents = `8:0 Read 5 -8:0 Write 10 -8:0 Sync 0 -8:0 Async 0 -8:0 Total 15 -Total 15` - timeRecursiveContents = `8:0 8` - throttleServiceBytes = `8:0 Read 11030528 -8:0 Write 23 -8:0 Sync 42 -8:0 Async 11030528 -8:0 Total 11030528 -252:0 Read 11030528 -252:0 Write 23 -252:0 Sync 42 -252:0 Async 11030528 -252:0 Total 11030528 -Total 22061056` - throttleServiced = `8:0 Read 164 -8:0 Write 23 -8:0 Sync 42 -8:0 Async 164 -8:0 Total 164 -252:0 Read 164 -252:0 Write 23 -252:0 Sync 42 -252:0 Async 164 -252:0 Total 164 -Total 328` -) - -func appendBlkioStatEntry(blkioStatEntries *[]cgroups.BlkioStatEntry, major, minor, value uint64, op string) { - *blkioStatEntries = append(*blkioStatEntries, cgroups.BlkioStatEntry{Major: major, Minor: minor, Value: value, Op: op}) -} - -func TestBlkioSetWeight(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - weightBefore = 100 - weightAfter = 200 - ) - - helper.writeFileContents(map[string]string{ - "blkio.weight": strconv.Itoa(weightBefore), - }) - - helper.CgroupData.config.Resources.BlkioWeight = weightAfter - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "blkio.weight") - if err != nil { - t.Fatalf("Failed to parse blkio.weight - %s", err) - } - - if value != weightAfter { - t.Fatal("Got the wrong value, set blkio.weight failed.") - } -} - -func TestBlkioSetWeightDevice(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - weightDeviceBefore = "8:0 400" - ) - - wd := configs.NewWeightDevice(8, 0, 500, 0) - weightDeviceAfter := wd.WeightString() - - helper.writeFileContents(map[string]string{ - "blkio.weight_device": weightDeviceBefore, - }) - - helper.CgroupData.config.Resources.BlkioWeightDevice = []*configs.WeightDevice{wd} - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "blkio.weight_device") - if err != nil { - t.Fatalf("Failed to parse blkio.weight_device - %s", err) - } - - if value != weightDeviceAfter { - t.Fatal("Got the wrong value, set blkio.weight_device failed.") - } -} - -// regression #274 -func TestBlkioSetMultipleWeightDevice(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - weightDeviceBefore = "8:0 400" - ) - - wd1 := configs.NewWeightDevice(8, 0, 500, 0) - wd2 := configs.NewWeightDevice(8, 16, 500, 0) - // we cannot actually set and check both because normal ioutil.WriteFile - // when writing to cgroup file will overwrite the whole file content instead - // of updating it as the kernel is doing. Just check the second device - // is present will suffice for the test to ensure multiple writes are done. - weightDeviceAfter := wd2.WeightString() - - helper.writeFileContents(map[string]string{ - "blkio.weight_device": weightDeviceBefore, - }) - - helper.CgroupData.config.Resources.BlkioWeightDevice = []*configs.WeightDevice{wd1, wd2} - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "blkio.weight_device") - if err != nil { - t.Fatalf("Failed to parse blkio.weight_device - %s", err) - } - - if value != weightDeviceAfter { - t.Fatal("Got the wrong value, set blkio.weight_device failed.") - } -} - -func TestBlkioStats(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - - // Verify expected stats. - expectedStats := cgroups.BlkioStats{} - appendBlkioStatEntry(&expectedStats.SectorsRecursive, 8, 0, 1024, "") - - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 100, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 200, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 300, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 500, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 500, "Total") - - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 10, "Read") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 40, "Write") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 20, "Sync") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 30, "Async") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 50, "Total") - - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 1, "Read") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 4, "Write") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 2, "Sync") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 3, "Async") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 5, "Total") - - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 173959, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 0, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 0, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 173959, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 17395, "Total") - - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Read") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 0, "Write") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 0, "Sync") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Async") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Total") - - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 5, "Read") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 10, "Write") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 0, "Sync") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 0, "Async") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 15, "Total") - - appendBlkioStatEntry(&expectedStats.IoTimeRecursive, 8, 0, 8, "") - - expectBlkioStatsEquals(t, expectedStats, actualStats.BlkioStats) -} - -func TestBlkioStatsNoSectorsFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoServiceBytesFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoServicedFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoQueuedFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoServiceTimeFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoWaitTimeFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoMergedFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoTimeFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsUnexpectedNumberOfFields(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": "8:0 Read 100 100", - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected to fail, but did not") - } -} - -func TestBlkioStatsUnexpectedFieldType(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": "8:0 Read Write", - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected to fail, but did not") - } -} - -func TestNonCFQBlkioStats(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": "", - "blkio.io_serviced_recursive": "", - "blkio.io_queued_recursive": "", - "blkio.sectors_recursive": "", - "blkio.io_service_time_recursive": "", - "blkio.io_wait_time_recursive": "", - "blkio.io_merged_recursive": "", - "blkio.time_recursive": "", - "blkio.throttle.io_service_bytes": throttleServiceBytes, - "blkio.throttle.io_serviced": throttleServiced, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - - // Verify expected stats. - expectedStats := cgroups.BlkioStats{} - - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Total") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Total") - - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Read") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Async") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Total") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Read") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Async") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Total") - - expectBlkioStatsEquals(t, expectedStats, actualStats.BlkioStats) -} - -func TestBlkioSetThrottleReadBpsDevice(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - throttleBefore = `8:0 1024` - ) - - td := configs.NewThrottleDevice(8, 0, 2048) - throttleAfter := td.String() - - helper.writeFileContents(map[string]string{ - "blkio.throttle.read_bps_device": throttleBefore, - }) - - helper.CgroupData.config.Resources.BlkioThrottleReadBpsDevice = []*configs.ThrottleDevice{td} - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.read_bps_device") - if err != nil { - t.Fatalf("Failed to parse blkio.throttle.read_bps_device - %s", err) - } - - if value != throttleAfter { - t.Fatal("Got the wrong value, set blkio.throttle.read_bps_device failed.") - } -} -func TestBlkioSetThrottleWriteBpsDevice(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - throttleBefore = `8:0 1024` - ) - - td := configs.NewThrottleDevice(8, 0, 2048) - throttleAfter := td.String() - - helper.writeFileContents(map[string]string{ - "blkio.throttle.write_bps_device": throttleBefore, - }) - - helper.CgroupData.config.Resources.BlkioThrottleWriteBpsDevice = []*configs.ThrottleDevice{td} - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.write_bps_device") - if err != nil { - t.Fatalf("Failed to parse blkio.throttle.write_bps_device - %s", err) - } - - if value != throttleAfter { - t.Fatal("Got the wrong value, set blkio.throttle.write_bps_device failed.") - } -} -func TestBlkioSetThrottleReadIOpsDevice(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - throttleBefore = `8:0 1024` - ) - - td := configs.NewThrottleDevice(8, 0, 2048) - throttleAfter := td.String() - - helper.writeFileContents(map[string]string{ - "blkio.throttle.read_iops_device": throttleBefore, - }) - - helper.CgroupData.config.Resources.BlkioThrottleReadIOPSDevice = []*configs.ThrottleDevice{td} - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.read_iops_device") - if err != nil { - t.Fatalf("Failed to parse blkio.throttle.read_iops_device - %s", err) - } - - if value != throttleAfter { - t.Fatal("Got the wrong value, set blkio.throttle.read_iops_device failed.") - } -} -func TestBlkioSetThrottleWriteIOpsDevice(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - throttleBefore = `8:0 1024` - ) - - td := configs.NewThrottleDevice(8, 0, 2048) - throttleAfter := td.String() - - helper.writeFileContents(map[string]string{ - "blkio.throttle.write_iops_device": throttleBefore, - }) - - helper.CgroupData.config.Resources.BlkioThrottleWriteIOPSDevice = []*configs.ThrottleDevice{td} - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.write_iops_device") - if err != nil { - t.Fatalf("Failed to parse blkio.throttle.write_iops_device - %s", err) - } - - if value != throttleAfter { - t.Fatal("Got the wrong value, set blkio.throttle.write_iops_device failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu_test.go deleted file mode 100644 index 554fd5e85..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu_test.go +++ /dev/null @@ -1,163 +0,0 @@ -// +build linux - -package fs - -import ( - "fmt" - "strconv" - "testing" - - "github.com/opencontainers/runc/libcontainer/cgroups" -) - -func TestCpuSetShares(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - const ( - sharesBefore = 1024 - sharesAfter = 512 - ) - - helper.writeFileContents(map[string]string{ - "cpu.shares": strconv.Itoa(sharesBefore), - }) - - helper.CgroupData.config.Resources.CpuShares = sharesAfter - cpu := &CpuGroup{} - if err := cpu.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "cpu.shares") - if err != nil { - t.Fatalf("Failed to parse cpu.shares - %s", err) - } - - if value != sharesAfter { - t.Fatal("Got the wrong value, set cpu.shares failed.") - } -} - -func TestCpuSetBandWidth(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - const ( - quotaBefore = 8000 - quotaAfter = 5000 - periodBefore = 10000 - periodAfter = 7000 - rtRuntimeBefore = 8000 - rtRuntimeAfter = 5000 - rtPeriodBefore = 10000 - rtPeriodAfter = 7000 - ) - - helper.writeFileContents(map[string]string{ - "cpu.cfs_quota_us": strconv.Itoa(quotaBefore), - "cpu.cfs_period_us": strconv.Itoa(periodBefore), - "cpu.rt_runtime_us": strconv.Itoa(rtRuntimeBefore), - "cpu.rt_period_us": strconv.Itoa(rtPeriodBefore), - }) - - helper.CgroupData.config.Resources.CpuQuota = quotaAfter - helper.CgroupData.config.Resources.CpuPeriod = periodAfter - helper.CgroupData.config.Resources.CpuRtRuntime = rtRuntimeAfter - helper.CgroupData.config.Resources.CpuRtPeriod = rtPeriodAfter - cpu := &CpuGroup{} - if err := cpu.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - quota, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_quota_us") - if err != nil { - t.Fatalf("Failed to parse cpu.cfs_quota_us - %s", err) - } - if quota != quotaAfter { - t.Fatal("Got the wrong value, set cpu.cfs_quota_us failed.") - } - - period, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_period_us") - if err != nil { - t.Fatalf("Failed to parse cpu.cfs_period_us - %s", err) - } - if period != periodAfter { - t.Fatal("Got the wrong value, set cpu.cfs_period_us failed.") - } - rtRuntime, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_runtime_us") - if err != nil { - t.Fatalf("Failed to parse cpu.rt_runtime_us - %s", err) - } - if rtRuntime != rtRuntimeAfter { - t.Fatal("Got the wrong value, set cpu.rt_runtime_us failed.") - } - rtPeriod, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_period_us") - if err != nil { - t.Fatalf("Failed to parse cpu.rt_period_us - %s", err) - } - if rtPeriod != rtPeriodAfter { - t.Fatal("Got the wrong value, set cpu.rt_period_us failed.") - } -} - -func TestCpuStats(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - const ( - kNrPeriods = 2000 - kNrThrottled = 200 - kThrottledTime = uint64(18446744073709551615) - ) - - cpuStatContent := fmt.Sprintf("nr_periods %d\n nr_throttled %d\n throttled_time %d\n", - kNrPeriods, kNrThrottled, kThrottledTime) - helper.writeFileContents(map[string]string{ - "cpu.stat": cpuStatContent, - }) - - cpu := &CpuGroup{} - actualStats := *cgroups.NewStats() - err := cpu.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - - expectedStats := cgroups.ThrottlingData{ - Periods: kNrPeriods, - ThrottledPeriods: kNrThrottled, - ThrottledTime: kThrottledTime} - - expectThrottlingDataEquals(t, expectedStats, actualStats.CpuStats.ThrottlingData) -} - -func TestNoCpuStatFile(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - cpu := &CpuGroup{} - actualStats := *cgroups.NewStats() - err := cpu.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal("Expected not to fail, but did") - } -} - -func TestInvalidCpuStat(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - cpuStatContent := `nr_periods 2000 - nr_throttled 200 - throttled_time fortytwo` - helper.writeFileContents(map[string]string{ - "cpu.stat": cpuStatContent, - }) - - cpu := &CpuGroup{} - actualStats := *cgroups.NewStats() - err := cpu.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failed stat parsing.") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset_test.go deleted file mode 100644 index 0f929151f..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// +build linux - -package fs - -import ( - "testing" -) - -func TestCpusetSetCpus(t *testing.T) { - helper := NewCgroupTestUtil("cpuset", t) - defer helper.cleanup() - - const ( - cpusBefore = "0" - cpusAfter = "1-3" - ) - - helper.writeFileContents(map[string]string{ - "cpuset.cpus": cpusBefore, - }) - - helper.CgroupData.config.Resources.CpusetCpus = cpusAfter - cpuset := &CpusetGroup{} - if err := cpuset.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "cpuset.cpus") - if err != nil { - t.Fatalf("Failed to parse cpuset.cpus - %s", err) - } - - if value != cpusAfter { - t.Fatal("Got the wrong value, set cpuset.cpus failed.") - } -} - -func TestCpusetSetMems(t *testing.T) { - helper := NewCgroupTestUtil("cpuset", t) - defer helper.cleanup() - - const ( - memsBefore = "0" - memsAfter = "1" - ) - - helper.writeFileContents(map[string]string{ - "cpuset.mems": memsBefore, - }) - - helper.CgroupData.config.Resources.CpusetMems = memsAfter - cpuset := &CpusetGroup{} - if err := cpuset.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "cpuset.mems") - if err != nil { - t.Fatalf("Failed to parse cpuset.mems - %s", err) - } - - if value != memsAfter { - t.Fatal("Got the wrong value, set cpuset.mems failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices_test.go deleted file mode 100644 index ee44084ee..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices_test.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build linux - -package fs - -import ( - "testing" - - "github.com/opencontainers/runc/libcontainer/configs" -) - -var ( - allowedDevices = []*configs.Device{ - { - Path: "/dev/zero", - Type: 'c', - Major: 1, - Minor: 5, - Permissions: "rwm", - FileMode: 0666, - }, - } - allowedList = "c 1:5 rwm" - deniedDevices = []*configs.Device{ - { - Path: "/dev/null", - Type: 'c', - Major: 1, - Minor: 3, - Permissions: "rwm", - FileMode: 0666, - }, - } - deniedList = "c 1:3 rwm" -) - -func TestDevicesSetAllow(t *testing.T) { - helper := NewCgroupTestUtil("devices", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "devices.deny": "a", - }) - - helper.CgroupData.config.Resources.AllowAllDevices = false - helper.CgroupData.config.Resources.AllowedDevices = allowedDevices - devices := &DevicesGroup{} - if err := devices.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "devices.allow") - if err != nil { - t.Fatalf("Failed to parse devices.allow - %s", err) - } - - if value != allowedList { - t.Fatal("Got the wrong value, set devices.allow failed.") - } -} - -func TestDevicesSetDeny(t *testing.T) { - helper := NewCgroupTestUtil("devices", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "devices.allow": "a", - }) - - helper.CgroupData.config.Resources.AllowAllDevices = true - helper.CgroupData.config.Resources.DeniedDevices = deniedDevices - devices := &DevicesGroup{} - if err := devices.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "devices.deny") - if err != nil { - t.Fatalf("Failed to parse devices.deny - %s", err) - } - - if value != deniedList { - t.Fatal("Got the wrong value, set devices.deny failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer_test.go deleted file mode 100644 index 77708db9a..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build linux - -package fs - -import ( - "testing" - - "github.com/opencontainers/runc/libcontainer/configs" -) - -func TestFreezerSetState(t *testing.T) { - helper := NewCgroupTestUtil("freezer", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "freezer.state": string(configs.Frozen), - }) - - helper.CgroupData.config.Resources.Freezer = configs.Thawed - freezer := &FreezerGroup{} - if err := freezer.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "freezer.state") - if err != nil { - t.Fatalf("Failed to parse freezer.state - %s", err) - } - if value != string(configs.Thawed) { - t.Fatal("Got the wrong value, set freezer.state failed.") - } -} - -func TestFreezerSetInvalidState(t *testing.T) { - helper := NewCgroupTestUtil("freezer", t) - defer helper.cleanup() - - const ( - invalidArg configs.FreezerState = "Invalid" - ) - - helper.CgroupData.config.Resources.Freezer = invalidArg - freezer := &FreezerGroup{} - if err := freezer.Set(helper.CgroupPath, helper.CgroupData.config); err == nil { - t.Fatal("Failed to return invalid argument error") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb_test.go deleted file mode 100644 index 2d41c4eb2..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// +build linux - -package fs - -import ( - "fmt" - "strconv" - "testing" - - "github.com/opencontainers/runc/libcontainer/cgroups" - "github.com/opencontainers/runc/libcontainer/configs" -) - -const ( - hugetlbUsageContents = "128\n" - hugetlbMaxUsageContents = "256\n" - hugetlbFailcnt = "100\n" -) - -var ( - usage = "hugetlb.%s.usage_in_bytes" - limit = "hugetlb.%s.limit_in_bytes" - maxUsage = "hugetlb.%s.max_usage_in_bytes" - failcnt = "hugetlb.%s.failcnt" -) - -func TestHugetlbSetHugetlb(t *testing.T) { - helper := NewCgroupTestUtil("hugetlb", t) - defer helper.cleanup() - - const ( - hugetlbBefore = 256 - hugetlbAfter = 512 - ) - - for _, pageSize := range HugePageSizes { - helper.writeFileContents(map[string]string{ - fmt.Sprintf(limit, pageSize): strconv.Itoa(hugetlbBefore), - }) - } - - for _, pageSize := range HugePageSizes { - helper.CgroupData.config.Resources.HugetlbLimit = []*configs.HugepageLimit{ - { - Pagesize: pageSize, - Limit: hugetlbAfter, - }, - } - hugetlb := &HugetlbGroup{} - if err := hugetlb.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - } - - for _, pageSize := range HugePageSizes { - limit := fmt.Sprintf(limit, pageSize) - value, err := getCgroupParamUint(helper.CgroupPath, limit) - if err != nil { - t.Fatalf("Failed to parse %s - %s", limit, err) - } - if value != hugetlbAfter { - t.Fatalf("Set hugetlb.limit_in_bytes failed. Expected: %v, Got: %v", hugetlbAfter, value) - } - } -} - -func TestHugetlbStats(t *testing.T) { - helper := NewCgroupTestUtil("hugetlb", t) - defer helper.cleanup() - for _, pageSize := range HugePageSizes { - helper.writeFileContents(map[string]string{ - fmt.Sprintf(usage, pageSize): hugetlbUsageContents, - fmt.Sprintf(maxUsage, pageSize): hugetlbMaxUsageContents, - fmt.Sprintf(failcnt, pageSize): hugetlbFailcnt, - }) - } - - hugetlb := &HugetlbGroup{} - actualStats := *cgroups.NewStats() - err := hugetlb.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - expectedStats := cgroups.HugetlbStats{Usage: 128, MaxUsage: 256, Failcnt: 100} - for _, pageSize := range HugePageSizes { - expectHugetlbStatEquals(t, expectedStats, actualStats.HugetlbStats[pageSize]) - } -} - -func TestHugetlbStatsNoUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("hugetlb", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - maxUsage: hugetlbMaxUsageContents, - }) - - hugetlb := &HugetlbGroup{} - actualStats := *cgroups.NewStats() - err := hugetlb.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestHugetlbStatsNoMaxUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("hugetlb", t) - defer helper.cleanup() - for _, pageSize := range HugePageSizes { - helper.writeFileContents(map[string]string{ - fmt.Sprintf(usage, pageSize): hugetlbUsageContents, - }) - } - - hugetlb := &HugetlbGroup{} - actualStats := *cgroups.NewStats() - err := hugetlb.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestHugetlbStatsBadUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("hugetlb", t) - defer helper.cleanup() - for _, pageSize := range HugePageSizes { - helper.writeFileContents(map[string]string{ - fmt.Sprintf(usage, pageSize): "bad", - maxUsage: hugetlbMaxUsageContents, - }) - } - - hugetlb := &HugetlbGroup{} - actualStats := *cgroups.NewStats() - err := hugetlb.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestHugetlbStatsBadMaxUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("hugetlb", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - usage: hugetlbUsageContents, - maxUsage: "bad", - }) - - hugetlb := &HugetlbGroup{} - actualStats := *cgroups.NewStats() - err := hugetlb.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory_test.go deleted file mode 100644 index 9464599b0..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory_test.go +++ /dev/null @@ -1,294 +0,0 @@ -// +build linux - -package fs - -import ( - "strconv" - "testing" - - "github.com/opencontainers/runc/libcontainer/cgroups" -) - -const ( - memoryStatContents = `cache 512 -rss 1024` - memoryUsageContents = "2048\n" - memoryMaxUsageContents = "4096\n" - memoryFailcnt = "100\n" -) - -func TestMemorySetMemory(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - memoryBefore = 314572800 // 300M - memoryAfter = 524288000 // 500M - reservationBefore = 209715200 // 200M - reservationAfter = 314572800 // 300M - ) - - helper.writeFileContents(map[string]string{ - "memory.limit_in_bytes": strconv.Itoa(memoryBefore), - "memory.soft_limit_in_bytes": strconv.Itoa(reservationBefore), - }) - - helper.CgroupData.config.Resources.Memory = memoryAfter - helper.CgroupData.config.Resources.MemoryReservation = reservationAfter - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.limit_in_bytes - %s", err) - } - if value != memoryAfter { - t.Fatal("Got the wrong value, set memory.limit_in_bytes failed.") - } - - value, err = getCgroupParamUint(helper.CgroupPath, "memory.soft_limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.soft_limit_in_bytes - %s", err) - } - if value != reservationAfter { - t.Fatal("Got the wrong value, set memory.soft_limit_in_bytes failed.") - } -} - -func TestMemorySetMemoryswap(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - memoryswapBefore = 314572800 // 300M - memoryswapAfter = 524288000 // 500M - ) - - helper.writeFileContents(map[string]string{ - "memory.memsw.limit_in_bytes": strconv.Itoa(memoryswapBefore), - }) - - helper.CgroupData.config.Resources.MemorySwap = memoryswapAfter - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.memsw.limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.memsw.limit_in_bytes - %s", err) - } - if value != memoryswapAfter { - t.Fatal("Got the wrong value, set memory.memsw.limit_in_bytes failed.") - } -} - -func TestMemorySetKernelMemory(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - kernelMemoryBefore = 314572800 // 300M - kernelMemoryAfter = 524288000 // 500M - ) - - helper.writeFileContents(map[string]string{ - "memory.kmem.limit_in_bytes": strconv.Itoa(kernelMemoryBefore), - }) - - helper.CgroupData.config.Resources.KernelMemory = kernelMemoryAfter - memory := &MemoryGroup{} - if err := memory.SetKernelMemory(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.kmem.limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.kmem.limit_in_bytes - %s", err) - } - if value != kernelMemoryAfter { - t.Fatal("Got the wrong value, set memory.kmem.limit_in_bytes failed.") - } -} - -func TestMemorySetMemorySwappinessDefault(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - swappinessBefore = 60 //deafult is 60 - swappinessAfter = 0 - ) - - helper.writeFileContents(map[string]string{ - "memory.swappiness": strconv.Itoa(swappinessBefore), - }) - - helper.CgroupData.config.Resources.Memory = swappinessAfter - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.swappiness") - if err != nil { - t.Fatalf("Failed to parse memory.swappiness - %s", err) - } - if value != swappinessAfter { - t.Fatal("Got the wrong value, set memory.swappiness failed.") - } -} - -func TestMemoryStats(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - "memory.failcnt": memoryFailcnt, - "memory.memsw.usage_in_bytes": memoryUsageContents, - "memory.memsw.max_usage_in_bytes": memoryMaxUsageContents, - "memory.memsw.failcnt": memoryFailcnt, - "memory.kmem.usage_in_bytes": memoryUsageContents, - "memory.kmem.max_usage_in_bytes": memoryMaxUsageContents, - "memory.kmem.failcnt": memoryFailcnt, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - expectedStats := cgroups.MemoryStats{Cache: 512, Usage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100}, SwapUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100}, KernelUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100}, Stats: map[string]uint64{"cache": 512, "rss": 1024}} - expectMemoryStatEquals(t, expectedStats, actualStats.MemoryStats) -} - -func TestMemoryStatsNoStatFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } -} - -func TestMemoryStatsNoUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsNoMaxUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": memoryUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsBadStatFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": "rss rss", - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsBadUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": "bad", - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsBadMaxUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": "bad", - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemorySetOomControl(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - oom_kill_disable = 1 // disable oom killer, default is 0 - ) - - helper.writeFileContents(map[string]string{ - "memory.oom_control": strconv.Itoa(oom_kill_disable), - }) - - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.oom_control") - if err != nil { - t.Fatalf("Failed to parse memory.oom_control - %s", err) - } - - if value != oom_kill_disable { - t.Fatalf("Got the wrong value, set memory.oom_control failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls_test.go deleted file mode 100644 index 974bd9d88..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build linux - -package fs - -import ( - "testing" -) - -const ( - classidBefore = "0x100002" - classidAfter = "0x100001" -) - -func TestNetClsSetClassid(t *testing.T) { - helper := NewCgroupTestUtil("net_cls", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "net_cls.classid": classidBefore, - }) - - helper.CgroupData.config.Resources.NetClsClassid = classidAfter - netcls := &NetClsGroup{} - if err := netcls.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - // As we are in mock environment, we can't get correct value of classid from - // net_cls.classid. - // So. we just judge if we successfully write classid into file - value, err := getCgroupParamString(helper.CgroupPath, "net_cls.classid") - if err != nil { - t.Fatalf("Failed to parse net_cls.classid - %s", err) - } - if value != classidAfter { - t.Fatal("Got the wrong value, set net_cls.classid failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio_test.go deleted file mode 100644 index efbf0639a..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build linux - -package fs - -import ( - "strings" - "testing" - - "github.com/opencontainers/runc/libcontainer/configs" -) - -var ( - prioMap = []*configs.IfPrioMap{ - { - Interface: "test", - Priority: 5, - }, - } -) - -func TestNetPrioSetIfPrio(t *testing.T) { - helper := NewCgroupTestUtil("net_prio", t) - defer helper.cleanup() - - helper.CgroupData.config.Resources.NetPrioIfpriomap = prioMap - netPrio := &NetPrioGroup{} - if err := netPrio.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "net_prio.ifpriomap") - if err != nil { - t.Fatalf("Failed to parse net_prio.ifpriomap - %s", err) - } - if !strings.Contains(value, "test 5") { - t.Fatal("Got the wrong value, set net_prio.ifpriomap failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids_test.go deleted file mode 100644 index 06b11927a..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// +build linux - -package fs - -import ( - "strconv" - "testing" - - "github.com/opencontainers/runc/libcontainer/cgroups" -) - -const ( - maxUnlimited = -1 - maxLimited = 1024 -) - -func TestPidsSetMax(t *testing.T) { - helper := NewCgroupTestUtil("pids", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "pids.max": "max", - }) - - helper.CgroupData.config.Resources.PidsLimit = maxLimited - pids := &PidsGroup{} - if err := pids.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "pids.max") - if err != nil { - t.Fatalf("Failed to parse pids.max - %s", err) - } - - if value != maxLimited { - t.Fatalf("Expected %d, got %d for setting pids.max - limited", maxLimited, value) - } -} - -func TestPidsSetUnlimited(t *testing.T) { - helper := NewCgroupTestUtil("pids", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "pids.max": strconv.Itoa(maxLimited), - }) - - helper.CgroupData.config.Resources.PidsLimit = maxUnlimited - pids := &PidsGroup{} - if err := pids.Set(helper.CgroupPath, helper.CgroupData.config); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "pids.max") - if err != nil { - t.Fatalf("Failed to parse pids.max - %s", err) - } - - if value != "max" { - t.Fatalf("Expected %s, got %s for setting pids.max - unlimited", "max", value) - } -} - -func TestPidsStats(t *testing.T) { - helper := NewCgroupTestUtil("pids", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "pids.current": strconv.Itoa(1337), - "pids.max": strconv.Itoa(maxLimited), - }) - - pids := &PidsGroup{} - stats := *cgroups.NewStats() - if err := pids.GetStats(helper.CgroupPath, &stats); err != nil { - t.Fatal(err) - } - - if stats.PidsStats.Current != 1337 { - t.Fatalf("Expected %d, got %d for pids.current", 1337, stats.PidsStats.Current) - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/stats_util_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/stats_util_test.go deleted file mode 100644 index b1777cc0a..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/stats_util_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// +build linux - -package fs - -import ( - "fmt" - "testing" - - "github.com/Sirupsen/logrus" - "github.com/opencontainers/runc/libcontainer/cgroups" -) - -func blkioStatEntryEquals(expected, actual []cgroups.BlkioStatEntry) error { - if len(expected) != len(actual) { - return fmt.Errorf("blkioStatEntries length do not match") - } - for i, expValue := range expected { - actValue := actual[i] - if expValue != actValue { - return fmt.Errorf("Expected blkio stat entry %v but found %v", expValue, actValue) - } - } - return nil -} - -func expectBlkioStatsEquals(t *testing.T, expected, actual cgroups.BlkioStats) { - if err := blkioStatEntryEquals(expected.IoServiceBytesRecursive, actual.IoServiceBytesRecursive); err != nil { - logrus.Printf("blkio IoServiceBytesRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoServicedRecursive, actual.IoServicedRecursive); err != nil { - logrus.Printf("blkio IoServicedRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoQueuedRecursive, actual.IoQueuedRecursive); err != nil { - logrus.Printf("blkio IoQueuedRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.SectorsRecursive, actual.SectorsRecursive); err != nil { - logrus.Printf("blkio SectorsRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoServiceTimeRecursive, actual.IoServiceTimeRecursive); err != nil { - logrus.Printf("blkio IoServiceTimeRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoWaitTimeRecursive, actual.IoWaitTimeRecursive); err != nil { - logrus.Printf("blkio IoWaitTimeRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoMergedRecursive, actual.IoMergedRecursive); err != nil { - logrus.Printf("blkio IoMergedRecursive do not match - %v vs %v\n", expected.IoMergedRecursive, actual.IoMergedRecursive) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoTimeRecursive, actual.IoTimeRecursive); err != nil { - logrus.Printf("blkio IoTimeRecursive do not match - %s\n", err) - t.Fail() - } -} - -func expectThrottlingDataEquals(t *testing.T, expected, actual cgroups.ThrottlingData) { - if expected != actual { - logrus.Printf("Expected throttling data %v but found %v\n", expected, actual) - t.Fail() - } -} - -func expectHugetlbStatEquals(t *testing.T, expected, actual cgroups.HugetlbStats) { - if expected != actual { - logrus.Printf("Expected hugetlb stats %v but found %v\n", expected, actual) - t.Fail() - } -} - -func expectMemoryStatEquals(t *testing.T, expected, actual cgroups.MemoryStats) { - expectMemoryDataEquals(t, expected.Usage, actual.Usage) - expectMemoryDataEquals(t, expected.SwapUsage, actual.SwapUsage) - expectMemoryDataEquals(t, expected.KernelUsage, actual.KernelUsage) - - for key, expValue := range expected.Stats { - actValue, ok := actual.Stats[key] - if !ok { - logrus.Printf("Expected memory stat key %s not found\n", key) - t.Fail() - } - if expValue != actValue { - logrus.Printf("Expected memory stat value %d but found %d\n", expValue, actValue) - t.Fail() - } - } -} - -func expectMemoryDataEquals(t *testing.T, expected, actual cgroups.MemoryData) { - if expected.Usage != actual.Usage { - logrus.Printf("Expected memory usage %d but found %d\n", expected.Usage, actual.Usage) - t.Fail() - } - if expected.MaxUsage != actual.MaxUsage { - logrus.Printf("Expected memory max usage %d but found %d\n", expected.MaxUsage, actual.MaxUsage) - t.Fail() - } - if expected.Failcnt != actual.Failcnt { - logrus.Printf("Expected memory failcnt %d but found %d\n", expected.Failcnt, actual.Failcnt) - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/util_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/util_test.go deleted file mode 100644 index 7067e799f..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/util_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// +build linux - -/* -Utility for testing cgroup operations. - -Creates a mock of the cgroup filesystem for the duration of the test. -*/ -package fs - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/opencontainers/runc/libcontainer/configs" -) - -type cgroupTestUtil struct { - // cgroup data to use in tests. - CgroupData *cgroupData - - // Path to the mock cgroup directory. - CgroupPath string - - // Temporary directory to store mock cgroup filesystem. - tempDir string - t *testing.T -} - -// Creates a new test util for the specified subsystem -func NewCgroupTestUtil(subsystem string, t *testing.T) *cgroupTestUtil { - d := &cgroupData{ - config: &configs.Cgroup{}, - } - d.config.Resources = &configs.Resources{} - tempDir, err := ioutil.TempDir("", "cgroup_test") - if err != nil { - t.Fatal(err) - } - d.root = tempDir - testCgroupPath := filepath.Join(d.root, subsystem) - if err != nil { - t.Fatal(err) - } - - // Ensure the full mock cgroup path exists. - err = os.MkdirAll(testCgroupPath, 0755) - if err != nil { - t.Fatal(err) - } - return &cgroupTestUtil{CgroupData: d, CgroupPath: testCgroupPath, tempDir: tempDir, t: t} -} - -func (c *cgroupTestUtil) cleanup() { - os.RemoveAll(c.tempDir) -} - -// Write the specified contents on the mock of the specified cgroup files. -func (c *cgroupTestUtil) writeFileContents(fileContents map[string]string) { - for file, contents := range fileContents { - err := writeFile(c.CgroupPath, file, contents) - if err != nil { - c.t.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils_test.go deleted file mode 100644 index 99cdc18e0..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// +build linux - -package fs - -import ( - "io/ioutil" - "math" - "os" - "path/filepath" - "strconv" - "testing" -) - -const ( - cgroupFile = "cgroup.file" - floatValue = 2048.0 - floatString = "2048" -) - -func TestGetCgroupParamsInt(t *testing.T) { - // Setup tempdir. - tempDir, err := ioutil.TempDir("", "cgroup_utils_test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempDir) - tempFile := filepath.Join(tempDir, cgroupFile) - - // Success. - err = ioutil.WriteFile(tempFile, []byte(floatString), 0755) - if err != nil { - t.Fatal(err) - } - value, err := getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != floatValue { - t.Fatalf("Expected %d to equal %f", value, floatValue) - } - - // Success with new line. - err = ioutil.WriteFile(tempFile, []byte(floatString+"\n"), 0755) - if err != nil { - t.Fatal(err) - } - value, err = getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != floatValue { - t.Fatalf("Expected %d to equal %f", value, floatValue) - } - - // Success with negative values - err = ioutil.WriteFile(tempFile, []byte("-12345"), 0755) - if err != nil { - t.Fatal(err) - } - value, err = getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != 0 { - t.Fatalf("Expected %d to equal %d", value, 0) - } - - // Success with negative values lesser than min int64 - s := strconv.FormatFloat(math.MinInt64, 'f', -1, 64) - err = ioutil.WriteFile(tempFile, []byte(s), 0755) - if err != nil { - t.Fatal(err) - } - value, err = getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != 0 { - t.Fatalf("Expected %d to equal %d", value, 0) - } - - // Not a float. - err = ioutil.WriteFile(tempFile, []byte("not-a-float"), 0755) - if err != nil { - t.Fatal(err) - } - _, err = getCgroupParamUint(tempDir, cgroupFile) - if err == nil { - t.Fatal("Expecting error, got none") - } - - // Unknown file. - err = os.Remove(tempFile) - if err != nil { - t.Fatal(err) - } - _, err = getCgroupParamUint(tempDir, cgroupFile) - if err == nil { - t.Fatal("Expecting error, got none") - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go deleted file mode 100644 index 7de9ae605..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go +++ /dev/null @@ -1,55 +0,0 @@ -// +build !linux - -package systemd - -import ( - "fmt" - - "github.com/opencontainers/runc/libcontainer/cgroups" - "github.com/opencontainers/runc/libcontainer/configs" -) - -type Manager struct { - Cgroups *configs.Cgroup - Paths map[string]string -} - -func UseSystemd() bool { - return false -} - -func (m *Manager) Apply(pid int) error { - return fmt.Errorf("Systemd not supported") -} - -func (m *Manager) GetPids() ([]int, error) { - return nil, fmt.Errorf("Systemd not supported") -} - -func (m *Manager) GetAllPids() ([]int, error) { - return nil, fmt.Errorf("Systemd not supported") -} - -func (m *Manager) Destroy() error { - return fmt.Errorf("Systemd not supported") -} - -func (m *Manager) GetPaths() map[string]string { - return nil -} - -func (m *Manager) GetStats() (*cgroups.Stats, error) { - return nil, fmt.Errorf("Systemd not supported") -} - -func (m *Manager) Set(container *configs.Config) error { - return nil, fmt.Errorf("Systemd not supported") -} - -func (m *Manager) Freeze(state configs.FreezerState) error { - return fmt.Errorf("Systemd not supported") -} - -func Freeze(c *configs.Cgroup, state configs.FreezerState) error { - return fmt.Errorf("Systemd not supported") -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go deleted file mode 100644 index db020a971..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go +++ /dev/null @@ -1,596 +0,0 @@ -// +build linux - -package systemd - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "strings" - "sync" - "time" - - systemdDbus "github.com/coreos/go-systemd/dbus" - systemdUtil "github.com/coreos/go-systemd/util" - "github.com/godbus/dbus" - "github.com/opencontainers/runc/libcontainer/cgroups" - "github.com/opencontainers/runc/libcontainer/cgroups/fs" - "github.com/opencontainers/runc/libcontainer/configs" -) - -type Manager struct { - mu sync.Mutex - Cgroups *configs.Cgroup - Paths map[string]string -} - -type subsystem interface { - // Name returns the name of the subsystem. - Name() string - // Returns the stats, as 'stats', corresponding to the cgroup under 'path'. - GetStats(path string, stats *cgroups.Stats) error - // Set the cgroup represented by cgroup. - Set(path string, cgroup *configs.Cgroup) error -} - -var errSubsystemDoesNotExist = errors.New("cgroup: subsystem does not exist") - -type subsystemSet []subsystem - -func (s subsystemSet) Get(name string) (subsystem, error) { - for _, ss := range s { - if ss.Name() == name { - return ss, nil - } - } - return nil, errSubsystemDoesNotExist -} - -var subsystems = subsystemSet{ - &fs.CpusetGroup{}, - &fs.DevicesGroup{}, - &fs.MemoryGroup{}, - &fs.CpuGroup{}, - &fs.CpuacctGroup{}, - &fs.PidsGroup{}, - &fs.BlkioGroup{}, - &fs.HugetlbGroup{}, - &fs.PerfEventGroup{}, - &fs.FreezerGroup{}, - &fs.NetPrioGroup{}, - &fs.NetClsGroup{}, - &fs.NameGroup{GroupName: "name=systemd"}, -} - -const ( - testScopeWait = 4 -) - -var ( - connLock sync.Mutex - theConn *systemdDbus.Conn - hasStartTransientUnit bool - hasTransientDefaultDependencies bool -) - -func newProp(name string, units interface{}) systemdDbus.Property { - return systemdDbus.Property{ - Name: name, - Value: dbus.MakeVariant(units), - } -} - -func UseSystemd() bool { - if !systemdUtil.IsRunningSystemd() { - return false - } - - connLock.Lock() - defer connLock.Unlock() - - if theConn == nil { - var err error - theConn, err = systemdDbus.New() - if err != nil { - return false - } - - // Assume we have StartTransientUnit - hasStartTransientUnit = true - - // But if we get UnknownMethod error we don't - if _, err := theConn.StartTransientUnit("test.scope", "invalid", nil, nil); err != nil { - if dbusError, ok := err.(dbus.Error); ok { - if dbusError.Name == "org.freedesktop.DBus.Error.UnknownMethod" { - hasStartTransientUnit = false - return hasStartTransientUnit - } - } - } - - // Ensure the scope name we use doesn't exist. Use the Pid to - // avoid collisions between multiple libcontainer users on a - // single host. - scope := fmt.Sprintf("libcontainer-%d-systemd-test-default-dependencies.scope", os.Getpid()) - testScopeExists := true - for i := 0; i <= testScopeWait; i++ { - if _, err := theConn.StopUnit(scope, "replace", nil); err != nil { - if dbusError, ok := err.(dbus.Error); ok { - if strings.Contains(dbusError.Name, "org.freedesktop.systemd1.NoSuchUnit") { - testScopeExists = false - break - } - } - } - time.Sleep(time.Millisecond) - } - - // Bail out if we can't kill this scope without testing for DefaultDependencies - if testScopeExists { - return hasStartTransientUnit - } - - // Assume StartTransientUnit on a scope allows DefaultDependencies - hasTransientDefaultDependencies = true - ddf := newProp("DefaultDependencies", false) - if _, err := theConn.StartTransientUnit(scope, "replace", []systemdDbus.Property{ddf}, nil); err != nil { - if dbusError, ok := err.(dbus.Error); ok { - if strings.Contains(dbusError.Name, "org.freedesktop.DBus.Error.PropertyReadOnly") { - hasTransientDefaultDependencies = false - } - } - } - - // Not critical because of the stop unit logic above. - theConn.StopUnit(scope, "replace", nil) - } - 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 - unitName = getUnitName(c) - slice = "system.slice" - properties []systemdDbus.Property - ) - - if c.Paths != nil { - paths := make(map[string]string) - for name, path := range c.Paths { - _, err := getSubsystemPath(m.Cgroups, name) - if err != nil { - // Don't fail if a cgroup hierarchy was not found, just skip this subsystem - if cgroups.IsNotFound(err) { - continue - } - return err - } - paths[name] = path - } - m.Paths = paths - return cgroups.EnterPid(m.Paths, pid) - } - - if c.Parent != "" { - slice = c.Parent - } - - properties = append(properties, - systemdDbus.PropSlice(slice), - systemdDbus.PropDescription("docker container "+c.Name), - newProp("PIDs", []uint32{uint32(pid)}), - ) - - // Always enable accounting, this gets us the same behaviour as the fs implementation, - // plus the kernel has some problems with joining the memory cgroup at a later time. - properties = append(properties, - newProp("MemoryAccounting", true), - newProp("CPUAccounting", true), - newProp("BlockIOAccounting", true)) - - if hasTransientDefaultDependencies { - properties = append(properties, - newProp("DefaultDependencies", false)) - } - - if c.Resources.Memory != 0 { - properties = append(properties, - newProp("MemoryLimit", uint64(c.Resources.Memory))) - } - - if c.Resources.CpuShares != 0 { - properties = append(properties, - newProp("CPUShares", uint64(c.Resources.CpuShares))) - } - - if c.Resources.BlkioWeight != 0 { - properties = append(properties, - newProp("BlockIOWeight", uint64(c.Resources.BlkioWeight))) - } - - // We need to set kernel memory before processes join cgroup because - // kmem.limit_in_bytes can only be set when the cgroup is empty. - // And swap memory limit needs to be set after memory limit, only - // memory limit is handled by systemd, so it's kind of ugly here. - if c.Resources.KernelMemory > 0 { - if err := setKernelMemory(c); err != nil { - return err - } - } - - if _, err := theConn.StartTransientUnit(unitName, "replace", properties, nil); err != nil { - 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 { - return err - } - - paths := make(map[string]string) - for _, s := range subsystems { - subsystemPath, err := getSubsystemPath(m.Cgroups, s.Name()) - if err != nil { - // Don't fail if a cgroup hierarchy was not found, just skip this subsystem - if cgroups.IsNotFound(err) { - continue - } - return err - } - paths[s.Name()] = subsystemPath - } - m.Paths = paths - return nil -} - -func (m *Manager) Destroy() error { - if m.Cgroups.Paths != nil { - return nil - } - m.mu.Lock() - defer m.mu.Unlock() - theConn.StopUnit(getUnitName(m.Cgroups), "replace", nil) - if err := cgroups.RemovePaths(m.Paths); err != nil { - return err - } - m.Paths = make(map[string]string) - return nil -} - -func (m *Manager) GetPaths() map[string]string { - m.mu.Lock() - paths := m.Paths - m.mu.Unlock() - return paths -} - -func writeFile(dir, file, data string) error { - // Normally dir should not be empty, one case is that cgroup subsystem - // is not mounted, we will get empty dir, and we want it fail here. - if dir == "" { - return fmt.Errorf("no such directory for %s.", file) - } - return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700) -} - -func join(c *configs.Cgroup, subsystem string, pid int) (string, error) { - path, err := getSubsystemPath(c, subsystem) - if err != nil { - return "", err - } - if err := os.MkdirAll(path, 0755); err != nil { - return "", err - } - if err := writeFile(path, "cgroup.procs", strconv.Itoa(pid)); err != nil { - return "", err - } - - 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 - } - 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 -} - -// systemd represents slice heirarchy using `-`, so we need to follow suit when -// generating the path of slice. Essentially, test-a-b.slice becomes -// test.slice/test-a.slice/test-a-b.slice. -func expandSlice(slice string) (string, error) { - suffix := ".slice" - sliceName := strings.TrimSuffix(slice, suffix) - - var path, prefix string - for _, component := range strings.Split(sliceName, "-") { - // test--a.slice isn't permitted, nor is -test.slice. - if component == "" { - return "", fmt.Errorf("invalid slice name: %s", slice) - } - - // Append the component to the path and to the prefix. - path += prefix + component + suffix + "/" - prefix += component + "-" - } - - return path, nil -} - -func getSubsystemPath(c *configs.Cgroup, subsystem string) (string, error) { - mountpoint, err := cgroups.FindCgroupMountpoint(subsystem) - if err != nil { - return "", err - } - - initPath, err := cgroups.GetInitCgroupDir(subsystem) - if err != nil { - return "", err - } - - slice := "system.slice" - if c.Parent != "" { - slice = c.Parent - } - - slice, err = expandSlice(slice) - if err != nil { - return "", err - } - - return filepath.Join(mountpoint, initPath, slice, getUnitName(c)), nil -} - -func (m *Manager) Freeze(state configs.FreezerState) error { - path, err := getSubsystemPath(m.Cgroups, "freezer") - if err != nil { - return err - } - prevState := m.Cgroups.Resources.Freezer - m.Cgroups.Resources.Freezer = state - freezer, err := subsystems.Get("freezer") - if err != nil { - return err - } - err = freezer.Set(path, m.Cgroups) - if err != nil { - m.Cgroups.Resources.Freezer = prevState - return err - } - return nil -} - -func (m *Manager) GetPids() ([]int, error) { - path, err := getSubsystemPath(m.Cgroups, "devices") - if err != nil { - return nil, err - } - return cgroups.GetPids(path) -} - -func (m *Manager) GetAllPids() ([]int, error) { - path, err := getSubsystemPath(m.Cgroups, "devices") - if err != nil { - return nil, err - } - return cgroups.GetAllPids(path) -} - -func (m *Manager) GetStats() (*cgroups.Stats, error) { - m.mu.Lock() - defer m.mu.Unlock() - stats := cgroups.NewStats() - for name, path := range m.Paths { - sys, err := subsystems.Get(name) - if err == errSubsystemDoesNotExist || !cgroups.PathExists(path) { - continue - } - if err := sys.GetStats(path, stats); err != nil { - return nil, err - } - } - - return stats, nil -} - -func (m *Manager) Set(container *configs.Config) error { - for _, sys := range subsystems { - // Get the subsystem path, but don't error out for not found cgroups. - path, err := getSubsystemPath(container.Cgroups, sys.Name()) - if err != nil && !cgroups.IsNotFound(err) { - return err - } - - if err := sys.Set(path, container.Cgroups); err != nil { - return err - } - } - - if m.Paths["cpu"] != "" { - if err := fs.CheckCpushares(m.Paths["cpu"], container.Cgroups.Resources.CpuShares); err != nil { - return err - } - } - return nil -} - -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) { - return err - } - - if err := os.MkdirAll(path, 0755); err != nil { - return err - } - - // This doesn't get called by manager.Set, so we need to do it here. - 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/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/config_unix_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/config_unix_test.go deleted file mode 100644 index 27d07d4e8..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/config_unix_test.go +++ /dev/null @@ -1,156 +0,0 @@ -// +build linux freebsd - -package configs - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "testing" -) - -// Checks whether the expected capability is specified in the capabilities. -func contains(expected string, values []string) bool { - for _, v := range values { - if v == expected { - return true - } - } - return false -} - -func containsDevice(expected *Device, values []*Device) bool { - for _, d := range values { - if d.Path == expected.Path && - d.Permissions == expected.Permissions && - d.FileMode == expected.FileMode && - d.Major == expected.Major && - d.Minor == expected.Minor && - d.Type == expected.Type { - return true - } - } - return false -} - -func loadConfig(name string) (*Config, error) { - f, err := os.Open(filepath.Join("../sample_configs", name)) - if err != nil { - return nil, err - } - defer f.Close() - - var container *Config - if err := json.NewDecoder(f).Decode(&container); err != nil { - return nil, err - } - - // Check that a config doesn't contain extra fields - var configMap, abstractMap map[string]interface{} - - if _, err := f.Seek(0, 0); err != nil { - return nil, err - } - - if err := json.NewDecoder(f).Decode(&abstractMap); err != nil { - return nil, err - } - - configData, err := json.Marshal(&container) - if err != nil { - return nil, err - } - - if err := json.Unmarshal(configData, &configMap); err != nil { - return nil, err - } - - for k := range configMap { - delete(abstractMap, k) - } - - if len(abstractMap) != 0 { - return nil, fmt.Errorf("unknown fields: %s", abstractMap) - } - - return container, nil -} - -func TestRemoveNamespace(t *testing.T) { - ns := Namespaces{ - {Type: NEWNET}, - } - if !ns.Remove(NEWNET) { - t.Fatal("NEWNET was not removed") - } - if len(ns) != 0 { - t.Fatalf("namespaces should have 0 items but reports %d", len(ns)) - } -} - -func TestHostUIDNoUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{}, - } - uid, err := config.HostUID() - if err != nil { - t.Fatal(err) - } - if uid != 0 { - t.Fatalf("expected uid 0 with no USERNS but received %d", uid) - } -} - -func TestHostUIDWithUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{{Type: NEWUSER}}, - UidMappings: []IDMap{ - { - ContainerID: 0, - HostID: 1000, - Size: 1, - }, - }, - } - uid, err := config.HostUID() - if err != nil { - t.Fatal(err) - } - if uid != 1000 { - t.Fatalf("expected uid 1000 with no USERNS but received %d", uid) - } -} - -func TestHostGIDNoUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{}, - } - uid, err := config.HostGID() - if err != nil { - t.Fatal(err) - } - if uid != 0 { - t.Fatalf("expected gid 0 with no USERNS but received %d", uid) - } -} - -func TestHostGIDWithUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{{Type: NEWUSER}}, - GidMappings: []IDMap{ - { - ContainerID: 0, - HostID: 1000, - Size: 1, - }, - }, - } - uid, err := config.HostGID() - if err != nil { - t.Fatal(err) - } - if uid != 1000 { - t.Fatalf("expected gid 1000 with no USERNS but received %d", uid) - } -} diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/config_windows_test.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/config_windows_test.go deleted file mode 100644 index 1a0c8fa2d..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/config_windows_test.go +++ /dev/null @@ -1,3 +0,0 @@ -package configs - -// All current tests are for Unix-specific functionality diff --git a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/validate/config.go b/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/validate/config.go deleted file mode 100644 index 848a67c34..000000000 --- a/Godeps/_workspace/src/github.com/opencontainers/runc/libcontainer/configs/validate/config.go +++ /dev/null @@ -1,93 +0,0 @@ -package validate - -import ( - "fmt" - "os" - "path/filepath" - - "github.com/opencontainers/runc/libcontainer/configs" -) - -type Validator interface { - Validate(*configs.Config) error -} - -func New() Validator { - return &ConfigValidator{} -} - -type ConfigValidator struct { -} - -func (v *ConfigValidator) Validate(config *configs.Config) error { - if err := v.rootfs(config); err != nil { - return err - } - if err := v.network(config); err != nil { - return err - } - if err := v.hostname(config); err != nil { - return err - } - if err := v.security(config); err != nil { - return err - } - if err := v.usernamespace(config); err != nil { - return err - } - return nil -} - -// rootfs validates the 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) - if err != nil { - return err - } - if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil { - return err - } - if config.Rootfs != cleaned { - return fmt.Errorf("%s is not an absolute path or is a symlink", config.Rootfs) - } - return nil -} - -func (v *ConfigValidator) network(config *configs.Config) error { - if !config.Namespaces.Contains(configs.NEWNET) { - if len(config.Networks) > 0 || len(config.Routes) > 0 { - return fmt.Errorf("unable to apply network settings without a private NET namespace") - } - } - return nil -} - -func (v *ConfigValidator) hostname(config *configs.Config) error { - if config.Hostname != "" && !config.Namespaces.Contains(configs.NEWUTS) { - return fmt.Errorf("unable to set hostname without a private UTS namespace") - } - return nil -} - -func (v *ConfigValidator) security(config *configs.Config) error { - // restrict sys without mount namespace - if (len(config.MaskPaths) > 0 || len(config.ReadonlyPaths) > 0) && - !config.Namespaces.Contains(configs.NEWNS) { - return fmt.Errorf("unable to restrict sys entries without a private MNT namespace") - } - return nil -} - -func (v *ConfigValidator) usernamespace(config *configs.Config) error { - if config.Namespaces.Contains(configs.NEWUSER) { - if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) { - return fmt.Errorf("USER namespaces aren't enabled in the kernel") - } - } else { - if config.UidMappings != nil || config.GidMappings != nil { - return fmt.Errorf("User namespace mappings specified, but USER namespace isn't enabled in the config") - } - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go deleted file mode 100644 index b5eae0924..000000000 --- a/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/json" - "reflect" - "testing" -) - -var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - -func TestJSON(t *testing.T) { - type S struct { - ID1 UUID - ID2 UUID - } - s1 := S{ID1: testUUID} - data, err := json.Marshal(&s1) - if err != nil { - t.Fatal(err) - } - var s2 S - if err := json.Unmarshal(data, &s2); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(&s1, &s2) { - t.Errorf("got %#v, want %#v", s2, s1) - } -} diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go deleted file mode 100644 index 3b3d1430d..000000000 --- a/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "flag" - "runtime" - "testing" - "time" -) - -// This test is only run when --regressions is passed on the go test line. -var regressions = flag.Bool("regressions", false, "run uuid regression tests") - -// TestClockSeqRace tests for a particular race condition of returning two -// identical Version1 UUIDs. The duration of 1 minute was chosen as the race -// condition, before being fixed, nearly always occured in under 30 seconds. -func TestClockSeqRace(t *testing.T) { - if !*regressions { - t.Skip("skipping regression tests") - } - duration := time.Minute - - done := make(chan struct{}) - defer close(done) - - ch := make(chan UUID, 10000) - ncpu := runtime.NumCPU() - switch ncpu { - case 0, 1: - // We can't run the test effectively. - t.Skip("skipping race test, only one CPU detected") - return - default: - runtime.GOMAXPROCS(ncpu) - } - for i := 0; i < ncpu; i++ { - go func() { - for { - select { - case <-done: - return - case ch <- NewUUID(): - } - } - }() - } - - uuids := make(map[string]bool) - cnt := 0 - start := time.Now() - for u := range ch { - s := u.String() - if uuids[s] { - t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s) - return - } - uuids[s] = true - if time.Since(start) > duration { - return - } - cnt++ - } -} diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go deleted file mode 100644 index 417ebeb26..000000000 --- a/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" - "time" -) - -type test struct { - in string - version Version - variant Variant - isuuid bool -} - -var tests = []test{ - {"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true}, - {"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true}, - {"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true}, - {"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true}, - {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true}, - {"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true}, - {"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true}, - {"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true}, - {"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true}, - {"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true}, - {"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true}, - {"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true}, - {"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true}, - {"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true}, - {"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true}, - - {"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true}, - {"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true}, - {"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true}, - {"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true}, - - {"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false}, - {"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false}, -} - -var constants = []struct { - c interface{} - name string -}{ - {Person, "Person"}, - {Group, "Group"}, - {Org, "Org"}, - {Invalid, "Invalid"}, - {RFC4122, "RFC4122"}, - {Reserved, "Reserved"}, - {Microsoft, "Microsoft"}, - {Future, "Future"}, - {Domain(17), "Domain17"}, - {Variant(42), "BadVariant42"}, -} - -func testTest(t *testing.T, in string, tt test) { - uuid := Parse(in) - if ok := (uuid != nil); ok != tt.isuuid { - t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid) - } - if uuid == nil { - return - } - - if v := uuid.Variant(); v != tt.variant { - t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant) - } - if v, _ := uuid.Version(); v != tt.version { - t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version) - } -} - -func TestUUID(t *testing.T) { - for _, tt := range tests { - testTest(t, tt.in, tt) - testTest(t, strings.ToUpper(tt.in), tt) - } -} - -func TestConstants(t *testing.T) { - for x, tt := range constants { - v, ok := tt.c.(fmt.Stringer) - if !ok { - t.Errorf("%x: %v: not a stringer", x, v) - } else if s := v.String(); s != tt.name { - v, _ := tt.c.(int) - t.Errorf("%x: Constant %T:%d gives %q, expected %q\n", x, tt.c, v, s, tt.name) - } - } -} - -func TestRandomUUID(t *testing.T) { - m := make(map[string]bool) - for x := 1; x < 32; x++ { - uuid := NewRandom() - s := uuid.String() - if m[s] { - t.Errorf("NewRandom returned duplicated UUID %s\n", s) - } - m[s] = true - if v, _ := uuid.Version(); v != 4 { - t.Errorf("Random UUID of version %s\n", v) - } - if uuid.Variant() != RFC4122 { - t.Errorf("Random UUID is variant %d\n", uuid.Variant()) - } - } -} - -func TestNew(t *testing.T) { - m := make(map[string]bool) - for x := 1; x < 32; x++ { - s := New() - if m[s] { - t.Errorf("New returned duplicated UUID %s\n", s) - } - m[s] = true - uuid := Parse(s) - if uuid == nil { - t.Errorf("New returned %q which does not decode\n", s) - continue - } - if v, _ := uuid.Version(); v != 4 { - t.Errorf("Random UUID of version %s\n", v) - } - if uuid.Variant() != RFC4122 { - t.Errorf("Random UUID is variant %d\n", uuid.Variant()) - } - } -} - -func clockSeq(t *testing.T, uuid UUID) int { - seq, ok := uuid.ClockSequence() - if !ok { - t.Fatalf("%s: invalid clock sequence\n", uuid) - } - return seq -} - -func TestClockSeq(t *testing.T) { - // Fake time.Now for this test to return a monotonically advancing time; restore it at end. - defer func(orig func() time.Time) { timeNow = orig }(timeNow) - monTime := time.Now() - timeNow = func() time.Time { - monTime = monTime.Add(1 * time.Second) - return monTime - } - - SetClockSequence(-1) - uuid1 := NewUUID() - uuid2 := NewUUID() - - if clockSeq(t, uuid1) != clockSeq(t, uuid2) { - t.Errorf("clock sequence %d != %d\n", clockSeq(t, uuid1), clockSeq(t, uuid2)) - } - - SetClockSequence(-1) - uuid2 = NewUUID() - - // Just on the very off chance we generated the same sequence - // two times we try again. - if clockSeq(t, uuid1) == clockSeq(t, uuid2) { - SetClockSequence(-1) - uuid2 = NewUUID() - } - if clockSeq(t, uuid1) == clockSeq(t, uuid2) { - t.Errorf("Duplicate clock sequence %d\n", clockSeq(t, uuid1)) - } - - SetClockSequence(0x1234) - uuid1 = NewUUID() - if seq := clockSeq(t, uuid1); seq != 0x1234 { - t.Errorf("%s: expected seq 0x1234 got 0x%04x\n", uuid1, seq) - } -} - -func TestCoding(t *testing.T) { - text := "7d444840-9dc0-11d1-b245-5ffdce74fad2" - urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2" - data := UUID{ - 0x7d, 0x44, 0x48, 0x40, - 0x9d, 0xc0, - 0x11, 0xd1, - 0xb2, 0x45, - 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2, - } - if v := data.String(); v != text { - t.Errorf("%x: encoded to %s, expected %s\n", data, v, text) - } - if v := data.URN(); v != urn { - t.Errorf("%x: urn is %s, expected %s\n", data, v, urn) - } - - uuid := Parse(text) - if !Equal(uuid, data) { - t.Errorf("%s: decoded to %s, expected %s\n", text, uuid, data) - } -} - -func TestVersion1(t *testing.T) { - uuid1 := NewUUID() - uuid2 := NewUUID() - - if Equal(uuid1, uuid2) { - t.Errorf("%s:duplicate uuid\n", uuid1) - } - if v, _ := uuid1.Version(); v != 1 { - t.Errorf("%s: version %s expected 1\n", uuid1, v) - } - if v, _ := uuid2.Version(); v != 1 { - t.Errorf("%s: version %s expected 1\n", uuid2, v) - } - n1 := uuid1.NodeID() - n2 := uuid2.NodeID() - if !bytes.Equal(n1, n2) { - t.Errorf("Different nodes %x != %x\n", n1, n2) - } - t1, ok := uuid1.Time() - if !ok { - t.Errorf("%s: invalid time\n", uuid1) - } - t2, ok := uuid2.Time() - if !ok { - t.Errorf("%s: invalid time\n", uuid2) - } - q1, ok := uuid1.ClockSequence() - if !ok { - t.Errorf("%s: invalid clock sequence\n", uuid1) - } - q2, ok := uuid2.ClockSequence() - if !ok { - t.Errorf("%s: invalid clock sequence", uuid2) - } - - switch { - case t1 == t2 && q1 == q2: - t.Errorf("time stopped\n") - case t1 > t2 && q1 == q2: - t.Errorf("time reversed\n") - case t1 < t2 && q1 != q2: - t.Errorf("clock sequence chaned unexpectedly\n") - } -} - -func TestNodeAndTime(t *testing.T) { - // Time is February 5, 1998 12:30:23.136364800 AM GMT - - uuid := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2") - node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2} - - ts, ok := uuid.Time() - if ok { - c := time.Unix(ts.UnixTime()) - want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC) - if !c.Equal(want) { - t.Errorf("Got time %v, want %v", c, want) - } - } else { - t.Errorf("%s: bad time\n", uuid) - } - if !bytes.Equal(node, uuid.NodeID()) { - t.Errorf("Expected node %v got %v\n", node, uuid.NodeID()) - } -} - -func TestMD5(t *testing.T) { - uuid := NewMD5(NameSpace_DNS, []byte("python.org")).String() - want := "6fa459ea-ee8a-3ca4-894e-db77e160355e" - if uuid != want { - t.Errorf("MD5: got %q expected %q\n", uuid, want) - } -} - -func TestSHA1(t *testing.T) { - uuid := NewSHA1(NameSpace_DNS, []byte("python.org")).String() - want := "886313e1-3b8a-5372-9b90-0c9aee199e5d" - if uuid != want { - t.Errorf("SHA1: got %q expected %q\n", uuid, want) - } -} - -func TestNodeID(t *testing.T) { - nid := []byte{1, 2, 3, 4, 5, 6} - SetNodeInterface("") - s := NodeInterface() - if s == "" || s == "user" { - t.Errorf("NodeInterface %q after SetInteface\n", s) - } - node1 := NodeID() - if node1 == nil { - t.Errorf("NodeID nil after SetNodeInterface\n", s) - } - SetNodeID(nid) - s = NodeInterface() - if s != "user" { - t.Errorf("Expected NodeInterface %q got %q\n", "user", s) - } - node2 := NodeID() - if node2 == nil { - t.Errorf("NodeID nil after SetNodeID\n", s) - } - if bytes.Equal(node1, node2) { - t.Errorf("NodeID not changed after SetNodeID\n", s) - } else if !bytes.Equal(nid, node2) { - t.Errorf("NodeID is %x, expected %x\n", node2, nid) - } -} - -func testDCE(t *testing.T, name string, uuid UUID, domain Domain, id uint32) { - if uuid == nil { - t.Errorf("%s failed\n", name) - return - } - if v, _ := uuid.Version(); v != 2 { - t.Errorf("%s: %s: expected version 2, got %s\n", name, uuid, v) - return - } - if v, ok := uuid.Domain(); !ok || v != domain { - if !ok { - t.Errorf("%s: %d: Domain failed\n", name, uuid) - } else { - t.Errorf("%s: %s: expected domain %d, got %d\n", name, uuid, domain, v) - } - } - if v, ok := uuid.Id(); !ok || v != id { - if !ok { - t.Errorf("%s: %d: Id failed\n", name, uuid) - } else { - t.Errorf("%s: %s: expected id %d, got %d\n", name, uuid, id, v) - } - } -} - -func TestDCE(t *testing.T) { - testDCE(t, "NewDCESecurity", NewDCESecurity(42, 12345678), 42, 12345678) - testDCE(t, "NewDCEPerson", NewDCEPerson(), Person, uint32(os.Getuid())) - testDCE(t, "NewDCEGroup", NewDCEGroup(), Group, uint32(os.Getgid())) -} - -type badRand struct{} - -func (r badRand) Read(buf []byte) (int, error) { - for i, _ := range buf { - buf[i] = byte(i) - } - return len(buf), nil -} - -func TestBadRand(t *testing.T) { - SetRand(badRand{}) - uuid1 := New() - uuid2 := New() - if uuid1 != uuid2 { - t.Errorf("execpted duplicates, got %q and %q\n", uuid1, uuid2) - } - SetRand(nil) - uuid1 = New() - uuid2 = New() - if uuid1 == uuid2 { - t.Errorf("unexecpted duplicates, got %q\n", uuid1) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/LICENSE b/Godeps/_workspace/src/github.com/prometheus/client_golang/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/prometheus/client_golang/LICENSE @@ -0,0 +1,201 @@ + 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/Godeps/_workspace/src/github.com/prometheus/client_golang/NOTICE b/Godeps/_workspace/src/github.com/prometheus/client_golang/NOTICE new file mode 100644 index 000000000..37e4a7d41 --- /dev/null +++ b/Godeps/_workspace/src/github.com/prometheus/client_golang/NOTICE @@ -0,0 +1,28 @@ +Prometheus instrumentation library for Go applications +Copyright 2012-2015 The Prometheus Authors + +This product includes software developed at +SoundCloud Ltd. (http://soundcloud.com/). + + +The following components are included in this product: + +goautoneg +http://bitbucket.org/ww/goautoneg +Copyright 2011, Open Knowledge Foundation Ltd. +See README.txt for license details. + +perks - a fork of https://github.com/bmizerany/perks +https://github.com/beorn7/perks +Copyright 2013-2015 Blake Mizerany, Björn Rabenstein +See https://github.com/beorn7/perks/blob/master/README.md for license details. + +Go support for Protocol Buffers - Google's data interchange format +http://github.com/golang/protobuf/ +Copyright 2010 The Go Authors +See source code for license details. + +Support for streaming Protocol Buffer messages for the Go language (golang). +https://github.com/matttproud/golang_protobuf_extensions +Copyright 2013 Matt T. Proud +Licensed under the Apache License, Version 2.0 diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/benchmark_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/benchmark_test.go deleted file mode 100644 index 6ae7333fc..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/benchmark_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "testing" -) - -func BenchmarkCounterWithLabelValues(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } -} - -func BenchmarkCounterWithMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.With(Labels{"two": "zwei", "one": "eins", "three": "drei"}).Inc() - } -} - -func BenchmarkCounterWithPreparedMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - labels := Labels{"two": "zwei", "one": "eins", "three": "drei"} - for i := 0; i < b.N; i++ { - m.With(labels).Inc() - } -} - -func BenchmarkCounterNoLabels(b *testing.B) { - m := NewCounter(CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Inc() - } -} - -func BenchmarkGaugeWithLabelValues(b *testing.B) { - m := NewGaugeVec( - GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Set(3.1415) - } -} - -func BenchmarkGaugeNoLabels(b *testing.B) { - m := NewGauge(GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Set(3.1415) - } -} - -func BenchmarkSummaryWithLabelValues(b *testing.B) { - m := NewSummaryVec( - SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkSummaryNoLabels(b *testing.B) { - m := NewSummary(SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} - -func BenchmarkHistogramWithLabelValues(b *testing.B) { - m := NewHistogramVec( - HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkHistogramNoLabels(b *testing.B) { - m := NewHistogram(HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/counter_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/counter_test.go deleted file mode 100644 index 67391a23a..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/counter_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "math" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestCounterAdd(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }).(*counter) - counter.Inc() - if expected, got := 1., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - counter.Add(42) - if expected, got := 43., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - - if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got { - t.Errorf("Expected error %q, got %q.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := `label: label: counter: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func decreaseCounter(c *counter) (err error) { - defer func() { - if e := recover(); e != nil { - err = e.(error) - } - }() - c.Add(-1) - return nil -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go deleted file mode 100644 index 6f3e215d4..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import ( - "sync" - - "github.com/prometheus/client_golang/prometheus" -) - -// ClusterManager is an example for a system that might have been built without -// Prometheus in mind. It models a central manager of jobs running in a -// cluster. To turn it into something that collects Prometheus metrics, we -// simply add the two methods required for the Collector interface. -// -// An additional challenge is that multiple instances of the ClusterManager are -// run within the same binary, each in charge of a different zone. We need to -// make use of ConstLabels to be able to register each ClusterManager instance -// with Prometheus. -type ClusterManager struct { - Zone string - OOMCount *prometheus.CounterVec - RAMUsage *prometheus.GaugeVec - mtx sync.Mutex // Protects OOMCount and RAMUsage. - // ... many more fields -} - -// ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a -// real cluster manager would have to do. Since it may actually be really -// expensive, it must only be called once per collection. This implementation, -// obviously, only returns some made-up data. -func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() ( - oomCountByHost map[string]int, ramUsageByHost map[string]float64, -) { - // Just example fake data. - oomCountByHost = map[string]int{ - "foo.example.org": 42, - "bar.example.org": 2001, - } - ramUsageByHost = map[string]float64{ - "foo.example.org": 6.023e23, - "bar.example.org": 3.14, - } - return -} - -// Describe faces the interesting challenge that the two metric vectors that are -// used in this example are already Collectors themselves. However, thanks to -// the use of channels, it is really easy to "chain" Collectors. Here we simply -// call the Describe methods of the two metric vectors. -func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) { - c.OOMCount.Describe(ch) - c.RAMUsage.Describe(ch) -} - -// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it -// sets the retrieved values in the two metric vectors and then sends all their -// metrics to the channel (again using a chaining technique as in the Describe -// method). Since Collect could be called multiple times concurrently, that part -// is protected by a mutex. -func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) { - oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState() - c.mtx.Lock() - defer c.mtx.Unlock() - for host, oomCount := range oomCountByHost { - c.OOMCount.WithLabelValues(host).Set(float64(oomCount)) - } - for host, ramUsage := range ramUsageByHost { - c.RAMUsage.WithLabelValues(host).Set(ramUsage) - } - c.OOMCount.Collect(ch) - c.RAMUsage.Collect(ch) - // All metrics in OOMCount and RAMUsage are sent to the channel now. We - // can safely reset the two metric vectors now, so that we can start - // fresh in the next Collect cycle. (Imagine a host disappears from the - // cluster. If we did not reset here, its Metric would stay in the - // metric vectors forever.) - c.OOMCount.Reset() - c.RAMUsage.Reset() -} - -// NewClusterManager creates the two metric vectors OOMCount and RAMUsage. Note -// that the zone is set as a ConstLabel. (It's different in each instance of the -// ClusterManager, but constant over the lifetime of an instance.) The reported -// values are partitioned by host, which is therefore a variable label. -func NewClusterManager(zone string) *ClusterManager { - return &ClusterManager{ - Zone: zone, - OOMCount: prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "clustermanager", - Name: "oom_count", - Help: "number of OOM crashes", - ConstLabels: prometheus.Labels{"zone": zone}, - }, - []string{"host"}, - ), - RAMUsage: prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Subsystem: "clustermanager", - Name: "ram_usage_bytes", - Help: "RAM usage as reported to the cluster manager", - ConstLabels: prometheus.Labels{"zone": zone}, - }, - []string{"host"}, - ), - } -} - -func ExampleCollector_clustermanager() { - workerDB := NewClusterManager("db") - workerCA := NewClusterManager("ca") - prometheus.MustRegister(workerDB) - prometheus.MustRegister(workerCA) - - // Since we are dealing with custom Collector implementations, it might - // be a good idea to enable the collect checks in the registry. - prometheus.EnableCollectChecks(true) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_memstats_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_memstats_test.go deleted file mode 100644 index a84d07250..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_memstats_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import ( - "runtime" - - "github.com/prometheus/client_golang/prometheus" -) - -var ( - allocDesc = prometheus.NewDesc( - prometheus.BuildFQName("", "memstats", "alloc_bytes"), - "bytes allocated and still in use", - nil, nil, - ) - totalAllocDesc = prometheus.NewDesc( - prometheus.BuildFQName("", "memstats", "total_alloc_bytes"), - "bytes allocated (even if freed)", - nil, nil, - ) - numGCDesc = prometheus.NewDesc( - prometheus.BuildFQName("", "memstats", "num_gc_total"), - "number of GCs run", - nil, nil, - ) -) - -// MemStatsCollector is an example for a custom Collector that solves the -// problem of feeding into multiple metrics at the same time. The -// runtime.ReadMemStats should happen only once, and then the results need to be -// fed into a number of separate Metrics. In this example, only a few of the -// values reported by ReadMemStats are used. For each, there is a Desc provided -// as a var, so the MemStatsCollector itself needs nothing else in the -// struct. Only the methods need to be implemented. -type MemStatsCollector struct{} - -// Describe just sends the three Desc objects for the Metrics we intend to -// collect. -func (_ MemStatsCollector) Describe(ch chan<- *prometheus.Desc) { - ch <- allocDesc - ch <- totalAllocDesc - ch <- numGCDesc -} - -// Collect does the trick by calling ReadMemStats once and then constructing -// three different Metrics on the fly. -func (_ MemStatsCollector) Collect(ch chan<- prometheus.Metric) { - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - ch <- prometheus.MustNewConstMetric( - allocDesc, - prometheus.GaugeValue, - float64(ms.Alloc), - ) - ch <- prometheus.MustNewConstMetric( - totalAllocDesc, - prometheus.GaugeValue, - float64(ms.TotalAlloc), - ) - ch <- prometheus.MustNewConstMetric( - numGCDesc, - prometheus.CounterValue, - float64(ms.NumGC), - ) - // To avoid new allocations on each collection, you could also keep - // metric objects around and return the same objects each time, just - // with new values set. -} - -func ExampleCollector_memstats() { - prometheus.MustRegister(&MemStatsCollector{}) - // Since we are dealing with custom Collector implementations, it might - // be a good idea to enable the collect checks in the registry. - prometheus.EnableCollectChecks(true) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go deleted file mode 100644 index 608deeb02..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import ( - "runtime" - - "github.com/golang/protobuf/proto" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -func NewCallbackMetric(desc *prometheus.Desc, callback func() float64) *CallbackMetric { - result := &CallbackMetric{desc: desc, callback: callback} - result.Init(result) // Initialize the SelfCollector. - return result -} - -// TODO: Come up with a better example. - -// CallbackMetric is an example for a user-defined Metric that exports the -// result of a function call as a metric of type "untyped" without any -// labels. It uses SelfCollector to turn the Metric into a Collector so that it -// can be registered with Prometheus. -// -// Note that this example is pretty much academic as the prometheus package -// already provides an UntypedFunc type. -type CallbackMetric struct { - prometheus.SelfCollector - - desc *prometheus.Desc - callback func() float64 -} - -func (cm *CallbackMetric) Desc() *prometheus.Desc { - return cm.desc -} - -func (cm *CallbackMetric) Write(m *dto.Metric) error { - m.Untyped = &dto.Untyped{Value: proto.Float64(cm.callback())} - return nil -} - -func ExampleSelfCollector() { - m := NewCallbackMetric( - prometheus.NewDesc( - "runtime_goroutines_count", - "Total number of goroutines that currently exist.", - nil, nil, // No labels, these must be nil. - ), - func() float64 { - return float64(runtime.NumGoroutine()) - }, - ) - prometheus.MustRegister(m) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/examples_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/examples_test.go deleted file mode 100644 index 0344e465b..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/examples_test.go +++ /dev/null @@ -1,649 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import ( - "flag" - "fmt" - "math" - "net/http" - "os" - "runtime" - "sort" - "time" - - dto "github.com/prometheus/client_model/go" - - "github.com/golang/protobuf/proto" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleGauge() { - opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed.", - }) - prometheus.MustRegister(opsQueued) - - // 10 operations queued by the goroutine managing incoming requests. - opsQueued.Add(10) - // A worker goroutine has picked up a waiting operation. - opsQueued.Dec() - // And once more... - opsQueued.Dec() -} - -func ExampleGaugeVec() { - binaryVersion := flag.String("binary_version", "debug", "Version of the binary: debug, canary, production.") - flag.Parse() - - opsQueued := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.", - ConstLabels: prometheus.Labels{"binary_version": *binaryVersion}, - }, - []string{ - // Which user has requested the operation? - "user", - // Of what type is the operation? - "type", - }, - ) - prometheus.MustRegister(opsQueued) - - // Increase a value using compact (but order-sensitive!) WithLabelValues(). - opsQueued.WithLabelValues("bob", "put").Add(4) - // Increase a value with a map using WithLabels. More verbose, but order - // doesn't matter anymore. - opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc() -} - -func ExampleGaugeFunc() { - if err := prometheus.Register(prometheus.NewGaugeFunc( - prometheus.GaugeOpts{ - Subsystem: "runtime", - Name: "goroutines_count", - Help: "Number of goroutines that currently exist.", - }, - func() float64 { return float64(runtime.NumGoroutine()) }, - )); err == nil { - fmt.Println("GaugeFunc 'goroutines_count' registered.") - } - // Note that the count of goroutines is a gauge (and not a counter) as - // it can go up and down. - - // Output: - // GaugeFunc 'goroutines_count' registered. -} - -func ExampleCounter() { - pushCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", // Note: No help string... - }) - err := prometheus.Register(pushCounter) // ... so this will return an error. - if err != nil { - fmt.Println("Push counter couldn't be registered, no counting will happen:", err) - return - } - - // Try it once more, this time with a help string. - pushCounter = prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", - Help: "Number of pushes to external repository.", - }) - err = prometheus.Register(pushCounter) - if err != nil { - fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err) - return - } - - pushComplete := make(chan struct{}) - // TODO: Start a goroutine that performs repository pushes and reports - // each completion via the channel. - for _ = range pushComplete { - pushCounter.Inc() - } - // Output: - // Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string -} - -func ExampleCounterVec() { - binaryVersion := flag.String("environment", "test", "Execution environment: test, staging, production.") - flag.Parse() - - httpReqs := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "http_requests_total", - Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", - ConstLabels: prometheus.Labels{"env": *binaryVersion}, - }, - []string{"code", "method"}, - ) - prometheus.MustRegister(httpReqs) - - httpReqs.WithLabelValues("404", "POST").Add(42) - - // If you have to access the same set of labels very frequently, it - // might be good to retrieve the metric only once and keep a handle to - // it. But beware of deletion of that metric, see below! - m := httpReqs.WithLabelValues("200", "GET") - for i := 0; i < 1000000; i++ { - m.Inc() - } - // Delete a metric from the vector. If you have previously kept a handle - // to that metric (as above), future updates via that handle will go - // unseen (even if you re-create a metric with the same label set - // later). - httpReqs.DeleteLabelValues("200", "GET") - // Same thing with the more verbose Labels syntax. - httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"}) -} - -func ExampleInstrumentHandler() { - // Handle the "/doc" endpoint with the standard http.FileServer handler. - // By wrapping the handler with InstrumentHandler, request count, - // request and response sizes, and request latency are automatically - // exported to Prometheus, partitioned by HTTP status code and method - // and by the handler name (here "fileserver"). - http.Handle("/doc", prometheus.InstrumentHandler( - "fileserver", http.FileServer(http.Dir("/usr/share/doc")), - )) - // The Prometheus handler still has to be registered to handle the - // "/metrics" endpoint. The handler returned by prometheus.Handler() is - // already instrumented - with "prometheus" as the handler name. In this - // example, we want the handler name to be "metrics", so we instrument - // the uninstrumented Prometheus handler ourselves. - http.Handle("/metrics", prometheus.InstrumentHandler( - "metrics", prometheus.UninstrumentedHandler(), - )) -} - -func ExampleLabelPairSorter() { - labelPairs := []*dto.LabelPair{ - &dto.LabelPair{Name: proto.String("status"), Value: proto.String("404")}, - &dto.LabelPair{Name: proto.String("method"), Value: proto.String("get")}, - } - - sort.Sort(prometheus.LabelPairSorter(labelPairs)) - - fmt.Println(labelPairs) - // Output: - // [name:"method" value:"get" name:"status" value:"404" ] -} - -func ExampleRegister() { - // Imagine you have a worker pool and want to count the tasks completed. - taskCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }) - // This will register fine. - if err := prometheus.Register(taskCounter); err != nil { - fmt.Println(err) - } else { - fmt.Println("taskCounter registered.") - } - // Don't forget to tell the HTTP server about the Prometheus handler. - // (In a real program, you still need to start the HTTP server...) - http.Handle("/metrics", prometheus.Handler()) - - // Now you can start workers and give every one of them a pointer to - // taskCounter and let it increment it whenever it completes a task. - taskCounter.Inc() // This has to happen somewhere in the worker code. - - // But wait, you want to see how individual workers perform. So you need - // a vector of counters, with one element for each worker. - taskCounterVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - - // Registering will fail because we already have a metric of that name. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - - // To fix, first unregister the old taskCounter. - if prometheus.Unregister(taskCounter) { - fmt.Println("taskCounter unregistered.") - } - - // Try registering taskCounterVec again. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Bummer! Still doesn't work. - - // Prometheus will not allow you to ever export metrics with - // inconsistent help strings or label names. After unregistering, the - // unregistered metrics will cease to show up in the /metrics HTTP - // response, but the registry still remembers that those metrics had - // been exported before. For this example, we will now choose a - // different name. (In a real program, you would obviously not export - // the obsolete metric in the first place.) - taskCounterVec = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_by_id", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Finally it worked! - - // The workers have to tell taskCounterVec their id to increment the - // right element in the metric vector. - taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42. - - // Each worker could also keep a reference to their own counter element - // around. Pick the counter at initialization time of the worker. - myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code. - myCounter.Inc() // Somewhere in the code of that worker. - - // Note that something like WithLabelValues("42", "spurious arg") would - // panic (because you have provided too many label values). If you want - // to get an error instead, use GetMetricWithLabelValues(...) instead. - notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg") - if err != nil { - fmt.Println("Worker initialization failed:", err) - } - if notMyCounter == nil { - fmt.Println("notMyCounter is nil.") - } - - // A different (and somewhat tricky) approach is to use - // ConstLabels. ConstLabels are pairs of label names and label values - // that never change. You might ask what those labels are good for (and - // rightfully so - if they never change, they could as well be part of - // the metric name). There are essentially two use-cases: The first is - // if labels are constant throughout the lifetime of a binary execution, - // but they vary over time or between different instances of a running - // binary. The second is what we have here: Each worker creates and - // registers an own Counter instance where the only difference is in the - // value of the ConstLabels. Those Counters can all be registered - // because the different ConstLabel values guarantee that each worker - // will increment a different Counter metric. - counterOpts := prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks", - Help: "Total number of tasks completed.", - ConstLabels: prometheus.Labels{"worker_id": "42"}, - } - taskCounterForWorker42 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker42); err != nil { - fmt.Println("taskCounterVForWorker42 not registered:", err) - } else { - fmt.Println("taskCounterForWorker42 registered.") - } - // Obviously, in real code, taskCounterForWorker42 would be a member - // variable of a worker struct, and the "42" would be retrieved with a - // GetId() method or something. The Counter would be created and - // registered in the initialization code of the worker. - - // For the creation of the next Counter, we can recycle - // counterOpts. Just change the ConstLabels. - counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"} - taskCounterForWorker2001 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker2001); err != nil { - fmt.Println("taskCounterVForWorker2001 not registered:", err) - } else { - fmt.Println("taskCounterForWorker2001 registered.") - } - - taskCounterForWorker2001.Inc() - taskCounterForWorker42.Inc() - taskCounterForWorker2001.Inc() - - // Yet another approach would be to turn the workers themselves into - // Collectors and register them. See the Collector example for details. - - // Output: - // taskCounter registered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounter unregistered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounterVec registered. - // Worker initialization failed: inconsistent label cardinality - // notMyCounter is nil. - // taskCounterForWorker42 registered. - // taskCounterForWorker2001 registered. -} - -func ExampleSummary() { - temps := prometheus.NewSummary(prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > -} - -func ExampleSummaryVec() { - temps := prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }, - []string{"species"}, - ) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10) - } - - // Create a Summary without any observations. - temps.WithLabelValues("leiopelma-hochstetteri") - - // Just for demonstration, let's check the state of the summary vector - // by (ab)using its Collect method and the Write method of its elements - // (which is usually only used by Prometheus internally - code like the - // following will never appear in your own code). - metricChan := make(chan prometheus.Metric) - go func() { - defer close(metricChan) - temps.Collect(metricChan) - }() - - metricStrings := []string{} - for metric := range metricChan { - dtoMetric := &dto.Metric{} - metric.Write(dtoMetric) - metricStrings = append(metricStrings, proto.MarshalTextString(dtoMetric)) - } - sort.Strings(metricStrings) // For reproducible print order. - fmt.Println(metricStrings) - - // Output: - // [label: < - // name: "species" - // value: "leiopelma-hochstetteri" - // > - // summary: < - // sample_count: 0 - // sample_sum: 0 - // quantile: < - // quantile: 0.5 - // value: nan - // > - // quantile: < - // quantile: 0.9 - // value: nan - // > - // quantile: < - // quantile: 0.99 - // value: nan - // > - // > - // label: < - // name: "species" - // value: "lithobates-catesbeianus" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 31956.100000000017 - // quantile: < - // quantile: 0.5 - // value: 32.4 - // > - // quantile: < - // quantile: 0.9 - // value: 41.4 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // label: < - // name: "species" - // value: "litoria-caerulea" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // ] -} - -func ExampleConstSummary() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A summary of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant summary from values we got from a 3rd party telemetry system. - s := prometheus.MustNewConstSummary( - desc, - 4711, 403.34, - map[float64]float64{0.5: 42.3, 0.9: 323.3}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - s.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // summary: < - // sample_count: 4711 - // sample_sum: 403.34 - // quantile: < - // quantile: 0.5 - // value: 42.3 - // > - // quantile: < - // quantile: 0.9 - // value: 323.3 - // > - // > -} - -func ExampleHistogram() { - temps := prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // histogram: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // bucket: < - // cumulative_count: 192 - // upper_bound: 20 - // > - // bucket: < - // cumulative_count: 366 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 501 - // upper_bound: 30 - // > - // bucket: < - // cumulative_count: 638 - // upper_bound: 35 - // > - // bucket: < - // cumulative_count: 816 - // upper_bound: 40 - // > - // > -} - -func ExampleConstHistogram() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A histogram of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant histogram from values we got from a 3rd party telemetry system. - h := prometheus.MustNewConstHistogram( - desc, - 4711, 403.34, - map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - h.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // histogram: < - // sample_count: 4711 - // sample_sum: 403.34 - // bucket: < - // cumulative_count: 121 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 2403 - // upper_bound: 50 - // > - // bucket: < - // cumulative_count: 3221 - // upper_bound: 100 - // > - // bucket: < - // cumulative_count: 4233 - // upper_bound: 200 - // > - // > -} - -func ExamplePushCollectors() { - hostname, _ := os.Hostname() - completionTime := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_last_completion_time", - Help: "The timestamp of the last succesful completion of a DB backup.", - }) - completionTime.Set(float64(time.Now().Unix())) - if err := prometheus.PushCollectors( - "db_backup", hostname, - "http://pushgateway:9091", - completionTime, - ); err != nil { - fmt.Println("Could not push completion time to Pushgateway:", err) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/expvar_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/expvar_test.go deleted file mode 100644 index 5d3128fae..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/expvar_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import ( - "expvar" - "fmt" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleExpvarCollector() { - expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{ - "memstats": prometheus.NewDesc( - "expvar_memstats", - "All numeric memstats as one metric family. Not a good role-model, actually... ;-)", - []string{"type"}, nil, - ), - "lone-int": prometheus.NewDesc( - "expvar_lone_int", - "Just an expvar int as an example.", - nil, nil, - ), - "http-request-map": prometheus.NewDesc( - "expvar_http_request_total", - "How many http requests processed, partitioned by status code and http method.", - []string{"code", "method"}, nil, - ), - }) - prometheus.MustRegister(expvarCollector) - - // The Prometheus part is done here. But to show that this example is - // doing anything, we have to manually export something via expvar. In - // real-life use-cases, some library would already have exported via - // expvar what we want to re-export as Prometheus metrics. - expvar.NewInt("lone-int").Set(42) - expvarMap := expvar.NewMap("http-request-map") - var ( - expvarMap1, expvarMap2 expvar.Map - expvarInt11, expvarInt12, expvarInt21, expvarInt22 expvar.Int - ) - expvarMap1.Init() - expvarMap2.Init() - expvarInt11.Set(3) - expvarInt12.Set(13) - expvarInt21.Set(11) - expvarInt22.Set(212) - expvarMap1.Set("POST", &expvarInt11) - expvarMap1.Set("GET", &expvarInt12) - expvarMap2.Set("POST", &expvarInt21) - expvarMap2.Set("GET", &expvarInt22) - expvarMap.Set("404", &expvarMap1) - expvarMap.Set("200", &expvarMap2) - // Results in the following expvar map: - // "http-request-count": {"200": {"POST": 11, "GET": 212}, "404": {"POST": 3, "GET": 13}} - - // Let's see what the scrape would yield, but exclude the memstats metrics. - metricStrings := []string{} - metric := dto.Metric{} - metricChan := make(chan prometheus.Metric) - go func() { - expvarCollector.Collect(metricChan) - close(metricChan) - }() - for m := range metricChan { - if strings.Index(m.Desc().String(), "expvar_memstats") == -1 { - metric.Reset() - m.Write(&metric) - metricStrings = append(metricStrings, metric.String()) - } - } - sort.Strings(metricStrings) - for _, s := range metricStrings { - fmt.Println(strings.TrimRight(s, " ")) - } - // Output: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // untyped: -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/gauge_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/gauge_test.go deleted file mode 100644 index 48cab4636..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/gauge_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "math" - "math/rand" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func listenGaugeStream(vals, result chan float64, done chan struct{}) { - var sum float64 -outer: - for { - select { - case <-done: - close(vals) - for v := range vals { - sum += v - } - break outer - case v := <-vals: - sum += v - } - } - result <- sum - close(result) -} - -func TestGaugeConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStream := make(chan float64, mutations*concLevel) - result := make(chan float64) - done := make(chan struct{}) - - go listenGaugeStream(sStream, result, done) - go func() { - end.Wait() - close(done) - }() - - gge := NewGauge(GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sStream <- v - gge.Add(v) - } - end.Done() - }(vals) - } - start.Done() - - if expected, got := <-result, math.Float64frombits(gge.(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeVecConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - vecLength := int(n%5 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStreams := make([]chan float64, vecLength) - results := make([]chan float64, vecLength) - done := make(chan struct{}) - - for i := 0; i < vecLength; i++ { - sStreams[i] = make(chan float64, mutations*concLevel) - results[i] = make(chan float64) - go listenGaugeStream(sStreams[i], results[i], done) - } - - go func() { - end.Wait() - close(done) - }() - - gge := NewGaugeVec( - GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }, - []string{"label"}, - ) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - pick := make([]int, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - pick[j] = rand.Intn(vecLength) - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sStreams[pick[i]] <- v - gge.WithLabelValues(string('A' + pick[i])).Add(v) - } - end.Done() - }(vals) - } - start.Done() - - for i := range sStreams { - if expected, got := <-results[i], math.Float64frombits(gge.WithLabelValues(string('A'+i)).(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeFunc(t *testing.T) { - gf := NewGaugeFunc( - GaugeOpts{ - Name: "test_name", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }, - func() float64 { return 3.1415 }, - ) - - if expected, got := `Desc{fqName: "test_name", help: "test help", constLabels: {a="1",b="2"}, variableLabels: []}`, gf.Desc().String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } - - m := &dto.Metric{} - gf.Write(m) - - if expected, got := `label: label: gauge: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/go_collector_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/go_collector_test.go deleted file mode 100644 index 9a8858cbd..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/go_collector_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package prometheus - -import ( - "runtime" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func TestGoCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - old = -1 - ) - defer close(closec) - - go func() { - c.Collect(ch) - go func(c <-chan struct{}) { - <-c - }(closec) - <-waitc - c.Collect(ch) - }() - - for { - select { - case metric := <-ch: - switch m := metric.(type) { - // Attention, this also catches Counter... - case Gauge: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetGauge() == nil { - continue - } - - if old == -1 { - old = int(pb.GetGauge().GetValue()) - close(waitc) - continue - } - - if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 { - // TODO: This is flaky in highly concurrent situations. - t.Errorf("want 1 new goroutine, got %d", diff) - } - - // GoCollector performs two sends per call. - // On line 27 we need to receive the second send - // to shut down cleanly. - <-ch - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} - -func TestGCCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - oldGC uint64 - oldPause float64 - ) - defer close(closec) - - go func() { - c.Collect(ch) - // force GC - runtime.GC() - <-waitc - c.Collect(ch) - }() - - first := true - for { - select { - case metric := <-ch: - switch m := metric.(type) { - case *constSummary, *value: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetSummary() == nil { - continue - } - - if len(pb.GetSummary().Quantile) != 5 { - t.Errorf("expected 4 buckets, got %d", len(pb.GetSummary().Quantile)) - } - for idx, want := range []float64{0.0, 0.25, 0.5, 0.75, 1.0} { - if *pb.GetSummary().Quantile[idx].Quantile != want { - t.Errorf("bucket #%d is off, got %f, want %f", idx, *pb.GetSummary().Quantile[idx].Quantile, want) - } - } - if first { - first = false - oldGC = *pb.GetSummary().SampleCount - oldPause = *pb.GetSummary().SampleSum - close(waitc) - continue - } - if diff := *pb.GetSummary().SampleCount - oldGC; diff != 1 { - t.Errorf("want 1 new garbage collection run, got %d", diff) - } - if diff := *pb.GetSummary().SampleSum - oldPause; diff <= 0 { - t.Errorf("want moar pause, got %f", diff) - } - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/histogram_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/histogram_test.go deleted file mode 100644 index 11cf66b4f..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/histogram_test.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2015 The Prometheus 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 prometheus - -import ( - "math" - "math/rand" - "reflect" - "sort" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkHistogramObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramObserve1(b *testing.B) { - benchmarkHistogramObserve(1, b) -} - -func BenchmarkHistogramObserve2(b *testing.B) { - benchmarkHistogramObserve(2, b) -} - -func BenchmarkHistogramObserve4(b *testing.B) { - benchmarkHistogramObserve(4, b) -} - -func BenchmarkHistogramObserve8(b *testing.B) { - benchmarkHistogramObserve(8, b) -} - -func benchmarkHistogramWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramWrite1(b *testing.B) { - benchmarkHistogramWrite(1, b) -} - -func BenchmarkHistogramWrite2(b *testing.B) { - benchmarkHistogramWrite(2, b) -} - -func BenchmarkHistogramWrite4(b *testing.B) { - benchmarkHistogramWrite(4, b) -} - -func BenchmarkHistogramWrite8(b *testing.B) { - benchmarkHistogramWrite(8, b) -} - -// Intentionally adding +Inf here to test if that case is handled correctly. -// Also, getCumulativeCounts depends on it. -var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)} - -func TestHistogramConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewHistogram(HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: testBuckets, - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Histogram.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - for i, wantBound := range testBuckets { - if i == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[i].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[i].CumulativeCount, wantCounts[i]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestHistogramVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - his := NewHistogramVec( - HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}, - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - his.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := his.WithLabelValues(string('A' + i)) - s.Write(m) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - if got, want := int(*m.Histogram.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars[i]) - - for j, wantBound := range testBuckets { - if j == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[j].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[j].CumulativeCount, wantCounts[j]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func getCumulativeCounts(vars []float64) []uint64 { - counts := make([]uint64, len(testBuckets)) - for _, v := range vars { - for i := len(testBuckets) - 1; i >= 0; i-- { - if v > testBuckets[i] { - break - } - counts[i]++ - } - } - return counts -} - -func TestBuckets(t *testing.T) { - got := LinearBuckets(-15, 5, 6) - want := []float64{-15, -10, -5, 0, 5, 10} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } - - got = ExponentialBuckets(100, 1.2, 3) - want = []float64{100, 120, 144} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/http_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/http_test.go deleted file mode 100644 index ffe0418cf..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/http_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -type respBody string - -func (b respBody) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTeapot) - w.Write([]byte(b)) -} - -func TestInstrumentHandler(t *testing.T) { - defer func(n nower) { - now = n.(nower) - }(now) - - instant := time.Now() - end := instant.Add(30 * time.Second) - now = nowSeries(instant, end) - respBody := respBody("Howdy there!") - - hndlr := InstrumentHandler("test-handler", respBody) - - opts := SummaryOpts{ - Subsystem: "http", - ConstLabels: Labels{"handler": "test-handler"}, - } - - reqCnt := MustRegisterOrGet(NewCounterVec( - CounterOpts{ - Namespace: opts.Namespace, - Subsystem: opts.Subsystem, - Name: "requests_total", - Help: "Total number of HTTP requests made.", - ConstLabels: opts.ConstLabels, - }, - instLabels, - )).(*CounterVec) - - opts.Name = "request_duration_microseconds" - opts.Help = "The HTTP request latencies in microseconds." - reqDur := MustRegisterOrGet(NewSummary(opts)).(Summary) - - opts.Name = "request_size_bytes" - opts.Help = "The HTTP request sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - opts.Name = "response_size_bytes" - opts.Help = "The HTTP response sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - reqCnt.Reset() - - resp := httptest.NewRecorder() - req := &http.Request{ - Method: "GET", - } - - hndlr.ServeHTTP(resp, req) - - if resp.Code != http.StatusTeapot { - t.Fatalf("expected status %d, got %d", http.StatusTeapot, resp.Code) - } - if string(resp.Body.Bytes()) != "Howdy there!" { - t.Fatalf("expected body %s, got %s", "Howdy there!", string(resp.Body.Bytes())) - } - - out := &dto.Metric{} - reqDur.Write(out) - if want, got := "test-handler", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqDur, got %q", want, got) - } - if want, got := uint64(1), out.Summary.GetSampleCount(); want != got { - t.Errorf("want sample count %d in reqDur, got %d", want, got) - } - - out.Reset() - if want, got := 1, len(reqCnt.children); want != got { - t.Errorf("want %d children in reqCnt, got %d", want, got) - } - cnt, err := reqCnt.GetMetricWithLabelValues("get", "418") - if err != nil { - t.Fatal(err) - } - cnt.Write(out) - if want, got := "418", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "test-handler", out.Label[1].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "get", out.Label[2].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if out.Counter == nil { - t.Fatal("expected non-nil counter in reqCnt") - } - if want, got := 1., out.Counter.GetValue(); want != got { - t.Errorf("want reqCnt of %f, got %f", want, got) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/metric_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/metric_test.go deleted file mode 100644 index 7145f5e53..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/metric_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import "testing" - -func TestBuildFQName(t *testing.T) { - scenarios := []struct{ namespace, subsystem, name, result string }{ - {"a", "b", "c", "a_b_c"}, - {"", "b", "c", "b_c"}, - {"a", "", "c", "a_c"}, - {"", "", "c", "c"}, - {"a", "b", "", ""}, - {"a", "", "", ""}, - {"", "b", "", ""}, - {" ", "", "", ""}, - } - - for i, s := range scenarios { - if want, got := s.result, BuildFQName(s.namespace, s.subsystem, s.name); want != got { - t.Errorf("%d. want %s, got %s", i, want, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/process_collector_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/process_collector_test.go deleted file mode 100644 index 829715acd..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/process_collector_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package prometheus - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "regexp" - "testing" - - "github.com/prometheus/procfs" -) - -func TestProcessCollector(t *testing.T) { - if _, err := procfs.Self(); err != nil { - t.Skipf("skipping TestProcessCollector, procfs not available: %s", err) - } - - registry := newRegistry() - registry.Register(NewProcessCollector(os.Getpid(), "")) - registry.Register(NewProcessCollectorPIDFn( - func() (int, error) { return os.Getpid(), nil }, "foobar")) - - s := httptest.NewServer(InstrumentHandler("prometheus", registry)) - defer s.Close() - r, err := http.Get(s.URL) - if err != nil { - t.Fatal(err) - } - defer r.Body.Close() - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - - for _, re := range []*regexp.Regexp{ - regexp.MustCompile("process_cpu_seconds_total [0-9]"), - regexp.MustCompile("process_max_fds [0-9]{2,}"), - regexp.MustCompile("process_open_fds [1-9]"), - regexp.MustCompile("process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("process_resident_memory_bytes [1-9]"), - regexp.MustCompile("process_start_time_seconds [0-9.]{10,}"), - regexp.MustCompile("foobar_process_cpu_seconds_total [0-9]"), - regexp.MustCompile("foobar_process_max_fds [0-9]{2,}"), - regexp.MustCompile("foobar_process_open_fds [1-9]"), - regexp.MustCompile("foobar_process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_resident_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_start_time_seconds [0-9.]{10,}"), - } { - if !re.Match(body) { - t.Errorf("want body to match %s\n%s", re, body) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/registry_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/registry_test.go deleted file mode 100644 index f30c90c06..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/registry_test.go +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright 2014 The Prometheus 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. - -// Copyright (c) 2013, The Prometheus 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 prometheus - -import ( - "bytes" - "encoding/binary" - "net/http" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -type fakeResponseWriter struct { - header http.Header - body bytes.Buffer -} - -func (r *fakeResponseWriter) Header() http.Header { - return r.header -} - -func (r *fakeResponseWriter) Write(d []byte) (l int, err error) { - return r.body.Write(d) -} - -func (r *fakeResponseWriter) WriteHeader(c int) { -} - -func testHandler(t testing.TB) { - - metricVec := NewCounterVec( - CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - - metricVec.WithLabelValues("val1").Inc() - metricVec.WithLabelValues("val2").Inc() - - varintBuf := make([]byte, binary.MaxVarintLen32) - - externalMetricFamily := &dto.MetricFamily{ - Name: proto.String("externalname"), - Help: proto.String("externaldocstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("externalconstname"), - Value: proto.String("externalconstvalue"), - }, - { - Name: proto.String("externallabelname"), - Value: proto.String("externalval1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - marshaledExternalMetricFamily, err := proto.Marshal(externalMetricFamily) - if err != nil { - t.Fatal(err) - } - var externalBuf bytes.Buffer - l := binary.PutUvarint(varintBuf, uint64(len(marshaledExternalMetricFamily))) - _, err = externalBuf.Write(varintBuf[:l]) - if err != nil { - t.Fatal(err) - } - _, err = externalBuf.Write(marshaledExternalMetricFamily) - if err != nil { - t.Fatal(err) - } - externalMetricFamilyAsBytes := externalBuf.Bytes() - externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring -# TYPE externalname counter -externalname{externalconstname="externalconstvalue",externallabelname="externalval1"} 1 -`) - externalMetricFamilyAsProtoText := []byte(`name: "externalname" -help: "externaldocstring" -type: COUNTER -metric: < - label: < - name: "externalconstname" - value: "externalconstvalue" - > - label: < - name: "externallabelname" - value: "externalval1" - > - counter: < - value: 1 - > -> - -`) - externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > -`) - - expectedMetricFamily := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - marshaledExpectedMetricFamily, err := proto.Marshal(expectedMetricFamily) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - l = binary.PutUvarint(varintBuf, uint64(len(marshaledExpectedMetricFamily))) - _, err = buf.Write(varintBuf[:l]) - if err != nil { - t.Fatal(err) - } - _, err = buf.Write(marshaledExpectedMetricFamily) - if err != nil { - t.Fatal(err) - } - expectedMetricFamilyAsBytes := buf.Bytes() - expectedMetricFamilyAsText := []byte(`# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -`) - expectedMetricFamilyAsProtoText := []byte(`name: "name" -help: "docstring" -type: COUNTER -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val1" - > - counter: < - value: 1 - > -> -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val2" - > - counter: < - value: 1 - > -> - -`) - expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > -`) - - externalMetricFamilyWithSameName := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("inconsistent help string does not matter here"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("different_val"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(42), - }, - }, - }, - } - - expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: > -`) - - type output struct { - headers map[string]string - body []byte - } - - var scenarios = []struct { - headers map[string]string - out output - collector Collector - externalMF []*dto.MetricFamily - }{ - { // 0 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, dings/bums;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 1 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/quark;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 2 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 3 - headers: map[string]string{ - "Accept": "text/plain;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: []byte{}, - }, - }, - { // 4 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 5 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: expectedMetricFamilyAsBytes, - }, - collector: metricVec, - }, - { // 6 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: externalMetricFamilyAsText, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 7 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: externalMetricFamilyAsBytes, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 8 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 9 - headers: map[string]string{ - "Accept": "text/plain", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 10 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 11 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5;version=0.0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsText, - expectedMetricFamilyAsText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 12 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.2, text/plain;q=0.5;version=0.0.2", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 13 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoText, - expectedMetricFamilyAsProtoText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 14 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 15 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyMergedWithExternalAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{ - externalMetricFamily, - externalMetricFamilyWithSameName, - }, - }, - } - for i, scenario := range scenarios { - registry := newRegistry() - registry.collectChecksEnabled = true - - if scenario.collector != nil { - registry.Register(scenario.collector) - } - if scenario.externalMF != nil { - registry.metricFamilyInjectionHook = func() []*dto.MetricFamily { - return scenario.externalMF - } - } - writer := &fakeResponseWriter{ - header: http.Header{}, - } - handler := InstrumentHandler("prometheus", registry) - request, _ := http.NewRequest("GET", "/", nil) - for key, value := range scenario.headers { - request.Header.Add(key, value) - } - handler(writer, request) - - for key, value := range scenario.out.headers { - if writer.Header().Get(key) != value { - t.Errorf( - "%d. expected %q for header %q, got %q", - i, value, key, writer.Header().Get(key), - ) - } - } - - if !bytes.Equal(scenario.out.body, writer.body.Bytes()) { - t.Errorf( - "%d. expected %q for body, got %q", - i, scenario.out.body, writer.body.Bytes(), - ) - } - } -} - -func TestHandler(t *testing.T) { - testHandler(t) -} - -func BenchmarkHandler(b *testing.B) { - for i := 0; i < b.N; i++ { - testHandler(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/summary_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/summary_test.go deleted file mode 100644 index 0790cdfe7..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/summary_test.go +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "math" - "math/rand" - "sort" - "sync" - "testing" - "testing/quick" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkSummaryObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryObserve1(b *testing.B) { - benchmarkSummaryObserve(1, b) -} - -func BenchmarkSummaryObserve2(b *testing.B) { - benchmarkSummaryObserve(2, b) -} - -func BenchmarkSummaryObserve4(b *testing.B) { - benchmarkSummaryObserve(4, b) -} - -func BenchmarkSummaryObserve8(b *testing.B) { - benchmarkSummaryObserve(8, b) -} - -func benchmarkSummaryWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryWrite1(b *testing.B) { - benchmarkSummaryWrite(1, b) -} - -func BenchmarkSummaryWrite2(b *testing.B) { - benchmarkSummaryWrite(2, b) -} - -func BenchmarkSummaryWrite4(b *testing.B) { - benchmarkSummaryWrite(4, b) -} - -func BenchmarkSummaryWrite8(b *testing.B) { - benchmarkSummaryWrite(8, b) -} - -func TestSummaryConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Summary.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Summary.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - for i, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[i].Quantile - gotV := *m.Summary.Quantile[i].Value - min, max := getBounds(allVars, wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f, want %f", gotQ, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f, want [%f,%f]", gotV, gotQ, min, max) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummaryVec( - SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sum.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := sum.WithLabelValues(string('A' + i)) - s.Write(m) - if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want) - } - if got, want := *m.Summary.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f for label %c, want %f", got, 'A'+i, want) - } - for j, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[j].Quantile - gotV := *m.Summary.Quantile[j].Value - min, max := getBounds(allVars[i], wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f for label %c, want %f", gotQ, 'A'+i, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f for label %c, want [%f,%f]", gotV, gotQ, 'A'+i, min, max) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryDecay(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - // More because it depends on timing than because it is particularly long... - } - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - MaxAge: 100 * time.Millisecond, - Objectives: map[float64]float64{0.1: 0.001}, - AgeBuckets: 10, - }) - - m := &dto.Metric{} - i := 0 - tick := time.NewTicker(time.Millisecond) - for _ = range tick.C { - i++ - sum.Observe(float64(i)) - if i%10 == 0 { - sum.Write(m) - if got, want := *m.Summary.Quantile[0].Value, math.Max(float64(i)/10, float64(i-90)); math.Abs(got-want) > 20 { - t.Errorf("%d. got %f, want %f", i, got, want) - } - m.Reset() - } - if i >= 1000 { - break - } - } - tick.Stop() - // Wait for MaxAge without observations and make sure quantiles are NaN. - time.Sleep(100 * time.Millisecond) - sum.Write(m) - if got := *m.Summary.Quantile[0].Value; !math.IsNaN(got) { - t.Errorf("got %f, want NaN after expiration", got) - } -} - -func getBounds(vars []float64, q, ε float64) (min, max float64) { - // TODO: This currently tolerates an error of up to 2*ε. The error must - // be at most ε, but for some reason, it's sometimes slightly - // higher. That's a bug. - n := float64(len(vars)) - lower := int((q - 2*ε) * n) - upper := int(math.Ceil((q + 2*ε) * n)) - min = vars[0] - if lower > 1 { - min = vars[lower-1] - } - max = vars[len(vars)-1] - if upper < len(vars) { - max = vars[upper-1] - } - return -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/vec_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/vec_test.go deleted file mode 100644 index 0e9431e65..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/vec_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "hash/fnv" - "testing" -) - -func TestDelete(t *testing.T) { - desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil) - vec := MetricVec{ - children: map[uint64]Metric{}, - desc: desc, - hash: fnv.New64a(), - newMetric: func(lvs ...string) Metric { - return newValue(desc, UntypedValue, 0, lvs...) - }, - } - - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v1", "l1": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestDeleteLabelValues(t *testing.T) { - desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil) - vec := MetricVec{ - children: map[uint64]Metric{}, - desc: desc, - hash: fnv.New64a(), - newMetric: func(lvs ...string) Metric { - return newValue(desc, UntypedValue, 0, lvs...) - }, - } - - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_model/LICENSE b/Godeps/_workspace/src/github.com/prometheus/client_model/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/prometheus/client_model/LICENSE @@ -0,0 +1,201 @@ + 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/Godeps/_workspace/src/github.com/prometheus/client_model/NOTICE b/Godeps/_workspace/src/github.com/prometheus/client_model/NOTICE new file mode 100644 index 000000000..20110e410 --- /dev/null +++ b/Godeps/_workspace/src/github.com/prometheus/client_model/NOTICE @@ -0,0 +1,5 @@ +Data model artifacts for Prometheus. +Copyright 2012-2015 The Prometheus Authors + +This product includes software developed at +SoundCloud Ltd. (http://soundcloud.com/). diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/bench_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/bench_test.go deleted file mode 100644 index 92b16a028..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/bench_test.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2015 The Prometheus 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 expfmt - -import ( - "bytes" - "compress/gzip" - "io" - "io/ioutil" - "testing" - - "github.com/matttproud/golang_protobuf_extensions/pbutil" - - dto "github.com/prometheus/client_model/go" -) - -var parser TextParser - -// Benchmarks to show how much penalty text format parsing actually inflicts. -// -// Example results on Linux 3.13.0, Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, go1.4. -// -// BenchmarkParseText 1000 1188535 ns/op 205085 B/op 6135 allocs/op -// BenchmarkParseTextGzip 1000 1376567 ns/op 246224 B/op 6151 allocs/op -// BenchmarkParseProto 10000 172790 ns/op 52258 B/op 1160 allocs/op -// BenchmarkParseProtoGzip 5000 324021 ns/op 94931 B/op 1211 allocs/op -// BenchmarkParseProtoMap 10000 187946 ns/op 58714 B/op 1203 allocs/op -// -// CONCLUSION: The overhead for the map is negligible. Text format needs ~5x more allocations. -// Without compression, it needs ~7x longer, but with compression (the more relevant scenario), -// the difference becomes less relevant, only ~4x. -// -// The test data contains 248 samples. -// -// BenchmarkProcessor002ParseOnly in the extraction package is not quite -// comparable to the benchmarks here, but it gives an idea: JSON parsing is even -// slower than text parsing and needs a comparable amount of allocs. - -// BenchmarkParseText benchmarks the parsing of a text-format scrape into metric -// family DTOs. -func BenchmarkParseText(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - if _, err := parser.TextToMetricFamilies(bytes.NewReader(data)); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseTextGzip benchmarks the parsing of a gzipped text-format scrape -// into metric family DTOs. -func BenchmarkParseTextGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - if _, err := parser.TextToMetricFamilies(in); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseProto benchmarks the parsing of a protobuf-format scrape into -// metric family DTOs. Note that this does not build a map of metric families -// (as the text version does), because it is not required for Prometheus -// ingestion either. (However, it is required for the text-format parsing, as -// the metric family might be sprinkled all over the text, while the -// protobuf-format guarantees bundling at one place.) -func BenchmarkParseProto(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoGzip is like BenchmarkParseProto above, but parses gzipped -// protobuf format. -func BenchmarkParseProtoGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoMap is like BenchmarkParseProto but DOES put the parsed -// metric family DTOs into a map. This is not happening during Prometheus -// ingestion. It is just here to measure the overhead of that map creation and -// separate it from the overhead of the text format parsing. -func BenchmarkParseProtoMap(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - families := map[string]*dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family := &dto.MetricFamily{} - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - families[family.GetName()] = family - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/decode_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/decode_test.go deleted file mode 100644 index 307fcd21f..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/decode_test.go +++ /dev/null @@ -1,373 +0,0 @@ -// Copyright 2015 The Prometheus 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 expfmt - -import ( - "errors" - "io" - "net/http" - "reflect" - "sort" - "strings" - "testing" - - "github.com/prometheus/common/model" -) - -func TestTextDecoder(t *testing.T) { - var ( - ts = model.Now() - in = ` -# Only a quite simple scenario with two metric families. -# More complicated tests of the parser itself can be found in the text package. -# TYPE mf2 counter -mf2 3 -mf1{label="value1"} -3.14 123456 -mf1{label="value2"} 42 -mf2 4 -` - out = model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value1", - }, - Value: -3.14, - Timestamp: 123456, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value2", - }, - Value: 42, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 3, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 4, - Timestamp: ts, - }, - } - ) - - dec := &SampleDecoder{ - Dec: &textDecoder{r: strings.NewReader(in)}, - Opts: &DecodeOptions{ - Timestamp: ts, - }, - } - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(out) - if !reflect.DeepEqual(all, out) { - t.Fatalf("output does not match") - } -} - -func TestProtoDecoder(t *testing.T) { - - var testTime = model.Now() - - scenarios := []struct { - in string - expected model.Vector - }{ - { - in: "", - }, - { - in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_label_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - }, - Value: 84, - Timestamp: testTime, - }, - }, - }, - { - in: "\xb9\x01\n\rrequest_count\x12\x12Number of requests\x18\x02\"O\n#\n\x0fsome_label_name\x12\x10some_label_value\"(\x1a\x12\t\xaeG\xe1z\x14\xae\xef?\x11\x00\x00\x00\x00\x00\x00E\xc0\x1a\x12\t+\x87\x16\xd9\xce\xf7\xef?\x11\x00\x00\x00\x00\x00\x00U\xc0\"A\n)\n\x12another_label_name\x12\x13another_label_value\"\x14\x1a\x12\t\x00\x00\x00\x00\x00\x00\xe0?\x11\x00\x00\x00\x00\x00\x00$@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.99", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.999", - }, - Value: -84, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - "quantile": "0.5", - }, - Value: 10, - Timestamp: testTime, - }, - }, - }, - { - in: "\x8d\x01\n\x1drequest_duration_microseconds\x12\x15The response latency.\x18\x04\"S:Q\b\x85\x15\x11\xcd\xcc\xccL\x8f\xcb:A\x1a\v\b{\x11\x00\x00\x00\x00\x00\x00Y@\x1a\f\b\x9c\x03\x11\x00\x00\x00\x00\x00\x00^@\x1a\f\b\xd0\x04\x11\x00\x00\x00\x00\x00\x00b@\x1a\f\b\xf4\v\x11\x9a\x99\x99\x99\x99\x99e@\x1a\f\b\x85\x15\x11\x00\x00\x00\x00\x00\x00\xf0\u007f", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "100", - }, - Value: 123, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "120", - }, - Value: 412, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "144", - }, - Value: 592, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "172.8", - }, - Value: 1524, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "+Inf", - }, - Value: 2693, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_sum", - }, - Value: 1756047.3, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_count", - }, - Value: 2693, - Timestamp: testTime, - }, - }, - }, - { - // The metric type is unset in this protobuf, which needs to be handled - // correctly by the decoder. - in: "\x1c\n\rrequest_count\"\v\x1a\t\t\x00\x00\x00\x00\x00\x00\xf0?", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - }, - Value: 1, - Timestamp: testTime, - }, - }, - }, - } - - for i, scenario := range scenarios { - dec := &SampleDecoder{ - Dec: &protoDecoder{r: strings.NewReader(scenario.in)}, - Opts: &DecodeOptions{ - Timestamp: testTime, - }, - } - - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(scenario.expected) - if !reflect.DeepEqual(all, scenario.expected) { - t.Fatalf("%d. output does not match, want: %#v, got %#v", i, scenario.expected, all) - } - } -} - -func testDiscriminatorHTTPHeader(t testing.TB) { - var scenarios = []struct { - input map[string]string - output Format - err error - }{ - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="delimited"`}, - output: FmtProtoDelim, - err: nil, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="illegal"; encoding="delimited"`}, - output: "", - err: errors.New("unrecognized protocol message illegal"), - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="illegal"`}, - output: "", - err: errors.New("unsupported encoding illegal"), - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.4`}, - output: FmtText, - err: nil, - }, - { - input: map[string]string{"Content-Type": `text/plain`}, - output: FmtText, - err: nil, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.3`}, - output: "", - err: errors.New("unrecognized protocol version 0.0.3"), - }, - } - - for i, scenario := range scenarios { - var header http.Header - - if len(scenario.input) > 0 { - header = http.Header{} - } - - for key, value := range scenario.input { - header.Add(key, value) - } - - actual, err := ResponseFormat(header) - - if scenario.err != err { - if scenario.err != nil && err != nil { - if scenario.err.Error() != err.Error() { - t.Errorf("%d. expected %s, got %s", i, scenario.err, err) - } - } else if scenario.err != nil || err != nil { - t.Errorf("%d. expected %s, got %s", i, scenario.err, err) - } - } - - if !reflect.DeepEqual(scenario.output, actual) { - t.Errorf("%d. expected %s, got %s", i, scenario.output, actual) - } - } -} - -func TestDiscriminatorHTTPHeader(t *testing.T) { - testDiscriminatorHTTPHeader(t) -} - -func BenchmarkDiscriminatorHTTPHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - testDiscriminatorHTTPHeader(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 deleted file mode 100644 index 139597f9c..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 deleted file mode 100644 index 2ae870679..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 +++ /dev/null @@ -1,6 +0,0 @@ - -minimal_metric 1.234 -another_metric -3e3 103948 -# Even that: -no_labels{} 3 -# HELP line for non-existing metric will be ignored. diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 deleted file mode 100644 index 5c351db36..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 +++ /dev/null @@ -1,12 +0,0 @@ - -# A normal comment. -# -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 -# HELP name two-line\n doc str\\ing - - # HELP name2 doc str"ing 2 - # TYPE name2 gauge -name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 -name2{ labelname = "val1" , }-Inf diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 deleted file mode 100644 index 0b3c345aa..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 +++ /dev/null @@ -1,22 +0,0 @@ - -# TYPE my_summary summary -my_summary{n1="val1",quantile="0.5"} 110 -decoy -1 -2 -my_summary{n1="val1",quantile="0.9"} 140 1 -my_summary_count{n1="val1"} 42 -# Latest timestamp wins in case of a summary. -my_summary_sum{n1="val1"} 4711 2 -fake_sum{n1="val1"} 2001 -# TYPE another_summary summary -another_summary_count{n2="val2",n1="val1"} 20 -my_summary_count{n2="val2",n1="val1"} 5 5 -another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 -my_summary_sum{n1="val2"} 08 15 -my_summary{n1="val3", quantile="0.2"} 4711 - my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN -# some -# funny comments -# HELP -# HELP -# HELP my_summary -# HELP my_summary diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 deleted file mode 100644 index bde0a387a..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 +++ /dev/null @@ -1,10 +0,0 @@ - -# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 deleted file mode 100644 index 4c67f9a19..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 +++ /dev/null @@ -1 +0,0 @@ -bla 3.14 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 deleted file mode 100644 index b853478ee..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 +++ /dev/null @@ -1 +0,0 @@ -metric{label="\t"} 3.14 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 deleted file mode 100644 index b5fe5f5a6..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"} 3.14 2 3 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 deleted file mode 100644 index 57c7fbc0b..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"} blubb diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 deleted file mode 100644 index 0a9df79a1..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 +++ /dev/null @@ -1,3 +0,0 @@ - -# HELP metric one -# HELP metric two diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 deleted file mode 100644 index 5bc742781..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 +++ /dev/null @@ -1,3 +0,0 @@ - -# TYPE metric counter -# TYPE metric untyped diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 deleted file mode 100644 index a9a24265b..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 +++ /dev/null @@ -1,3 +0,0 @@ - -metric 4.12 -# TYPE metric counter diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 deleted file mode 100644 index 7e95ca8f4..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 +++ /dev/null @@ -1,2 +0,0 @@ - -# TYPE metric bla diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 deleted file mode 100644 index 7825f8887..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 +++ /dev/null @@ -1,2 +0,0 @@ - -# TYPE met-ric diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 deleted file mode 100644 index 8f35cae0c..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 +++ /dev/null @@ -1 +0,0 @@ -@invalidmetric{label="bla"} 3.14 2 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 deleted file mode 100644 index 7ca2cc268..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 +++ /dev/null @@ -1 +0,0 @@ -{label="bla"} 3.14 2 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 deleted file mode 100644 index 7a6ccc0dd..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 +++ /dev/null @@ -1,3 +0,0 @@ - -# TYPE metric histogram -metric_bucket{le="bla"} 3.14 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 deleted file mode 100644 index 726d0017c..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 +++ /dev/null @@ -1,3 +0,0 @@ - -metric{label="new -line"} 3.14 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 deleted file mode 100644 index 6aa9e3081..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 +++ /dev/null @@ -1 +0,0 @@ -metric{@="bla"} 3.14 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 deleted file mode 100644 index d112cb902..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 +++ /dev/null @@ -1 +0,0 @@ -metric{__name__="bla"} 3.14 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 deleted file mode 100644 index b34554a8d..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 +++ /dev/null @@ -1 +0,0 @@ -metric{label+="bla"} 3.14 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 deleted file mode 100644 index c4d7df3d1..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 +++ /dev/null @@ -1 +0,0 @@ -metric{label=bla} 3.14 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 deleted file mode 100644 index 97eafc4a6..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 +++ /dev/null @@ -1,3 +0,0 @@ - -# TYPE metric summary -metric{quantile="bla"} 3.14 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 deleted file mode 100644 index fc706496b..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"+} 3.14 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 deleted file mode 100644 index 57b4879c0..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"} 3.14 2.72 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/minimal b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/minimal deleted file mode 100644 index be1e6a369..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/fuzz/corpus/minimal +++ /dev/null @@ -1 +0,0 @@ -m{} 0 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/json_decode_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/json_decode_test.go deleted file mode 100644 index c98ea29e1..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/json_decode_test.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2015 The Prometheus 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 expfmt - -import ( - "os" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func TestJSON2Decode(t *testing.T) { - f, err := os.Open("testdata/json2") - if err != nil { - t.Fatal(err) - } - defer f.Close() - - dec := newJSON2Decoder(f) - - var v1 dto.MetricFamily - if err := dec.Decode(&v1); err != nil { - t.Fatal(err) - } - - exp1 := dto.MetricFamily{ - Type: dto.MetricType_UNTYPED.Enum(), - Help: proto.String("RPC calls."), - Name: proto.String("rpc_calls_total"), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("job"), - Value: proto.String("batch_job"), - }, { - Name: proto.String("service"), - Value: proto.String("zed"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(25), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("job"), - Value: proto.String("batch_job"), - }, { - Name: proto.String("service"), - Value: proto.String("bar"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(24), - }, - }, - }, - } - - if !reflect.DeepEqual(v1, exp1) { - t.Fatalf("Expected %v, got %v", exp1, v1) - } - - var v2 dto.MetricFamily - if err := dec.Decode(&v2); err != nil { - t.Fatal(err) - } - - exp2 := dto.MetricFamily{ - Type: dto.MetricType_UNTYPED.Enum(), - Help: proto.String("RPC latency."), - Name: proto.String("rpc_latency_microseconds"), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("percentile"), - Value: proto.String("0.010000"), - }, { - Name: proto.String("service"), - Value: proto.String("foo"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(15), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("percentile"), - Value: proto.String("0.990000"), - }, { - Name: proto.String("service"), - Value: proto.String("foo"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(17), - }, - }, - }, - } - - if !reflect.DeepEqual(v2, exp2) { - t.Fatalf("Expected %v, got %v", exp2, v2) - } - -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/json2 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/json2 deleted file mode 100644 index b914c9386..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/json2 +++ /dev/null @@ -1,46 +0,0 @@ -[ - { - "baseLabels": { - "__name__": "rpc_calls_total", - "job": "batch_job" - }, - "docstring": "RPC calls.", - "metric": { - "type": "counter", - "value": [ - { - "labels": { - "service": "zed" - }, - "value": 25 - }, - { - "labels": { - "service": "bar" - }, - "value": 24 - } - ] - } - }, - { - "baseLabels": { - "__name__": "rpc_latency_microseconds" - }, - "docstring": "RPC latency.", - "metric": { - "type": "histogram", - "value": [ - { - "labels": { - "service": "foo" - }, - "value": { - "0.010000": 15, - "0.990000": 17 - } - } - ] - } - } -] diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf deleted file mode 100644 index d5aae5091..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf +++ /dev/null @@ -1,516 +0,0 @@ -fc08 0a22 6874 7470 5f72 6571 7565 7374 -5f64 7572 6174 696f 6e5f 6d69 6372 6f73 -6563 6f6e 6473 122b 5468 6520 4854 5450 -2072 6571 7565 7374 206c 6174 656e 6369 -6573 2069 6e20 6d69 6372 6f73 6563 6f6e -6473 2e18 0222 570a 0c0a 0768 616e 646c -6572 1201 2f22 4708 0011 0000 0000 0000 -0000 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0000 225d -0a12 0a07 6861 6e64 6c65 7212 072f 616c -6572 7473 2247 0800 1100 0000 0000 0000 -001a 1209 0000 0000 0000 e03f 1100 0000 -0000 0000 001a 1209 cdcc cccc cccc ec3f -1100 0000 0000 0000 001a 1209 ae47 e17a -14ae ef3f 1100 0000 0000 0000 0022 620a -170a 0768 616e 646c 6572 120c 2f61 7069 -2f6d 6574 7269 6373 2247 0800 1100 0000 -0000 0000 001a 1209 0000 0000 0000 e03f -1100 0000 0000 0000 001a 1209 cdcc cccc -cccc ec3f 1100 0000 0000 0000 001a 1209 -ae47 e17a 14ae ef3f 1100 0000 0000 0000 -0022 600a 150a 0768 616e 646c 6572 120a -2f61 7069 2f71 7565 7279 2247 0800 1100 -0000 0000 0000 001a 1209 0000 0000 0000 -e03f 1100 0000 0000 0000 001a 1209 cdcc -cccc cccc ec3f 1100 0000 0000 0000 001a -1209 ae47 e17a 14ae ef3f 1100 0000 0000 -0000 0022 660a 1b0a 0768 616e 646c 6572 -1210 2f61 7069 2f71 7565 7279 5f72 616e -6765 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 620a 170a -0768 616e 646c 6572 120c 2f61 7069 2f74 -6172 6765 7473 2247 0800 1100 0000 0000 -0000 001a 1209 0000 0000 0000 e03f 1100 -0000 0000 0000 001a 1209 cdcc cccc cccc -ec3f 1100 0000 0000 0000 001a 1209 ae47 -e17a 14ae ef3f 1100 0000 0000 0000 0022 -600a 150a 0768 616e 646c 6572 120a 2f63 -6f6e 736f 6c65 732f 2247 0800 1100 0000 -0000 0000 001a 1209 0000 0000 0000 e03f -1100 0000 0000 0000 001a 1209 cdcc cccc -cccc ec3f 1100 0000 0000 0000 001a 1209 -ae47 e17a 14ae ef3f 1100 0000 0000 0000 -0022 5c0a 110a 0768 616e 646c 6572 1206 -2f67 7261 7068 2247 0800 1100 0000 0000 -0000 001a 1209 0000 0000 0000 e03f 1100 -0000 0000 0000 001a 1209 cdcc cccc cccc -ec3f 1100 0000 0000 0000 001a 1209 ae47 -e17a 14ae ef3f 1100 0000 0000 0000 0022 -5b0a 100a 0768 616e 646c 6572 1205 2f68 -6561 7022 4708 0011 0000 0000 0000 0000 -1a12 0900 0000 0000 00e0 3f11 0000 0000 -0000 0000 1a12 09cd cccc cccc ccec 3f11 -0000 0000 0000 0000 1a12 09ae 47e1 7a14 -aeef 3f11 0000 0000 0000 0000 225e 0a13 -0a07 6861 6e64 6c65 7212 082f 7374 6174 -6963 2f22 4708 0011 0000 0000 0000 0000 -1a12 0900 0000 0000 00e0 3f11 0000 0000 -0000 0000 1a12 09cd cccc cccc ccec 3f11 -0000 0000 0000 0000 1a12 09ae 47e1 7a14 -aeef 3f11 0000 0000 0000 0000 2260 0a15 -0a07 6861 6e64 6c65 7212 0a70 726f 6d65 -7468 6575 7322 4708 3b11 5b8f c2f5 083f -f440 1a12 0900 0000 0000 00e0 3f11 e17a -14ae c7af 9340 1a12 09cd cccc cccc ccec -3f11 2fdd 2406 81f0 9640 1a12 09ae 47e1 -7a14 aeef 3f11 3d0a d7a3 b095 a740 e608 -0a17 6874 7470 5f72 6571 7565 7374 5f73 -697a 655f 6279 7465 7312 2054 6865 2048 -5454 5020 7265 7175 6573 7420 7369 7a65 -7320 696e 2062 7974 6573 2e18 0222 570a -0c0a 0768 616e 646c 6572 1201 2f22 4708 -0011 0000 0000 0000 0000 1a12 0900 0000 -0000 00e0 3f11 0000 0000 0000 0000 1a12 -09cd cccc cccc ccec 3f11 0000 0000 0000 -0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 -0000 0000 0000 225d 0a12 0a07 6861 6e64 -6c65 7212 072f 616c 6572 7473 2247 0800 -1100 0000 0000 0000 001a 1209 0000 0000 -0000 e03f 1100 0000 0000 0000 001a 1209 -cdcc cccc cccc ec3f 1100 0000 0000 0000 -001a 1209 ae47 e17a 14ae ef3f 1100 0000 -0000 0000 0022 620a 170a 0768 616e 646c -6572 120c 2f61 7069 2f6d 6574 7269 6373 -2247 0800 1100 0000 0000 0000 001a 1209 -0000 0000 0000 e03f 1100 0000 0000 0000 -001a 1209 cdcc cccc cccc ec3f 1100 0000 -0000 0000 001a 1209 ae47 e17a 14ae ef3f -1100 0000 0000 0000 0022 600a 150a 0768 -616e 646c 6572 120a 2f61 7069 2f71 7565 -7279 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 660a 1b0a -0768 616e 646c 6572 1210 2f61 7069 2f71 -7565 7279 5f72 616e 6765 2247 0800 1100 -0000 0000 0000 001a 1209 0000 0000 0000 -e03f 1100 0000 0000 0000 001a 1209 cdcc -cccc cccc ec3f 1100 0000 0000 0000 001a -1209 ae47 e17a 14ae ef3f 1100 0000 0000 -0000 0022 620a 170a 0768 616e 646c 6572 -120c 2f61 7069 2f74 6172 6765 7473 2247 -0800 1100 0000 0000 0000 001a 1209 0000 -0000 0000 e03f 1100 0000 0000 0000 001a -1209 cdcc cccc cccc ec3f 1100 0000 0000 -0000 001a 1209 ae47 e17a 14ae ef3f 1100 -0000 0000 0000 0022 600a 150a 0768 616e -646c 6572 120a 2f63 6f6e 736f 6c65 732f -2247 0800 1100 0000 0000 0000 001a 1209 -0000 0000 0000 e03f 1100 0000 0000 0000 -001a 1209 cdcc cccc cccc ec3f 1100 0000 -0000 0000 001a 1209 ae47 e17a 14ae ef3f -1100 0000 0000 0000 0022 5c0a 110a 0768 -616e 646c 6572 1206 2f67 7261 7068 2247 -0800 1100 0000 0000 0000 001a 1209 0000 -0000 0000 e03f 1100 0000 0000 0000 001a -1209 cdcc cccc cccc ec3f 1100 0000 0000 -0000 001a 1209 ae47 e17a 14ae ef3f 1100 -0000 0000 0000 0022 5b0a 100a 0768 616e -646c 6572 1205 2f68 6561 7022 4708 0011 -0000 0000 0000 0000 1a12 0900 0000 0000 -00e0 3f11 0000 0000 0000 0000 1a12 09cd -cccc cccc ccec 3f11 0000 0000 0000 0000 -1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 -0000 0000 225e 0a13 0a07 6861 6e64 6c65 -7212 082f 7374 6174 6963 2f22 4708 0011 -0000 0000 0000 0000 1a12 0900 0000 0000 -00e0 3f11 0000 0000 0000 0000 1a12 09cd -cccc cccc ccec 3f11 0000 0000 0000 0000 -1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 -0000 0000 2260 0a15 0a07 6861 6e64 6c65 -7212 0a70 726f 6d65 7468 6575 7322 4708 -3b11 0000 0000 40c4 d040 1a12 0900 0000 -0000 00e0 3f11 0000 0000 0030 7240 1a12 -09cd cccc cccc ccec 3f11 0000 0000 0030 -7240 1a12 09ae 47e1 7a14 aeef 3f11 0000 -0000 0030 7240 7c0a 1368 7474 705f 7265 -7175 6573 7473 5f74 6f74 616c 1223 546f -7461 6c20 6e75 6d62 6572 206f 6620 4854 -5450 2072 6571 7565 7374 7320 6d61 6465 -2e18 0022 3e0a 0b0a 0463 6f64 6512 0332 -3030 0a15 0a07 6861 6e64 6c65 7212 0a70 -726f 6d65 7468 6575 730a 0d0a 066d 6574 -686f 6412 0367 6574 1a09 0900 0000 0000 -804d 40e8 080a 1868 7474 705f 7265 7370 -6f6e 7365 5f73 697a 655f 6279 7465 7312 -2154 6865 2048 5454 5020 7265 7370 6f6e -7365 2073 697a 6573 2069 6e20 6279 7465 -732e 1802 2257 0a0c 0a07 6861 6e64 6c65 -7212 012f 2247 0800 1100 0000 0000 0000 -001a 1209 0000 0000 0000 e03f 1100 0000 -0000 0000 001a 1209 cdcc cccc cccc ec3f -1100 0000 0000 0000 001a 1209 ae47 e17a -14ae ef3f 1100 0000 0000 0000 0022 5d0a -120a 0768 616e 646c 6572 1207 2f61 6c65 -7274 7322 4708 0011 0000 0000 0000 0000 -1a12 0900 0000 0000 00e0 3f11 0000 0000 -0000 0000 1a12 09cd cccc cccc ccec 3f11 -0000 0000 0000 0000 1a12 09ae 47e1 7a14 -aeef 3f11 0000 0000 0000 0000 2262 0a17 -0a07 6861 6e64 6c65 7212 0c2f 6170 692f -6d65 7472 6963 7322 4708 0011 0000 0000 -0000 0000 1a12 0900 0000 0000 00e0 3f11 -0000 0000 0000 0000 1a12 09cd cccc cccc -ccec 3f11 0000 0000 0000 0000 1a12 09ae -47e1 7a14 aeef 3f11 0000 0000 0000 0000 -2260 0a15 0a07 6861 6e64 6c65 7212 0a2f -6170 692f 7175 6572 7922 4708 0011 0000 -0000 0000 0000 1a12 0900 0000 0000 00e0 -3f11 0000 0000 0000 0000 1a12 09cd cccc -cccc ccec 3f11 0000 0000 0000 0000 1a12 -09ae 47e1 7a14 aeef 3f11 0000 0000 0000 -0000 2266 0a1b 0a07 6861 6e64 6c65 7212 -102f 6170 692f 7175 6572 795f 7261 6e67 -6522 4708 0011 0000 0000 0000 0000 1a12 -0900 0000 0000 00e0 3f11 0000 0000 0000 -0000 1a12 09cd cccc cccc ccec 3f11 0000 -0000 0000 0000 1a12 09ae 47e1 7a14 aeef -3f11 0000 0000 0000 0000 2262 0a17 0a07 -6861 6e64 6c65 7212 0c2f 6170 692f 7461 -7267 6574 7322 4708 0011 0000 0000 0000 -0000 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0000 2260 -0a15 0a07 6861 6e64 6c65 7212 0a2f 636f -6e73 6f6c 6573 2f22 4708 0011 0000 0000 -0000 0000 1a12 0900 0000 0000 00e0 3f11 -0000 0000 0000 0000 1a12 09cd cccc cccc -ccec 3f11 0000 0000 0000 0000 1a12 09ae -47e1 7a14 aeef 3f11 0000 0000 0000 0000 -225c 0a11 0a07 6861 6e64 6c65 7212 062f -6772 6170 6822 4708 0011 0000 0000 0000 -0000 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0000 225b -0a10 0a07 6861 6e64 6c65 7212 052f 6865 -6170 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 5e0a 130a -0768 616e 646c 6572 1208 2f73 7461 7469 -632f 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 600a 150a -0768 616e 646c 6572 120a 7072 6f6d 6574 -6865 7573 2247 083b 1100 0000 00e0 b4fc -401a 1209 0000 0000 0000 e03f 1100 0000 -0000 349f 401a 1209 cdcc cccc cccc ec3f -1100 0000 0000 08a0 401a 1209 ae47 e17a -14ae ef3f 1100 0000 0000 0aa0 405c 0a19 -7072 6f63 6573 735f 6370 755f 7365 636f -6e64 735f 746f 7461 6c12 3054 6f74 616c -2075 7365 7220 616e 6420 7379 7374 656d -2043 5055 2074 696d 6520 7370 656e 7420 -696e 2073 6563 6f6e 6473 2e18 0022 0b1a -0909 a470 3d0a d7a3 d03f 4f0a 1270 726f -6365 7373 5f67 6f72 6f75 7469 6e65 7312 -2a4e 756d 6265 7220 6f66 2067 6f72 6f75 -7469 6e65 7320 7468 6174 2063 7572 7265 -6e74 6c79 2065 7869 7374 2e18 0122 0b12 -0909 0000 0000 0000 5140 4a0a 0f70 726f -6365 7373 5f6d 6178 5f66 6473 1228 4d61 -7869 6d75 6d20 6e75 6d62 6572 206f 6620 -6f70 656e 2066 696c 6520 6465 7363 7269 -7074 6f72 732e 1801 220b 1209 0900 0000 -0000 00c0 4043 0a10 7072 6f63 6573 735f -6f70 656e 5f66 6473 1220 4e75 6d62 6572 -206f 6620 6f70 656e 2066 696c 6520 6465 -7363 7269 7074 6f72 732e 1801 220b 1209 -0900 0000 0000 003d 404e 0a1d 7072 6f63 -6573 735f 7265 7369 6465 6e74 5f6d 656d -6f72 795f 6279 7465 7312 1e52 6573 6964 -656e 7420 6d65 6d6f 7279 2073 697a 6520 -696e 2062 7974 6573 2e18 0122 0b12 0909 -0000 0000 004b 8841 630a 1a70 726f 6365 -7373 5f73 7461 7274 5f74 696d 655f 7365 -636f 6e64 7312 3653 7461 7274 2074 696d -6520 6f66 2074 6865 2070 726f 6365 7373 -2073 696e 6365 2075 6e69 7820 6570 6f63 -6820 696e 2073 6563 6f6e 6473 2e18 0122 -0b12 0909 3d0a 172d e831 d541 4c0a 1c70 -726f 6365 7373 5f76 6972 7475 616c 5f6d -656d 6f72 795f 6279 7465 7312 1d56 6972 -7475 616c 206d 656d 6f72 7920 7369 7a65 -2069 6e20 6279 7465 732e 1801 220b 1209 -0900 0000 0020 12c0 415f 0a27 7072 6f6d -6574 6865 7573 5f64 6e73 5f73 645f 6c6f -6f6b 7570 5f66 6169 6c75 7265 735f 746f -7461 6c12 2554 6865 206e 756d 6265 7220 -6f66 2044 4e53 2d53 4420 6c6f 6f6b 7570 -2066 6169 6c75 7265 732e 1800 220b 1a09 -0900 0000 0000 0000 004f 0a1f 7072 6f6d -6574 6865 7573 5f64 6e73 5f73 645f 6c6f -6f6b 7570 735f 746f 7461 6c12 1d54 6865 -206e 756d 6265 7220 6f66 2044 4e53 2d53 -4420 6c6f 6f6b 7570 732e 1800 220b 1a09 -0900 0000 0000 0008 40cf 010a 2a70 726f -6d65 7468 6575 735f 6576 616c 7561 746f -725f 6475 7261 7469 6f6e 5f6d 696c 6c69 -7365 636f 6e64 7312 2c54 6865 2064 7572 -6174 696f 6e20 666f 7220 616c 6c20 6576 -616c 7561 7469 6f6e 7320 746f 2065 7865 -6375 7465 2e18 0222 7122 6f08 0b11 0000 -0000 0000 2240 1a12 097b 14ae 47e1 7a84 -3f11 0000 0000 0000 0000 1a12 099a 9999 -9999 99a9 3f11 0000 0000 0000 0000 1a12 -0900 0000 0000 00e0 3f11 0000 0000 0000 -0000 1a12 09cd cccc cccc ccec 3f11 0000 -0000 0000 f03f 1a12 09ae 47e1 7a14 aeef -3f11 0000 0000 0000 f03f a301 0a39 7072 -6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 -746f 7261 6765 5f63 6865 636b 706f 696e -745f 6475 7261 7469 6f6e 5f6d 696c 6c69 -7365 636f 6e64 7312 5754 6865 2064 7572 -6174 696f 6e20 2869 6e20 6d69 6c6c 6973 -6563 6f6e 6473 2920 6974 2074 6f6f 6b20 -746f 2063 6865 636b 706f 696e 7420 696e -2d6d 656d 6f72 7920 6d65 7472 6963 7320 -616e 6420 6865 6164 2063 6875 6e6b 732e -1801 220b 1209 0900 0000 0000 0000 00f2 -010a 2870 726f 6d65 7468 6575 735f 6c6f -6361 6c5f 7374 6f72 6167 655f 6368 756e -6b5f 6f70 735f 746f 7461 6c12 3354 6865 -2074 6f74 616c 206e 756d 6265 7220 6f66 -2063 6875 6e6b 206f 7065 7261 7469 6f6e -7320 6279 2074 6865 6972 2074 7970 652e -1800 221b 0a0e 0a04 7479 7065 1206 6372 -6561 7465 1a09 0900 0000 0000 b880 4022 -1c0a 0f0a 0474 7970 6512 0770 6572 7369 -7374 1a09 0900 0000 0000 c05b 4022 180a -0b0a 0474 7970 6512 0370 696e 1a09 0900 -0000 0000 807b 4022 1e0a 110a 0474 7970 -6512 0974 7261 6e73 636f 6465 1a09 0900 -0000 0000 a06b 4022 1a0a 0d0a 0474 7970 -6512 0575 6e70 696e 1a09 0900 0000 0000 -807b 40c4 010a 3c70 726f 6d65 7468 6575 -735f 6c6f 6361 6c5f 7374 6f72 6167 655f -696e 6465 7869 6e67 5f62 6174 6368 5f6c -6174 656e 6379 5f6d 696c 6c69 7365 636f -6e64 7312 3751 7561 6e74 696c 6573 2066 -6f72 2062 6174 6368 2069 6e64 6578 696e -6720 6c61 7465 6e63 6965 7320 696e 206d -696c 6c69 7365 636f 6e64 732e 1802 2249 -2247 0801 1100 0000 0000 0000 001a 1209 -0000 0000 0000 e03f 1100 0000 0000 0000 -001a 1209 cdcc cccc cccc ec3f 1100 0000 -0000 0000 001a 1209 ae47 e17a 14ae ef3f -1100 0000 0000 0000 00bf 010a 2d70 726f -6d65 7468 6575 735f 6c6f 6361 6c5f 7374 -6f72 6167 655f 696e 6465 7869 6e67 5f62 -6174 6368 5f73 697a 6573 1241 5175 616e -7469 6c65 7320 666f 7220 696e 6465 7869 -6e67 2062 6174 6368 2073 697a 6573 2028 -6e75 6d62 6572 206f 6620 6d65 7472 6963 -7320 7065 7220 6261 7463 6829 2e18 0222 -4922 4708 0111 0000 0000 0000 0040 1a12 -0900 0000 0000 00e0 3f11 0000 0000 0000 -0040 1a12 09cd cccc cccc ccec 3f11 0000 -0000 0000 0040 1a12 09ae 47e1 7a14 aeef -3f11 0000 0000 0000 0040 660a 3070 726f -6d65 7468 6575 735f 6c6f 6361 6c5f 7374 -6f72 6167 655f 696e 6465 7869 6e67 5f71 -7565 7565 5f63 6170 6163 6974 7912 2354 -6865 2063 6170 6163 6974 7920 6f66 2074 -6865 2069 6e64 6578 696e 6720 7175 6575 -652e 1801 220b 1209 0900 0000 0000 00d0 -406d 0a2e 7072 6f6d 6574 6865 7573 5f6c -6f63 616c 5f73 746f 7261 6765 5f69 6e64 -6578 696e 675f 7175 6575 655f 6c65 6e67 -7468 122c 5468 6520 6e75 6d62 6572 206f -6620 6d65 7472 6963 7320 7761 6974 696e -6720 746f 2062 6520 696e 6465 7865 642e -1801 220b 1209 0900 0000 0000 0000 0067 -0a2f 7072 6f6d 6574 6865 7573 5f6c 6f63 -616c 5f73 746f 7261 6765 5f69 6e67 6573 -7465 645f 7361 6d70 6c65 735f 746f 7461 -6c12 2554 6865 2074 6f74 616c 206e 756d -6265 7220 6f66 2073 616d 706c 6573 2069 -6e67 6573 7465 642e 1800 220b 1a09 0900 -0000 0080 27cd 40c3 010a 3770 726f 6d65 -7468 6575 735f 6c6f 6361 6c5f 7374 6f72 -6167 655f 696e 7661 6c69 645f 7072 656c -6f61 645f 7265 7175 6573 7473 5f74 6f74 -616c 1279 5468 6520 746f 7461 6c20 6e75 -6d62 6572 206f 6620 7072 656c 6f61 6420 -7265 7175 6573 7473 2072 6566 6572 7269 -6e67 2074 6f20 6120 6e6f 6e2d 6578 6973 -7465 6e74 2073 6572 6965 732e 2054 6869 -7320 6973 2061 6e20 696e 6469 6361 7469 -6f6e 206f 6620 6f75 7464 6174 6564 206c -6162 656c 2069 6e64 6578 6573 2e18 0022 -0b1a 0909 0000 0000 0000 0000 6f0a 2a70 -726f 6d65 7468 6575 735f 6c6f 6361 6c5f -7374 6f72 6167 655f 6d65 6d6f 7279 5f63 -6875 6e6b 6465 7363 7312 3254 6865 2063 -7572 7265 6e74 206e 756d 6265 7220 6f66 -2063 6875 6e6b 2064 6573 6372 6970 746f -7273 2069 6e20 6d65 6d6f 7279 2e18 0122 -0b12 0909 0000 0000 0020 8f40 9c01 0a26 -7072 6f6d 6574 6865 7573 5f6c 6f63 616c -5f73 746f 7261 6765 5f6d 656d 6f72 795f -6368 756e 6b73 1263 5468 6520 6375 7272 -656e 7420 6e75 6d62 6572 206f 6620 6368 -756e 6b73 2069 6e20 6d65 6d6f 7279 2c20 -6578 636c 7564 696e 6720 636c 6f6e 6564 -2063 6875 6e6b 7320 2869 2e65 2e20 6368 -756e 6b73 2077 6974 686f 7574 2061 2064 -6573 6372 6970 746f 7229 2e18 0122 0b12 -0909 0000 0000 00e8 8d40 600a 2670 726f -6d65 7468 6575 735f 6c6f 6361 6c5f 7374 -6f72 6167 655f 6d65 6d6f 7279 5f73 6572 -6965 7312 2754 6865 2063 7572 7265 6e74 -206e 756d 6265 7220 6f66 2073 6572 6965 -7320 696e 206d 656d 6f72 792e 1801 220b -1209 0900 0000 0000 807a 40b7 010a 3570 -726f 6d65 7468 6575 735f 6c6f 6361 6c5f -7374 6f72 6167 655f 7065 7273 6973 745f -6c61 7465 6e63 795f 6d69 6372 6f73 6563 -6f6e 6473 1231 4120 7375 6d6d 6172 7920 -6f66 206c 6174 656e 6369 6573 2066 6f72 -2070 6572 7369 7374 696e 6720 6561 6368 -2063 6875 6e6b 2e18 0222 4922 4708 6f11 -1c2f dd24 e68c cc40 1a12 0900 0000 0000 -00e0 3f11 8d97 6e12 8360 3e40 1a12 09cd -cccc cccc ccec 3f11 0ad7 a370 3d62 6b40 -1a12 09ae 47e1 7a14 aeef 3f11 7b14 ae47 -e1b6 7240 6a0a 2f70 726f 6d65 7468 6575 -735f 6c6f 6361 6c5f 7374 6f72 6167 655f -7065 7273 6973 745f 7175 6575 655f 6361 -7061 6369 7479 1228 5468 6520 746f 7461 -6c20 6361 7061 6369 7479 206f 6620 7468 -6520 7065 7273 6973 7420 7175 6575 652e -1801 220b 1209 0900 0000 0000 0090 407a -0a2d 7072 6f6d 6574 6865 7573 5f6c 6f63 -616c 5f73 746f 7261 6765 5f70 6572 7369 -7374 5f71 7565 7565 5f6c 656e 6774 6812 -3a54 6865 2063 7572 7265 6e74 206e 756d -6265 7220 6f66 2063 6875 6e6b 7320 7761 -6974 696e 6720 696e 2074 6865 2070 6572 -7369 7374 2071 7565 7565 2e18 0122 0b12 -0909 0000 0000 0000 0000 ac01 0a29 7072 -6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 -746f 7261 6765 5f73 6572 6965 735f 6f70 -735f 746f 7461 6c12 3454 6865 2074 6f74 -616c 206e 756d 6265 7220 6f66 2073 6572 -6965 7320 6f70 6572 6174 696f 6e73 2062 -7920 7468 6569 7220 7479 7065 2e18 0022 -1b0a 0e0a 0474 7970 6512 0663 7265 6174 -651a 0909 0000 0000 0000 0040 222a 0a1d -0a04 7479 7065 1215 6d61 696e 7465 6e61 -6e63 655f 696e 5f6d 656d 6f72 791a 0909 -0000 0000 0000 1440 d601 0a2d 7072 6f6d -6574 6865 7573 5f6e 6f74 6966 6963 6174 -696f 6e73 5f6c 6174 656e 6379 5f6d 696c -6c69 7365 636f 6e64 7312 584c 6174 656e -6379 2071 7561 6e74 696c 6573 2066 6f72 -2073 656e 6469 6e67 2061 6c65 7274 206e -6f74 6966 6963 6174 696f 6e73 2028 6e6f -7420 696e 636c 7564 696e 6720 6472 6f70 -7065 6420 6e6f 7469 6669 6361 7469 6f6e -7329 2e18 0222 4922 4708 0011 0000 0000 -0000 0000 1a12 0900 0000 0000 00e0 3f11 -0000 0000 0000 0000 1a12 09cd cccc cccc -ccec 3f11 0000 0000 0000 0000 1a12 09ae -47e1 7a14 aeef 3f11 0000 0000 0000 0000 -680a 2770 726f 6d65 7468 6575 735f 6e6f -7469 6669 6361 7469 6f6e 735f 7175 6575 -655f 6361 7061 6369 7479 122e 5468 6520 -6361 7061 6369 7479 206f 6620 7468 6520 -616c 6572 7420 6e6f 7469 6669 6361 7469 -6f6e 7320 7175 6575 652e 1801 220b 1209 -0900 0000 0000 0059 4067 0a25 7072 6f6d -6574 6865 7573 5f6e 6f74 6966 6963 6174 -696f 6e73 5f71 7565 7565 5f6c 656e 6774 -6812 2f54 6865 206e 756d 6265 7220 6f66 -2061 6c65 7274 206e 6f74 6966 6963 6174 -696f 6e73 2069 6e20 7468 6520 7175 6575 -652e 1801 220b 1209 0900 0000 0000 0000 -009e 020a 3070 726f 6d65 7468 6575 735f -7275 6c65 5f65 7661 6c75 6174 696f 6e5f -6475 7261 7469 6f6e 5f6d 696c 6c69 7365 -636f 6e64 7312 2354 6865 2064 7572 6174 -696f 6e20 666f 7220 6120 7275 6c65 2074 -6f20 6578 6563 7574 652e 1802 2260 0a15 -0a09 7275 6c65 5f74 7970 6512 0861 6c65 -7274 696e 6722 4708 3711 0000 0000 0000 -2840 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0840 2261 -0a16 0a09 7275 6c65 5f74 7970 6512 0972 -6563 6f72 6469 6e67 2247 0837 1100 0000 -0000 002e 401a 1209 0000 0000 0000 e03f -1100 0000 0000 0000 001a 1209 cdcc cccc -cccc ec3f 1100 0000 0000 0000 001a 1209 -ae47 e17a 14ae ef3f 1100 0000 0000 0008 -4069 0a29 7072 6f6d 6574 6865 7573 5f72 -756c 655f 6576 616c 7561 7469 6f6e 5f66 -6169 6c75 7265 735f 746f 7461 6c12 2d54 -6865 2074 6f74 616c 206e 756d 6265 7220 -6f66 2072 756c 6520 6576 616c 7561 7469 -6f6e 2066 6169 6c75 7265 732e 1800 220b -1a09 0900 0000 0000 0000 0060 0a21 7072 -6f6d 6574 6865 7573 5f73 616d 706c 6573 -5f71 7565 7565 5f63 6170 6163 6974 7912 -2c43 6170 6163 6974 7920 6f66 2074 6865 -2071 7565 7565 2066 6f72 2075 6e77 7269 -7474 656e 2073 616d 706c 6573 2e18 0122 -0b12 0909 0000 0000 0000 b040 da01 0a1f -7072 6f6d 6574 6865 7573 5f73 616d 706c -6573 5f71 7565 7565 5f6c 656e 6774 6812 -a701 4375 7272 656e 7420 6e75 6d62 6572 -206f 6620 6974 656d 7320 696e 2074 6865 -2071 7565 7565 2066 6f72 2075 6e77 7269 -7474 656e 2073 616d 706c 6573 2e20 4561 -6368 2069 7465 6d20 636f 6d70 7269 7365 -7320 616c 6c20 7361 6d70 6c65 7320 6578 -706f 7365 6420 6279 206f 6e65 2074 6172 -6765 7420 6173 206f 6e65 206d 6574 7269 -6320 6661 6d69 6c79 2028 692e 652e 206d -6574 7269 6373 206f 6620 7468 6520 7361 -6d65 206e 616d 6529 2e18 0122 0b12 0909 -0000 0000 0000 0000 d902 0a29 7072 6f6d -6574 6865 7573 5f74 6172 6765 745f 696e -7465 7276 616c 5f6c 656e 6774 685f 7365 -636f 6e64 7312 2141 6374 7561 6c20 696e -7465 7276 616c 7320 6265 7477 6565 6e20 -7363 7261 7065 732e 1802 2282 010a 0f0a -0869 6e74 6572 7661 6c12 0331 3573 226f -0804 1100 0000 0000 804d 401a 1209 7b14 -ae47 e17a 843f 1100 0000 0000 002c 401a -1209 9a99 9999 9999 a93f 1100 0000 0000 -002c 401a 1209 0000 0000 0000 e03f 1100 -0000 0000 002e 401a 1209 cdcc cccc cccc -ec3f 1100 0000 0000 002e 401a 1209 ae47 -e17a 14ae ef3f 1100 0000 0000 002e 4022 -8101 0a0e 0a08 696e 7465 7276 616c 1202 -3173 226f 083a 1100 0000 0000 003c 401a -1209 7b14 ae47 e17a 843f 1100 0000 0000 -0000 001a 1209 9a99 9999 9999 a93f 1100 -0000 0000 0000 001a 1209 0000 0000 0000 -e03f 1100 0000 0000 0000 001a 1209 cdcc -cccc cccc ec3f 1100 0000 0000 00f0 3f1a -1209 ae47 e17a 14ae ef3f 1100 0000 0000 -00f0 3f \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf.gz b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf.gz deleted file mode 100644 index 62fccb616..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf.gz +++ /dev/null @@ -1,129 +0,0 @@ -1f8b 0808 efa0 c754 0003 7072 6f74 6f62 -7566 00ed 594d 8c1c c515 9eb1 8d3d 5b86 -6037 265e 8c4d ca03 c4bb ceee cc9a 9f58 -01cc f6ca 4424 041b 8837 21c8 24ed daee -9a99 cef6 1f55 d578 c7e4 b004 0e39 8088 -8448 048a 124b 4442 9110 e110 25b9 c54a -9072 01c5 9724 4a24 2472 413e 448a 8592 -1b87 bcea aeda eeea 99d9 3530 49a4 68e7 -b0bb 5355 fdde abf7 bef7 bdf7 7a3f 6ca0 -664f 88c4 61f4 8994 72e1 7829 23c2 8f23 -27f4 5d16 73ea c691 c7ad cf2d f628 fed2 -e2e2 c358 9dc3 0111 3472 7dca b11f e1f2 -d9d6 e496 e6a3 e86a b4a3 4722 2fa0 ccaa -b79b f737 6abb 6bea b3cf 9ac8 ff78 6fbe -bcf6 cedb f2f3 7763 ed8d fbff 766e cf1b -ff28 d69a df44 5621 7847 9bc0 2fc1 c727 -7e09 ed2d c45f dd26 89df 0ea9 60be 3b46 -1d67 d0f5 850e 94e9 008f b2fe f834 74d0 -8d85 865d 8506 8791 a84b ffa3 de12 8475 -e938 2352 f116 208c c701 e563 84d4 e368 -77a1 617b bbcb 48d2 1b9f f4d3 6857 21fd -aa76 8f92 647c c2bf 85ae 2b84 37da 5c40 -e6ba 6374 8de9 fc84 c590 0c3d 9aca f0de -bdfb f40b bffd 5763 fe9f 7659 8314 f0fb -9fbf 6897 35b4 dfbd 65fb d397 7f60 9735 -1c43 7f7e f5cd 975e b3df 6fa0 bd06 fb70 -ff1c 7596 fa82 720b 0f50 8edc cce8 263b -b0c9 339b 3cb3 c933 5afa ff2f cfc8 13f6 -5b17 ed01 0d73 cc1e d090 af99 1a60 ed3b -e8ba 32cd 7047 c482 04d6 cd8b f217 8ed2 -7089 321c 770c bae1 3824 1e6d 4dd6 9af7 -a29d 689b 1b7b d4da 7adb dcdc 085b d135 -68bb fc33 f6ac ad00 cd7d 13b9 b5ab 27ec -4b0d 34a9 b4f3 0470 45cb 2c77 b0c4 72f9 -ee26 cd7d 02ec 6cd2 dc26 cd7d 6ce1 ff73 -9a7b ef17 1f0e d2dc 1d3f 19a4 b9c6 f941 -9a43 e7ed c7d1 0d20 d5a5 9c3b 6e92 3a6a -2053 6437 9793 5dca 81ea c006 ccfb 5cd0 -101f 7ff8 6b58 f821 d04e 4223 2169 676d -8eab 3577 028d fd34 91dd dac5 f987 90a5 -8577 6316 a7c2 8f80 bf0e 9f5c 23cf 6215 -8b1e 11d8 4d19 0391 411f d315 9f8b d664 -bdb9 d352 b458 7bc4 7e00 5dab e585 64c5 -e9c0 9439 7582 acf8 611a 9618 3906 ab70 -c70f 28f6 2877 999f 8898 7153 d405 fb38 -daa5 45c9 f399 2c7c f2a3 c838 669f 4407 -b40c 6062 df03 cb9d 9086 31e4 79ce d437 -7d55 2de3 7c39 e3e9 124d 97c4 7de5 7b0b -2eda a7c5 018e 9870 a48f 7544 accf 9f92 -6bb9 dfc1 4040 0156 a741 6ae4 529c 46fe -0aa6 49ec f68c 88e4 3a8e a1bd b397 8efc -71e1 41b4 5feb 78d2 6722 2581 69f1 81af -e7ab 1b1a 8cad 0b0b 0e3a 5420 d2f1 22b0 -db73 8238 5e4e 13a7 43fc 2005 af28 24dd -2a6b 5611 a2fb 4e9e 9a3d 751f cecf 627d -56c3 47a3 ff21 f499 51f2 b5dc 03eb c8ad -c86b d87f a8a3 c325 81f4 4912 a404 025b -7e81 1104 bef6 f88c 94ad b770 2786 1c08 -02ac 9e82 25c0 6c0c 38a5 6e2a a82c b94f -34e3 c64e 95ba 4d99 6c4f ed91 e9f6 ac91 -e2af bc2c 3f3f 9bff 88f4 7079 7e90 1e2e -cfbf 5a47 5f28 5d28 885d 8827 871b 912e -75dc 1e75 9793 d88f c488 fb3d 6adc 6f2a -7b27 536c 4f63 1fd0 068e 94b7 2c64 0118 -6615 3654 5dce 9801 58d5 8353 69b4 5cc9 -925a ed83 3a9a 5ac7 4878 0432 50c7 f376 -6993 a8b4 58d9 2199 924c f97d a92f f1ef -332c fa49 d66e dd88 3e85 b6c9 2fd6 7697 -5122 a88e faaf 57ed e67e 74ad dadc 0122 -38f0 8ade bd70 da6e 4eca 4e2d dbdd 9af8 -d15a 0ff6 94dd bc09 ca52 be33 21a0 6e73 -d9ce e9fd f3cb 7673 1ff4 6ff9 fe55 6964 -3efb 561d dd33 f2ce 7ee4 01bb 455d 6789 -08b7 e7e4 6fc5 fa66 6c8e 3e92 9248 00ff -f00c 78d9 49ac 1fac be48 2b9e 9330 fc32 -d486 fa58 aacf 6fea 68f6 4a6f 9175 a0d6 -8269 f69a c1b9 fd79 973a 5504 5623 08c2 -921f 991e b8c0 6071 cbd7 aa17 182c 6eb0 -d641 731b db0f 8d59 0a40 2409 717d d187 -061f 10a8 bf69 a65d bb48 76d8 44f8 453b -44ad 2b55 13d0 a82b 7a39 b50c fae1 2cf1 -85d4 0219 b7a4 9452 af9a 4f5d d45e 475b -17c6 10ea 399c 8449 60b2 6f35 abd4 11ac -9f29 b3e5 eaa1 77ec dfd5 d1d1 7514 010d -fa9e 9330 1ac4 c4ab 4e49 fd61 0ad5 d962 -5862 b443 1953 1726 388a a3d9 acec cb82 -092d 07e0 bb85 177b 3e98 2849 46fa c377 -73b2 9215 3a15 1ea4 8107 c9b0 4403 e5ac -8112 121b 8c6f de41 15be 8c5d 6495 e7d6 -6d59 ecf3 1e64 807f 4a8d 4096 76d9 d346 -70f0 0bf6 8fea e8b3 57a4 905b ee3a ca4a -1a66 a0c4 b841 ea49 37b9 411c 51cd b3c0 -d82d dad2 5fce fa30 47a6 02dc 58d8 396d -5877 e979 fbcc c6c6 e57e b70e 0d37 2edf -1d71 fdd5 73f6 afea e8ce 911a 14f9 9608 -aff4 df82 230b 98a7 6148 5896 7305 c149 -1a51 0f4a 0f50 023c 925d 5933 45bc 7b7f -fbdd 5bde 7fee 6d83 299e ff61 643d 73e6 -5e83 29a0 254d 8e2d 2d1b 4c91 95e8 5f32 -fbdb eb24 95b6 bb42 1453 05c6 ab74 a19e -18c6 16df b7cf ad43 aaa6 2a45 1677 ad0b -14cd 1910 930d 54d7 6aaf d7d1 f448 dd79 -6c4b b5f8 8ea1 ac91 23e0 6315 6360 e4e6 -6174 406d 5e1f 12e8 2768 44a0 7905 3e51 -005c 3bbb c7fe 9359 7ea2 58f8 1d45 007c -78d5 fcc6 83f9 2adc be5c 8638 8db2 f4c9 -de55 6043 0e54 a358 f634 3ac3 3c16 2709 -a498 7168 ad2a 8d67 a8eb 196d b379 ad0a -c65a c38a d1b0 6b0c 09f7 6376 17dd ba81 -2285 b0b6 598e 8629 50f0 1a0a ab1f 6f31 -ea2c 4b03 ea14 6df2 88ee f3e6 c1ee 1acb -272b 4db5 1c80 2732 8919 681a 996d 1029 -88c6 51e5 d1a9 613d c215 46a3 6137 09fa -7459 c304 0303 9967 aa68 7d22 15be 9175 -55f7 5426 a5d9 6159 9739 a678 66e4 c474 -061d 2c69 d24d 4005 5433 c72b 80ca f6b3 -10a4 d159 e60b c821 dd1d 98a1 7ed3 fe6b -dd98 c94c 0d0a 4daf d58f 0f90 952f 6868 -8268 843e fc45 c9f0 f238 76e3 3061 8017 -9ecd 5dba 5da1 2b09 140d 4fd2 0e14 439c -bfee c284 67df f246 0adc 0350 ebab 02a9 -9b2b 7559 9003 5887 1fd3 5518 ff65 8b11 -a75c b223 398a 81e7 d5ed d6e6 f183 0b6e -3628 eb7d 2042 2ace 5279 1597 9124 7f0b -fbdd 3acc 1e0d 7dc4 da7a e44e 0e43 e2b6 -1c19 ab27 860c 8933 f6e0 9038 3304 7dad -214d 706b 4813 dcb2 9b4f d781 900b 23b6 -1c91 36dc a5f6 eff9 af0c aaff 06f1 48e5 -4433 2000 00 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/test.gz b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/test.gz deleted file mode 100644 index 3f8199dfb..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/test.gz +++ /dev/null @@ -1,163 +0,0 @@ -1f8b 0808 2aa1 c754 0003 7465 7874 00b5 -5b5d 939b 3816 7def 5fa1 ea79 99a9 4d3c -601b db3c f4c3 5426 55f3 309b ca6e 7ab7 -6a9e 281a d436 150c 04c4 a4bd 5df3 dff7 -4a88 361f 025d 094f 1e92 34e8 1cae 8ea4 -ab7b 04fd 03f9 ede3 ef9f c989 b122 28e9 -b79a 562c 88eb 3264 499e 05e7 242a f38a -4679 1657 e4f1 44c9 6f8f 8f9f 896c 46d2 -90d1 2c4a 6845 928c 749b aeee 7e20 8f7f -7cfe 8861 adea f339 2c2f 77fa a6af a730 -8b53 5a3e dcff 7cff ee5b 1d66 2c49 e9c3 -bdb3 f2ee ff22 ce12 027f 3101 9621 80ee -7659 90a8 28af 3366 8eeb 2042 f887 558b -7553 d158 a8a7 a4b1 d450 7259 2a69 84ee -e28a e4e7 3365 6512 dd40 d429 2e1b 6527 -b96c e5ed 10da 6a6c 4c31 0043 cbf2 7213 -9915 4c96 22ab 9816 48dc d02d 10d8 8440 -050d ca30 3bd2 db89 ace2 5b22 b592 6fa9 -e092 74a9 ec46 3403 0216 9647 7a8b cc3c -c565 29ba 9a6b 81e0 2de1 02b1 cd28 3a60 -f8b9 ca53 5a2d 2f1c 2698 2c44 9e62 b294 -f84a 6729 b029 4107 7a2c c3e2 b458 5a05 -8b85 ac2a 164b 491b 2a4b 394d c01d d889 -86c5 6225 c724 1642 2a48 2c75 144c 9632 -1a60 3ba8 8ac1 ed68 f96a 57f2 5868 a9e6 -b194 b325 b354 d40c 7e05 1665 0e45 dc89 -d68a bdca dd38 fbd5 7aef dd84 90cb e21e -bcc3 6ab7 59df 8690 336e 9cc3 7eb5 396c -8df5 eeb0 425c 7bff 70d8 ad3c 47fe 712d -46a0 4fe8 fa60 96c7 16bc 4afe 4783 a70b -a30a dfcd ef09 cf2d eeab cd76 07af 74d8 -d7fb 26b6 1a81 524c 6a0c 6a16 a675 cd9d -a67a abac 0c07 e98f d158 ac0c 5827 3c29 -c694 819d 9144 0fb1 34ba 6604 6889 4c2c -edb4 4e73 2674 4e2c 1cce cab1 9ac0 4dd4 -427a d359 ad26 fca4 4629 2d6a 81f5 3427 -31d6 0c6b 32f5 ca4d 5942 8c7e 7aac a587 -3423 3051 0fed 1667 959b f477 1ad5 1038 -2b33 6802 c7aa 6560 fb26 b59a b16a 334a -a150 c6ae 0e0b c5ea 83f4 6f93 da4c f8ae -195d b408 537b 8644 6215 c119 b149 41d4 -0e6a 460f 1dc0 c267 e1c1 5851 d08e 6a52 -9749 1f34 230d 0283 334c 6bdf b527 f017 -1368 1866 0cd0 66bb 3d1c b07a 619c 4e15 -b09c 8529 7914 7f67 f5f9 8996 247f ee39 -9e8a 9cc3 982a 8d4e 0b17 4fa6 e59d e2de -6b94 c7d0 edb5 e3dc bf53 4ac3 ff93 c70f -f7b0 8728 e3ac 0ac8 9c74 c292 3537 359e -6ccc 3030 65a3 0638 5786 87f9 96b0 79dc -8c31 1bb7 9d73 6673 1169 ad99 2918 ad85 -de9c e914 195b 2dbd 2e08 8cb1 3fb3 62c0 -eb84 7368 5ab1 d456 0ba1 1812 6868 d22c -f046 9269 6d1a 46b0 91e3 c2c9 a587 5939 -356b 1673 e1f4 5e0d 2ddf d870 1988 8800 -1bdb 352b 0623 0911 860d 239f c279 e1a4 -c300 0d3d 9b05 1e2d 19ca b5e9 0453 1a30 -bd5c 3898 8171 33c4 a245 d25a 379d 4023 -27a6 1747 0fc1 bb37 3328 5a16 9d7f d3a9 -32f4 637a 51b4 0823 0b67 8c46 2b83 3071 -3a71 148e 4caf 0f06 84f4 71ce d65f 4021 -7c98 e31d 9650 341c bb2d 52b1 9e27 5b6f -f79d 7758 5ae1 a6fc 1c5c 8f68 05cd 8b3a -685f 7a75 5d5d 5d81 a703 1252 5d2a 46cf -e4c3 e7ff 1096 9cc1 3515 3463 dc35 0d3f -1c9d 666c 8dde 740b 1819 6f18 d931 2ff3 -9a25 1938 af4f 6f16 b373 919d 4246 a2ba -2c21 9ef4 42e8 4b52 b151 309d f6c7 b03e -d23b c58d bd33 7cf4 397c 099e e38a fc33 -7c49 cef5 b963 7173 e83d 7986 7124 31ad -a232 2958 5e8e 2568 f1fd 47b6 570f aebf -1e3e 91f3 8a9b 9f0c 1ff5 06ec 3feb edf2 -7a34 e230 6992 1834 0bce f49c 432d d498 -db7f cbab a4b9 2acc f1d8 1bcf 73f4 4350 -b7f1 569b c3de f1fc 35fd 87b3 1f86 068b -bc64 019f 66ed fc20 5ff8 a566 e681 2630 -91db c610 6116 5152 67c9 0ba1 451e 9de6 -e6a4 82b8 1fac a281 bbda aed7 9bdd c1df -1e36 3b88 7624 e49f 49c9 ea30 edf7 efbf -cd45 9c8c 4a86 7e60 ca26 de6a eb6e f707 -dfe5 2a1e 3a71 c9a5 1ec4 1974 290e d23c -ff5a 17c1 7398 a435 0c47 bbc0 41c4 eb8c -fef5 d397 f75f 7e25 4d53 d236 ed86 8a22 -edac 7154 7b47 1735 225a 7d94 d8e8 da76 -7b45 54f4 cf30 ad43 587c dd4f 05d2 34e9 -7e63 dfde 21cf 3964 cd34 2512 0497 2051 -e590 9c68 5433 aa8a 5747 df9e 3ae1 21af -ddbd c671 c596 698b f696 a017 81c5 2725 -d660 5334 df70 89bb 3641 8839 45d6 1bc5 -9449 f308 966c 05d8 f048 83e8 44a3 af45 -9e64 0c33 837e 14bf 9871 bdfb 1349 20ff -c12c e5f3 e84a 0549 e5bd cc31 f218 45ec -d650 46c6 d0aa cebe 2a17 8761 606f a9c8 -12af 5ae4 430a 0815 76ab ee6a 6783 6365 -d186 6f87 a55c 504f 17be 1124 2561 9742 -b9a6 e69f a148 06b3 8057 fe98 87fb a8a4 -21e3 8706 9e7f 30c5 42ec 1594 27e2 6ba4 -ad31 38c9 00e8 af1d 5320 2bc3 ace2 27e9 -00df ba9e 29bc ceae 4fd6 8d63 92c5 5080 -65c7 e029 64d1 2968 7ecd e8d2 9f0d ff92 -0bb4 1259 5234 242d 6ef8 8b49 5798 7e7c -31cf 5664 5163 92f9 dcb6 8cce bf31 dd72 -3e91 1117 5234 29d2 359d 3dcd 8b99 fe74 -799b 28cd bc69 9afc 784d 126d 1284 95d6 -34f9 c978 e234 9ca6 3345 a046 5363 bd00 -ef2f c55b 1088 d136 c518 0fef b79a d690 -6dc2 228c 1276 11c9 feed 0759 ddbf 8db3 -686b 3086 036e cdd6 3505 7377 fc7b 53c3 -0ea5 343b b2d3 a052 6d27 e4f7 3061 bc3f -b07b 3fc9 eed1 d8b8 5ff2 1166 bd92 204c -f63e 5270 f971 5085 e722 a573 9bb1 6c41 -5a08 a627 4a72 ed2e 3c81 db38 dbbd bee6 -4a32 a8de 9238 284a 9ae6 613c 7a73 ade8 -996c 7a7d 815d d267 5a96 72ec 4292 e5d9 -7b71 c8c0 5d72 454b d8ab 5640 9480 16bc -f6e2 439b 444d 0dc7 dd7b cd62 4889 316c -6c4f 3495 e38e dacc 6603 47a8 368b d7cf -0569 3445 49c0 0f1e 9af2 549e b38c aab2 -ced1 84d8 b805 58df cbf1 4334 337b 0c70 -1dcf 37ea cc6c 473a d1bf 03b7 16a5 75cc -073e 4af3 8cb6 0535 94e6 2bba 6a7f f89e -b013 0c32 4c8c ab06 883d a71f 9141 af79 -8f11 8598 8434 f373 a2c7 f2a6 f978 4920 -2e6a d978 bbd6 e753 591e 778a 88ce 6f9b -ffd2 6ec9 3cf4 6b99 c88b 0289 e323 4543 -a80a 8450 fade cc3e 4ebb ffcf a147 75c0 -c659 6df6 fb1b 9035 47c6 9b95 b7f1 6fc1 -26e8 76eb dd6a bbdb d8f1 3515 8303 c3bb -9af5 16b3 1cb2 82d8 e3a7 88a2 8490 9971 -5048 4800 b68e 98e0 d74c f509 14ac 54d3 -1e75 6a88 c914 d596 12b0 7017 f710 5750 -2831 fa24 d42c 7d8d ad97 f9c1 ded7 8f9e -a2dd 1c87 88a1 b39f 2980 27a0 e730 8147 -6661 16f1 ad57 a63e f1a6 4521 5296 b3e4 -59d6 0895 daa7 fede 5c24 df7a e6a7 a299 -d88e c467 46a4 4703 1e28 e787 41ed 8e15 -9779 51c0 96d5 6ba4 dc97 10d1 2872 a11e -356f 930d f123 1f6b 8ab7 2018 3b5f 04a6 -c964 aaa5 d107 232c 906a 9427 d7f8 2cfb -6875 cfb6 761d 6cf8 4ac3 a30a 5b66 2aa3 -e8a7 32d3 4c5b 55dc 659d d2e0 7a0c 8f3e -bc27 1ca8 39b3 c771 2b56 0f0a f82a 5a35 -f945 880a eb5a f5ae fff6 bca3 c572 2bde -d189 048a 58bc 0557 91ff 3538 aac7 b135 -6fc6 27f8 fa25 8c71 bf4b b854 c67f c340 -4d10 2f1f a929 62f1 8bb7 8b87 eaca 0eda -9a4b 3b1e ab1e a1eb 2116 bce2 ade7 b004 -114b fd0a 997d fba9 a157 d41e 1a84 2a69 -b547 1d83 ccfc 61b0 4388 db22 5dd5 d9f7 -3261 b01f b507 33aa d027 5847 1976 a2dd -d6f1 77da 5865 26fe 30aa 5d13 46cf fd8d -6022 70f2 915b 38de 1cc4 3c17 25cc 854a -bc4b 6d8f 9ce8 4b01 c621 e665 22b8 72d2 -7c8e 48c2 4afc d41c b7c1 08c2 34ba 48a7 -de1e c149 d580 07f6 2bf8 4b59 0e29 bba3 -9168 66fb 69a2 0b78 7558 c214 904d df3e -2ef8 2512 5f09 b4b7 a1f6 a5ec 3be5 6a44 -6558 a887 5143 a9d8 6ee6 11af edf5 877b -d71b 7ca2 245e 1bbb db1b 9179 3724 f346 -19c5 9ecb bf25 9729 9948 997d 42fe 7ad0 -84a1 c992 238e b55d 8f54 53c0 b90d d568 -1fb4 a6ba 1dd3 e813 017b 2643 aae1 c8f3 -41f3 168d 7bf3 71df feee ff2d f9e8 431a -5200 00 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/text b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/text deleted file mode 100644 index f3d8c3784..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/text +++ /dev/null @@ -1,322 +0,0 @@ -# HELP http_request_duration_microseconds The HTTP request latencies in microseconds. -# TYPE http_request_duration_microseconds summary -http_request_duration_microseconds{handler="/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/"} 0 -http_request_duration_microseconds_count{handler="/"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/alerts"} 0 -http_request_duration_microseconds_count{handler="/alerts"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/metrics"} 0 -http_request_duration_microseconds_count{handler="/api/metrics"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/query"} 0 -http_request_duration_microseconds_count{handler="/api/query"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/query_range"} 0 -http_request_duration_microseconds_count{handler="/api/query_range"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/targets"} 0 -http_request_duration_microseconds_count{handler="/api/targets"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/consoles/"} 0 -http_request_duration_microseconds_count{handler="/consoles/"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/graph"} 0 -http_request_duration_microseconds_count{handler="/graph"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/heap"} 0 -http_request_duration_microseconds_count{handler="/heap"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/static/"} 0 -http_request_duration_microseconds_count{handler="/static/"} 0 -http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 1307.275 -http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 1858.632 -http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 3087.384 -http_request_duration_microseconds_sum{handler="prometheus"} 179886.5000000001 -http_request_duration_microseconds_count{handler="prometheus"} 119 -# HELP http_request_size_bytes The HTTP request sizes in bytes. -# TYPE http_request_size_bytes summary -http_request_size_bytes{handler="/",quantile="0.5"} 0 -http_request_size_bytes{handler="/",quantile="0.9"} 0 -http_request_size_bytes{handler="/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/"} 0 -http_request_size_bytes_count{handler="/"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.5"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.9"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/alerts"} 0 -http_request_size_bytes_count{handler="/alerts"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/metrics"} 0 -http_request_size_bytes_count{handler="/api/metrics"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/query"} 0 -http_request_size_bytes_count{handler="/api/query"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/query_range"} 0 -http_request_size_bytes_count{handler="/api/query_range"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/targets"} 0 -http_request_size_bytes_count{handler="/api/targets"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.5"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.9"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/consoles/"} 0 -http_request_size_bytes_count{handler="/consoles/"} 0 -http_request_size_bytes{handler="/graph",quantile="0.5"} 0 -http_request_size_bytes{handler="/graph",quantile="0.9"} 0 -http_request_size_bytes{handler="/graph",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/graph"} 0 -http_request_size_bytes_count{handler="/graph"} 0 -http_request_size_bytes{handler="/heap",quantile="0.5"} 0 -http_request_size_bytes{handler="/heap",quantile="0.9"} 0 -http_request_size_bytes{handler="/heap",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/heap"} 0 -http_request_size_bytes_count{handler="/heap"} 0 -http_request_size_bytes{handler="/static/",quantile="0.5"} 0 -http_request_size_bytes{handler="/static/",quantile="0.9"} 0 -http_request_size_bytes{handler="/static/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/static/"} 0 -http_request_size_bytes_count{handler="/static/"} 0 -http_request_size_bytes{handler="prometheus",quantile="0.5"} 291 -http_request_size_bytes{handler="prometheus",quantile="0.9"} 291 -http_request_size_bytes{handler="prometheus",quantile="0.99"} 291 -http_request_size_bytes_sum{handler="prometheus"} 34488 -http_request_size_bytes_count{handler="prometheus"} 119 -# HELP http_requests_total Total number of HTTP requests made. -# TYPE http_requests_total counter -http_requests_total{code="200",handler="prometheus",method="get"} 119 -# HELP http_response_size_bytes The HTTP response sizes in bytes. -# TYPE http_response_size_bytes summary -http_response_size_bytes{handler="/",quantile="0.5"} 0 -http_response_size_bytes{handler="/",quantile="0.9"} 0 -http_response_size_bytes{handler="/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/"} 0 -http_response_size_bytes_count{handler="/"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.5"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.9"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/alerts"} 0 -http_response_size_bytes_count{handler="/alerts"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/metrics"} 0 -http_response_size_bytes_count{handler="/api/metrics"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/query"} 0 -http_response_size_bytes_count{handler="/api/query"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/query_range"} 0 -http_response_size_bytes_count{handler="/api/query_range"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/targets"} 0 -http_response_size_bytes_count{handler="/api/targets"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.5"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.9"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/consoles/"} 0 -http_response_size_bytes_count{handler="/consoles/"} 0 -http_response_size_bytes{handler="/graph",quantile="0.5"} 0 -http_response_size_bytes{handler="/graph",quantile="0.9"} 0 -http_response_size_bytes{handler="/graph",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/graph"} 0 -http_response_size_bytes_count{handler="/graph"} 0 -http_response_size_bytes{handler="/heap",quantile="0.5"} 0 -http_response_size_bytes{handler="/heap",quantile="0.9"} 0 -http_response_size_bytes{handler="/heap",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/heap"} 0 -http_response_size_bytes_count{handler="/heap"} 0 -http_response_size_bytes{handler="/static/",quantile="0.5"} 0 -http_response_size_bytes{handler="/static/",quantile="0.9"} 0 -http_response_size_bytes{handler="/static/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/static/"} 0 -http_response_size_bytes_count{handler="/static/"} 0 -http_response_size_bytes{handler="prometheus",quantile="0.5"} 2049 -http_response_size_bytes{handler="prometheus",quantile="0.9"} 2058 -http_response_size_bytes{handler="prometheus",quantile="0.99"} 2064 -http_response_size_bytes_sum{handler="prometheus"} 247001 -http_response_size_bytes_count{handler="prometheus"} 119 -# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. -# TYPE process_cpu_seconds_total counter -process_cpu_seconds_total 0.55 -# HELP go_goroutines Number of goroutines that currently exist. -# TYPE go_goroutines gauge -go_goroutines 70 -# HELP process_max_fds Maximum number of open file descriptors. -# TYPE process_max_fds gauge -process_max_fds 8192 -# HELP process_open_fds Number of open file descriptors. -# TYPE process_open_fds gauge -process_open_fds 29 -# HELP process_resident_memory_bytes Resident memory size in bytes. -# TYPE process_resident_memory_bytes gauge -process_resident_memory_bytes 5.3870592e+07 -# HELP process_start_time_seconds Start time of the process since unix epoch in seconds. -# TYPE process_start_time_seconds gauge -process_start_time_seconds 1.42236894836e+09 -# HELP process_virtual_memory_bytes Virtual memory size in bytes. -# TYPE process_virtual_memory_bytes gauge -process_virtual_memory_bytes 5.41478912e+08 -# HELP prometheus_dns_sd_lookup_failures_total The number of DNS-SD lookup failures. -# TYPE prometheus_dns_sd_lookup_failures_total counter -prometheus_dns_sd_lookup_failures_total 0 -# HELP prometheus_dns_sd_lookups_total The number of DNS-SD lookups. -# TYPE prometheus_dns_sd_lookups_total counter -prometheus_dns_sd_lookups_total 7 -# HELP prometheus_evaluator_duration_milliseconds The duration for all evaluations to execute. -# TYPE prometheus_evaluator_duration_milliseconds summary -prometheus_evaluator_duration_milliseconds{quantile="0.01"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.05"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.5"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.9"} 1 -prometheus_evaluator_duration_milliseconds{quantile="0.99"} 1 -prometheus_evaluator_duration_milliseconds_sum 12 -prometheus_evaluator_duration_milliseconds_count 23 -# HELP prometheus_local_storage_checkpoint_duration_milliseconds The duration (in milliseconds) it took to checkpoint in-memory metrics and head chunks. -# TYPE prometheus_local_storage_checkpoint_duration_milliseconds gauge -prometheus_local_storage_checkpoint_duration_milliseconds 0 -# HELP prometheus_local_storage_chunk_ops_total The total number of chunk operations by their type. -# TYPE prometheus_local_storage_chunk_ops_total counter -prometheus_local_storage_chunk_ops_total{type="create"} 598 -prometheus_local_storage_chunk_ops_total{type="persist"} 174 -prometheus_local_storage_chunk_ops_total{type="pin"} 920 -prometheus_local_storage_chunk_ops_total{type="transcode"} 415 -prometheus_local_storage_chunk_ops_total{type="unpin"} 920 -# HELP prometheus_local_storage_indexing_batch_latency_milliseconds Quantiles for batch indexing latencies in milliseconds. -# TYPE prometheus_local_storage_indexing_batch_latency_milliseconds summary -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.5"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.9"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.99"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds_sum 0 -prometheus_local_storage_indexing_batch_latency_milliseconds_count 1 -# HELP prometheus_local_storage_indexing_batch_sizes Quantiles for indexing batch sizes (number of metrics per batch). -# TYPE prometheus_local_storage_indexing_batch_sizes summary -prometheus_local_storage_indexing_batch_sizes{quantile="0.5"} 2 -prometheus_local_storage_indexing_batch_sizes{quantile="0.9"} 2 -prometheus_local_storage_indexing_batch_sizes{quantile="0.99"} 2 -prometheus_local_storage_indexing_batch_sizes_sum 2 -prometheus_local_storage_indexing_batch_sizes_count 1 -# HELP prometheus_local_storage_indexing_queue_capacity The capacity of the indexing queue. -# TYPE prometheus_local_storage_indexing_queue_capacity gauge -prometheus_local_storage_indexing_queue_capacity 16384 -# HELP prometheus_local_storage_indexing_queue_length The number of metrics waiting to be indexed. -# TYPE prometheus_local_storage_indexing_queue_length gauge -prometheus_local_storage_indexing_queue_length 0 -# HELP prometheus_local_storage_ingested_samples_total The total number of samples ingested. -# TYPE prometheus_local_storage_ingested_samples_total counter -prometheus_local_storage_ingested_samples_total 30473 -# HELP prometheus_local_storage_invalid_preload_requests_total The total number of preload requests referring to a non-existent series. This is an indication of outdated label indexes. -# TYPE prometheus_local_storage_invalid_preload_requests_total counter -prometheus_local_storage_invalid_preload_requests_total 0 -# HELP prometheus_local_storage_memory_chunkdescs The current number of chunk descriptors in memory. -# TYPE prometheus_local_storage_memory_chunkdescs gauge -prometheus_local_storage_memory_chunkdescs 1059 -# HELP prometheus_local_storage_memory_chunks The current number of chunks in memory, excluding cloned chunks (i.e. chunks without a descriptor). -# TYPE prometheus_local_storage_memory_chunks gauge -prometheus_local_storage_memory_chunks 1020 -# HELP prometheus_local_storage_memory_series The current number of series in memory. -# TYPE prometheus_local_storage_memory_series gauge -prometheus_local_storage_memory_series 424 -# HELP prometheus_local_storage_persist_latency_microseconds A summary of latencies for persisting each chunk. -# TYPE prometheus_local_storage_persist_latency_microseconds summary -prometheus_local_storage_persist_latency_microseconds{quantile="0.5"} 30.377 -prometheus_local_storage_persist_latency_microseconds{quantile="0.9"} 203.539 -prometheus_local_storage_persist_latency_microseconds{quantile="0.99"} 2626.463 -prometheus_local_storage_persist_latency_microseconds_sum 20424.415 -prometheus_local_storage_persist_latency_microseconds_count 174 -# HELP prometheus_local_storage_persist_queue_capacity The total capacity of the persist queue. -# TYPE prometheus_local_storage_persist_queue_capacity gauge -prometheus_local_storage_persist_queue_capacity 1024 -# HELP prometheus_local_storage_persist_queue_length The current number of chunks waiting in the persist queue. -# TYPE prometheus_local_storage_persist_queue_length gauge -prometheus_local_storage_persist_queue_length 0 -# HELP prometheus_local_storage_series_ops_total The total number of series operations by their type. -# TYPE prometheus_local_storage_series_ops_total counter -prometheus_local_storage_series_ops_total{type="create"} 2 -prometheus_local_storage_series_ops_total{type="maintenance_in_memory"} 11 -# HELP prometheus_notifications_latency_milliseconds Latency quantiles for sending alert notifications (not including dropped notifications). -# TYPE prometheus_notifications_latency_milliseconds summary -prometheus_notifications_latency_milliseconds{quantile="0.5"} 0 -prometheus_notifications_latency_milliseconds{quantile="0.9"} 0 -prometheus_notifications_latency_milliseconds{quantile="0.99"} 0 -prometheus_notifications_latency_milliseconds_sum 0 -prometheus_notifications_latency_milliseconds_count 0 -# HELP prometheus_notifications_queue_capacity The capacity of the alert notifications queue. -# TYPE prometheus_notifications_queue_capacity gauge -prometheus_notifications_queue_capacity 100 -# HELP prometheus_notifications_queue_length The number of alert notifications in the queue. -# TYPE prometheus_notifications_queue_length gauge -prometheus_notifications_queue_length 0 -# HELP prometheus_rule_evaluation_duration_milliseconds The duration for a rule to execute. -# TYPE prometheus_rule_evaluation_duration_milliseconds summary -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.5"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.9"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.99"} 2 -prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="alerting"} 12 -prometheus_rule_evaluation_duration_milliseconds_count{rule_type="alerting"} 115 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.5"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.9"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.99"} 3 -prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="recording"} 15 -prometheus_rule_evaluation_duration_milliseconds_count{rule_type="recording"} 115 -# HELP prometheus_rule_evaluation_failures_total The total number of rule evaluation failures. -# TYPE prometheus_rule_evaluation_failures_total counter -prometheus_rule_evaluation_failures_total 0 -# HELP prometheus_samples_queue_capacity Capacity of the queue for unwritten samples. -# TYPE prometheus_samples_queue_capacity gauge -prometheus_samples_queue_capacity 4096 -# HELP prometheus_samples_queue_length Current number of items in the queue for unwritten samples. Each item comprises all samples exposed by one target as one metric family (i.e. metrics of the same name). -# TYPE prometheus_samples_queue_length gauge -prometheus_samples_queue_length 0 -# HELP prometheus_target_interval_length_seconds Actual intervals between scrapes. -# TYPE prometheus_target_interval_length_seconds summary -prometheus_target_interval_length_seconds{interval="15s",quantile="0.01"} 14 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.05"} 14 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.5"} 15 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.9"} 15 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.99"} 15 -prometheus_target_interval_length_seconds_sum{interval="15s"} 175 -prometheus_target_interval_length_seconds_count{interval="15s"} 12 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.01"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.05"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.5"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.9"} 1 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.99"} 1 -prometheus_target_interval_length_seconds_sum{interval="1s"} 55 -prometheus_target_interval_length_seconds_count{interval="1s"} 117 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_create_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_create_test.go deleted file mode 100644 index e4cc5d803..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_create_test.go +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright 2014 The Prometheus 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 expfmt - -import ( - "bytes" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - dto "github.com/prometheus/client_model/go" -) - -func testCreate(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - out string - }{ - // 0: Counter, NaN as value, timestamp given. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - out: `# HELP name two-line\n doc str\\ing -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name{labelname="val2",basename="basevalue"} 0.23 1234567890 -`, - }, - // 1: Gauge, some escaping required, +Inf as value, multi-byte characters in label values. - { - in: &dto.MetricFamily{ - Name: proto.String("gauge_name"), - Help: proto.String("gauge\ndoc\nstr\"ing"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("val with\nnew line"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("val with \\backslash and \"quotes\""), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("Björn"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("佖佥"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(3.14E42), - }, - }, - }, - }, - out: `# HELP gauge_name gauge\ndoc\nstr"ing -# TYPE gauge_name gauge -gauge_name{name_1="val with\nnew line",name_2="val with \\backslash and \"quotes\""} +Inf -gauge_name{name_1="Björn",name_2="佖佥"} 3.14e+42 -`, - }, - // 2: Untyped, no help, one sample with no labels and -Inf as value, another sample with one label. - { - in: &dto.MetricFamily{ - Name: proto.String("untyped_name"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(-1.23e-45), - }, - }, - }, - }, - out: `# TYPE untyped_name untyped -untyped_name -Inf -untyped_name{name_1="value 1"} -1.23e-45 -`, - }, - // 3: Summary. - { - in: &dto.MetricFamily{ - Name: proto.String("summary_name"), - Help: proto.String("summary docstring"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(-3.4567), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(-1.23), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(.2342354), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(0), - }, - }, - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("value 2"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(4711), - SampleSum: proto.Float64(2010.1971), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(1), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(2), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - out: `# HELP summary_name summary docstring -# TYPE summary_name summary -summary_name{quantile="0.5"} -1.23 -summary_name{quantile="0.9"} 0.2342354 -summary_name{quantile="0.99"} 0 -summary_name_sum -3.4567 -summary_name_count 42 -summary_name{name_1="value 1",name_2="value 2",quantile="0.5"} 1 -summary_name{name_1="value 1",name_2="value 2",quantile="0.9"} 2 -summary_name{name_1="value 1",name_2="value 2",quantile="0.99"} 3 -summary_name_sum{name_1="value 1",name_2="value 2"} 2010.1971 -summary_name_count{name_1="value 1",name_2="value 2"} 4711 -`, - }, - // 4: Histogram - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 5: Histogram with missing +Inf bucket. - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 6: No metric type, should result in default type Counter. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Metric: []*dto.Metric{ - &dto.Metric{ - Counter: &dto.Counter{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - out: `# HELP name doc string -# TYPE name counter -name -Inf -`, - }, - } - - for i, scenario := range scenarios { - out := bytes.NewBuffer(make([]byte, 0, len(scenario.out))) - n, err := MetricFamilyToText(out, scenario.in) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), n; expected != got { - t.Errorf( - "%d. expected %d bytes written, got %d", - i, expected, got, - ) - } - if expected, got := scenario.out, out.String(); expected != got { - t.Errorf( - "%d. expected out=%q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreate(t *testing.T) { - testCreate(t) -} - -func BenchmarkCreate(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreate(b) - } -} - -func testCreateError(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - err string - }{ - // 0: No metric. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{}, - }, - err: "MetricFamily has no metrics", - }, - // 1: No metric name. - { - in: &dto.MetricFamily{ - Help: proto.String("doc string"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "MetricFamily has no name", - }, - // 2: Wrong type. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "expected counter in metric", - }, - } - - for i, scenario := range scenarios { - var out bytes.Buffer - _, err := MetricFamilyToText(&out, scenario.in) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreateError(t *testing.T) { - testCreateError(t) -} - -func BenchmarkCreateError(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreateError(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_parse_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_parse_test.go deleted file mode 100644 index 589c87a9d..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_parse_test.go +++ /dev/null @@ -1,586 +0,0 @@ -// Copyright 2014 The Prometheus 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 expfmt - -import ( - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func testTextParse(t testing.TB) { - var scenarios = []struct { - in string - out []*dto.MetricFamily - }{ - // 0: Empty lines as input. - { - in: ` - -`, - out: []*dto.MetricFamily{}, - }, - // 1: Minimal case. - { - in: ` -minimal_metric 1.234 -another_metric -3e3 103948 -# Even that: -no_labels{} 3 -# HELP line for non-existing metric will be ignored. -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("minimal_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(1.234), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-3e3), - }, - TimestampMs: proto.Int64(103948), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("no_labels"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - // 2: Counters & gauges, docstrings, various whitespace, escape sequences. - { - in: ` -# A normal comment. -# -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 -# HELP name two-line\n doc str\\ing - - # HELP name2 doc str"ing 2 - # TYPE name2 gauge -name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 -name2{ labelname = "val1" , }-Inf -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("base\"v\\al\nue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("name2"), - Help: proto.String("doc str\"ing 2"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue2"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - TimestampMs: proto.Int64(54321), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - }, - }, - // 3: The evil summary, mixed with other types and funny comments. - { - in: ` -# TYPE my_summary summary -my_summary{n1="val1",quantile="0.5"} 110 -decoy -1 -2 -my_summary{n1="val1",quantile="0.9"} 140 1 -my_summary_count{n1="val1"} 42 -# Latest timestamp wins in case of a summary. -my_summary_sum{n1="val1"} 4711 2 -fake_sum{n1="val1"} 2001 -# TYPE another_summary summary -another_summary_count{n2="val2",n1="val1"} 20 -my_summary_count{n2="val2",n1="val1"} 5 5 -another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 -my_summary_sum{n1="val2"} 08 15 -my_summary{n1="val3", quantile="0.2"} 4711 - my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN -# some -# funny comments -# HELP -# HELP -# HELP my_summary -# HELP my_summary -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("fake_sum"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(2001), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("decoy"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-1), - }, - TimestampMs: proto.Int64(-2), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("my_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(4711), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(110), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(140), - }, - }, - }, - TimestampMs: proto.Int64(2), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(5), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(-12.34), - Value: proto.Float64(math.NaN()), - }, - }, - }, - TimestampMs: proto.Int64(5), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val2"), - }, - }, - Summary: &dto.Summary{ - SampleSum: proto.Float64(8), - }, - TimestampMs: proto.Int64(15), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val3"), - }, - }, - Summary: &dto.Summary{ - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.2), - Value: proto.Float64(4711), - }, - }, - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(20), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.3), - Value: proto.Float64(-1.2), - }, - }, - }, - }, - }, - }, - }, - }, - // 4: The histogram. - { - in: ` -# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - out: []*dto.MetricFamily{ - { - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - }, - }, - } - - for i, scenario := range scenarios { - out, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), len(out); expected != got { - t.Errorf( - "%d. expected %d MetricFamilies, got %d", - i, expected, got, - ) - } - for _, expected := range scenario.out { - got, ok := out[expected.GetName()] - if !ok { - t.Errorf( - "%d. expected MetricFamily %q, found none", - i, expected.GetName(), - ) - continue - } - if expected.String() != got.String() { - t.Errorf( - "%d. expected MetricFamily %s, got %s", - i, expected, got, - ) - } - } - } -} - -func TestTextParse(t *testing.T) { - testTextParse(t) -} - -func BenchmarkTextParse(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParse(b) - } -} - -func testTextParseError(t testing.TB) { - var scenarios = []struct { - in string - err string - }{ - // 0: No new-line at end of input. - { - in: `bla 3.14`, - err: "EOF", - }, - // 1: Invalid escape sequence in label value. - { - in: `metric{label="\t"} 3.14`, - err: "text format parsing error in line 1: invalid escape sequence", - }, - // 2: Newline in label value. - { - in: ` -metric{label="new -line"} 3.14 -`, - err: `text format parsing error in line 2: label value "new" contains unescaped new-line`, - }, - // 3: - { - in: `metric{@="bla"} 3.14`, - err: "text format parsing error in line 1: invalid label name for metric", - }, - // 4: - { - in: `metric{__name__="bla"} 3.14`, - err: `text format parsing error in line 1: label name "__name__" is reserved`, - }, - // 5: - { - in: `metric{label+="bla"} 3.14`, - err: "text format parsing error in line 1: expected '=' after label name", - }, - // 6: - { - in: `metric{label=bla} 3.14`, - err: "text format parsing error in line 1: expected '\"' at start of label value", - }, - // 7: - { - in: ` -# TYPE metric summary -metric{quantile="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'quantile' label", - }, - // 8: - { - in: `metric{label="bla"+} 3.14`, - err: "text format parsing error in line 1: unexpected end of label value", - }, - // 9: - { - in: `metric{label="bla"} 3.14 2.72 -`, - err: "text format parsing error in line 1: expected integer as timestamp", - }, - // 10: - { - in: `metric{label="bla"} 3.14 2 3 -`, - err: "text format parsing error in line 1: spurious string after timestamp", - }, - // 11: - { - in: `metric{label="bla"} blubb -`, - err: "text format parsing error in line 1: expected float as value", - }, - // 12: - { - in: ` -# HELP metric one -# HELP metric two -`, - err: "text format parsing error in line 3: second HELP line for metric name", - }, - // 13: - { - in: ` -# TYPE metric counter -# TYPE metric untyped -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -metric 4.12 -# TYPE metric counter -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -# TYPE metric bla -`, - err: "text format parsing error in line 2: unknown metric type", - }, - // 15: - { - in: ` -# TYPE met-ric -`, - err: "text format parsing error in line 2: invalid metric name in comment", - }, - // 16: - { - in: `@invalidmetric{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 17: - { - in: `{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 18: - { - in: ` -# TYPE metric histogram -metric_bucket{le="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'le' label", - }, - } - - for i, scenario := range scenarios { - _, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestTextParseError(t *testing.T) { - testTextParseError(t) -} - -func BenchmarkParseError(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParseError(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/labels_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/labels_test.go deleted file mode 100644 index ab17025c7..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/labels_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import ( - "sort" - "testing" -) - -func testLabelNames(t testing.TB) { - var scenarios = []struct { - in LabelNames - out LabelNames - }{ - { - in: LabelNames{"ZZZ", "zzz"}, - out: LabelNames{"ZZZ", "zzz"}, - }, - { - in: LabelNames{"aaa", "AAA"}, - out: LabelNames{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelNames(t *testing.T) { - testLabelNames(t) -} - -func BenchmarkLabelNames(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelNames(b) - } -} - -func testLabelValues(t testing.TB) { - var scenarios = []struct { - in LabelValues - out LabelValues - }{ - { - in: LabelValues{"ZZZ", "zzz"}, - out: LabelValues{"ZZZ", "zzz"}, - }, - { - in: LabelValues{"aaa", "AAA"}, - out: LabelValues{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelValues(t *testing.T) { - testLabelValues(t) -} - -func BenchmarkLabelValues(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelValues(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/metric_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/metric_test.go deleted file mode 100644 index 5c7cfceaf..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/metric_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import "testing" - -func testMetric(t testing.TB) { - var scenarios = []struct { - input LabelSet - fingerprint Fingerprint - fastFingerprint Fingerprint - }{ - { - input: LabelSet{}, - fingerprint: 14695981039346656037, - fastFingerprint: 14695981039346656037, - }, - { - input: LabelSet{ - "first_name": "electro", - "occupation": "robot", - "manufacturer": "westinghouse", - }, - fingerprint: 5911716720268894962, - fastFingerprint: 11310079640881077873, - }, - { - input: LabelSet{ - "x": "y", - }, - fingerprint: 8241431561484471700, - fastFingerprint: 13948396922932177635, - }, - { - input: LabelSet{ - "a": "bb", - "b": "c", - }, - fingerprint: 3016285359649981711, - fastFingerprint: 3198632812309449502, - }, - { - input: LabelSet{ - "a": "b", - "bb": "c", - }, - fingerprint: 7122421792099404749, - fastFingerprint: 5774953389407657638, - }, - } - - for i, scenario := range scenarios { - input := Metric(scenario.input) - - if scenario.fingerprint != input.Fingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, input.Fingerprint()) - } - if scenario.fastFingerprint != input.FastFingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, input.FastFingerprint()) - } - } -} - -func TestMetric(t *testing.T) { - testMetric(t) -} - -func BenchmarkMetric(b *testing.B) { - for i := 0; i < b.N; i++ { - testMetric(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/signature_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/signature_test.go deleted file mode 100644 index d9c665f8c..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/signature_test.go +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright 2014 The Prometheus 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 model - -import ( - "runtime" - "sync" - "testing" -) - -func TestLabelsToSignature(t *testing.T) { - var scenarios = []struct { - in map[string]string - out uint64 - }{ - { - in: map[string]string{}, - out: 14695981039346656037, - }, - { - in: map[string]string{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := LabelsToSignature(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFastFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 12952432476264840823, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFastFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureForLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels LabelNames - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 14695981039346656037, - }, - } - - for i, scenario := range scenarios { - actual := SignatureForLabels(scenario.in, scenario.labels...) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureWithoutLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels map[LabelName]struct{} - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{"fear": struct{}{}, "name": struct{}{}}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: map[LabelName]struct{}{"foo": struct{}{}}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := SignatureWithoutLabels(scenario.in, scenario.labels) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func benchmarkLabelToSignature(b *testing.B, l map[string]string, e uint64) { - for i := 0; i < b.N; i++ { - if a := LabelsToSignature(l); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, l, a) - } - } -} - -func BenchmarkLabelToSignatureScalar(b *testing.B) { - benchmarkLabelToSignature(b, nil, 14695981039346656037) -} - -func BenchmarkLabelToSignatureSingle(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkLabelToSignatureDouble(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkLabelToSignatureTriple(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFingerprintScalar(b *testing.B) { - benchmarkMetricToFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFingerprintSingle(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkMetricToFingerprintDouble(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkMetricToFingerprintTriple(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFastFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFastFingerprintScalar(b *testing.B) { - benchmarkMetricToFastFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFastFingerprintSingle(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5147259542624943964) -} - -func BenchmarkMetricToFastFingerprintDouble(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528) -} - -func BenchmarkMetricToFastFingerprintTriple(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676) -} - -func BenchmarkEmptyLabelSignature(b *testing.B) { - input := []map[string]string{nil, {}} - - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - - alloc := ms.Alloc - - for _, labels := range input { - LabelsToSignature(labels) - } - - runtime.ReadMemStats(&ms) - - if got := ms.Alloc; alloc != got { - b.Fatal("expected LabelsToSignature with empty labels not to perform allocations") - } -} - -func benchmarkMetricToFastFingerprintConc(b *testing.B, ls LabelSet, e Fingerprint, concLevel int) { - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - for i := 0; i < concLevel; i++ { - go func() { - start.Wait() - for j := b.N / concLevel; j >= 0; j-- { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } - end.Done() - }() - } - b.ResetTimer() - start.Done() - end.Wait() -} - -func BenchmarkMetricToFastFingerprintTripleConc1(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1) -} - -func BenchmarkMetricToFastFingerprintTripleConc2(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2) -} - -func BenchmarkMetricToFastFingerprintTripleConc4(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4) -} - -func BenchmarkMetricToFastFingerprintTripleConc8(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/time_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/time_test.go deleted file mode 100644 index 9013a6277..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/time_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import ( - "testing" - "time" -) - -func TestComparators(t *testing.T) { - t1a := TimeFromUnix(0) - t1b := TimeFromUnix(0) - t2 := TimeFromUnix(2*second - 1) - - if !t1a.Equal(t1b) { - t.Fatalf("Expected %s to be equal to %s", t1a, t1b) - } - if t1a.Equal(t2) { - t.Fatalf("Expected %s to not be equal to %s", t1a, t2) - } - - if !t1a.Before(t2) { - t.Fatalf("Expected %s to be before %s", t1a, t2) - } - if t1a.Before(t1b) { - t.Fatalf("Expected %s to not be before %s", t1a, t1b) - } - - if !t2.After(t1a) { - t.Fatalf("Expected %s to be after %s", t2, t1a) - } - if t1b.After(t1a) { - t.Fatalf("Expected %s to not be after %s", t1b, t1a) - } -} - -func TestTimeConversions(t *testing.T) { - unixSecs := int64(1136239445) - unixNsecs := int64(123456789) - unixNano := unixSecs*1e9 + unixNsecs - - t1 := time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick) - t2 := time.Unix(unixSecs, unixNsecs) - - ts := TimeFromUnixNano(unixNano) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - // Test available precision. - ts = TimeFromUnixNano(t2.UnixNano()) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - if ts.UnixNano() != unixNano-unixNano%nanosPerTick { - t.Fatalf("Expected %d, got %d", unixNano, ts.UnixNano()) - } -} - -func TestDuration(t *testing.T) { - duration := time.Second + time.Minute + time.Hour - goTime := time.Unix(1136239445, 0) - - ts := TimeFromUnix(goTime.Unix()) - if !goTime.Add(duration).Equal(ts.Add(duration).Time()) { - t.Fatalf("Expected %s to be equal to %s", goTime.Add(duration), ts.Add(duration)) - } - - earlier := ts.Add(-duration) - delta := ts.Sub(earlier) - if delta != duration { - t.Fatalf("Expected %s to be equal to %s", delta, duration) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/value_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/value_test.go deleted file mode 100644 index 2e9c7eb09..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/value_test.go +++ /dev/null @@ -1,362 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import ( - "encoding/json" - "math" - "reflect" - "sort" - "testing" -) - -func TestSamplePairJSON(t *testing.T) { - input := []struct { - plain string - value SamplePair - }{ - { - plain: `[1234.567,"123.1"]`, - value: SamplePair{ - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sp SamplePair - err = json.Unmarshal(b, &sp) - if err != nil { - t.Error(err) - continue - } - - if sp != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sp) - } - } -} - -func TestSampleJSON(t *testing.T) { - input := []struct { - plain string - value Sample - }{ - { - plain: `{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}`, - value: Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Sample - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(sv, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorJSON(t *testing.T) { - input := []struct { - plain string - value Vector - }{ - { - plain: `[]`, - value: Vector{}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}]`, - value: Vector{&Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]},{"metric":{"foo":"bar"},"value":[1.234,"+Inf"]}]`, - value: Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - &Sample{ - Metric: Metric{ - "foo": "bar", - }, - Value: SampleValue(math.Inf(1)), - Timestamp: 1234, - }, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var vec Vector - err = json.Unmarshal(b, &vec) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(vec, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, vec) - } - } -} - -func TestScalarJSON(t *testing.T) { - input := []struct { - plain string - value Scalar - }{ - { - plain: `[123.456,"456"]`, - value: Scalar{ - Timestamp: 123456, - Value: 456, - }, - }, - { - plain: `[123123.456,"+Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(1)), - }, - }, - { - plain: `[123123.456,"-Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(-1)), - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Scalar - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestStringJSON(t *testing.T) { - input := []struct { - plain string - value String - }{ - { - plain: `[123.456,"test"]`, - value: String{ - Timestamp: 123456, - Value: "test", - }, - }, - { - plain: `[123123.456,"台北"]`, - value: String{ - Timestamp: 123123456, - Value: "台北", - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv String - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorSort(t *testing.T) { - input := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - } - - expected := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - } - - sort.Sort(input) - - for i, actual := range input { - actualFp := actual.Metric.Fingerprint() - expectedFp := expected[i].Metric.Fingerprint() - - if actualFp != expectedFp { - t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String()) - } - - if actual.Timestamp != expected[i].Timestamp { - t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/cmdline b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/cmdline deleted file mode 100644 index d2d8ef887..000000000 Binary files a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/cmdline and /dev/null differ diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/0 b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/0 deleted file mode 100644 index e69de29bb..000000000 diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/1 b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/1 deleted file mode 100644 index e69de29bb..000000000 diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/2 b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/2 deleted file mode 100644 index e69de29bb..000000000 diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/3 b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/3 deleted file mode 100644 index e69de29bb..000000000 diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/4 b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/fd/4 deleted file mode 100644 index e69de29bb..000000000 diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/limits b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/limits deleted file mode 100644 index 23c6b6898..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/limits +++ /dev/null @@ -1,17 +0,0 @@ -Limit Soft Limit Hard Limit Units -Max cpu time unlimited unlimited seconds -Max file size unlimited unlimited bytes -Max data size unlimited unlimited bytes -Max stack size 8388608 unlimited bytes -Max core file size 0 unlimited bytes -Max resident set unlimited unlimited bytes -Max processes 62898 62898 processes -Max open files 2048 4096 files -Max locked memory 65536 65536 bytes -Max address space unlimited unlimited bytes -Max file locks unlimited unlimited locks -Max pending signals 62898 62898 signals -Max msgqueue size 819200 819200 bytes -Max nice priority 0 0 -Max realtime priority 0 0 -Max realtime timeout unlimited unlimited us diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/stat b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/stat deleted file mode 100644 index 438aaa9dc..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/26231/stat +++ /dev/null @@ -1 +0,0 @@ -26231 (vim) R 5392 7446 5392 34835 7446 4218880 32533 309516 26 82 1677 44 158 99 20 0 1 0 82375 56274944 1981 18446744073709551615 4194304 6294284 140736914091744 140736914087944 139965136429984 0 0 12288 1870679807 0 0 0 17 0 0 0 31 0 0 8391624 8481048 16420864 140736914093252 140736914093279 140736914093279 140736914096107 0 diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/584/stat b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/584/stat deleted file mode 100644 index 65b9369d1..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/584/stat +++ /dev/null @@ -1,2 +0,0 @@ -1020 ((a b ) ( c d) ) R 28378 1020 28378 34842 1020 4218880 286 0 0 0 0 0 0 0 20 0 1 0 10839175 10395648 155 18446744073709551615 4194304 4238788 140736466511168 140736466511168 140609271124624 0 0 0 0 0 0 0 17 5 0 0 0 0 0 6336016 6337300 25579520 140736466515030 140736466515061 140736466515061 140736466518002 0 -#!/bin/cat /proc/self/stat diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/stat b/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/stat deleted file mode 100644 index dabb96f74..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/fixtures/stat +++ /dev/null @@ -1,16 +0,0 @@ -cpu 301854 612 111922 8979004 3552 2 3944 0 0 0 -cpu0 44490 19 21045 1087069 220 1 3410 0 0 0 -cpu1 47869 23 16474 1110787 591 0 46 0 0 0 -cpu2 46504 36 15916 1112321 441 0 326 0 0 0 -cpu3 47054 102 15683 1113230 533 0 60 0 0 0 -cpu4 28413 25 10776 1140321 217 0 8 0 0 0 -cpu5 29271 101 11586 1136270 672 0 30 0 0 0 -cpu6 29152 36 10276 1139721 319 0 29 0 0 0 -cpu7 29098 268 10164 1139282 555 0 31 0 0 0 -intr 8885917 17 0 0 0 0 0 0 0 1 79281 0 0 0 0 0 0 0 231237 0 0 0 0 250586 103 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 223424 190745 13 906 1283803 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 38014093 -btime 1418183276 -processes 26442 -procs_running 2 -procs_blocked 0 -softirq 5057579 250191 1481983 1647 211099 186066 0 1783454 622196 12499 508444 diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fs_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/fs_test.go deleted file mode 100644 index 91f1c6c97..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/fs_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package procfs - -import "testing" - -func TestNewFS(t *testing.T) { - if _, err := NewFS("foobar"); err == nil { - t.Error("want NewFS to fail for non-existing mount point") - } - - if _, err := NewFS("procfs.go"); err == nil { - t.Error("want NewFS to fail if mount point is not a directory") - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_limits_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/proc_limits_test.go deleted file mode 100644 index ca7a254da..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_limits_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package procfs - -import "testing" - -func TestNewLimits(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - p, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - - l, err := p.NewLimits() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "cpu time", want: -1, got: l.CPUTime}, - {name: "open files", want: 2048, got: l.OpenFiles}, - {name: "msgqueue size", want: 819200, got: l.MsqqueueSize}, - {name: "nice priority", want: 0, got: l.NicePriority}, - {name: "address space", want: -1, got: l.AddressSpace}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_stat_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/proc_stat_test.go deleted file mode 100644 index e4d5cacfa..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_stat_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package procfs - -import "testing" - -func TestProcStat(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - p, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewStat() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "pid", want: 26231, got: s.PID}, - {name: "user time", want: 1677, got: int(s.UTime)}, - {name: "system time", want: 44, got: int(s.STime)}, - {name: "start time", want: 82375, got: int(s.Starttime)}, - {name: "virtual memory size", want: 56274944, got: s.VSize}, - {name: "resident set size", want: 1981, got: s.RSS}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } -} - -func TestProcStatComm(t *testing.T) { - s1, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - if want, got := "vim", s1.Comm; want != got { - t.Errorf("want comm %s, got %s", want, got) - } - - s2, err := testProcStat(584) - if err != nil { - t.Fatal(err) - } - if want, got := "(a b ) ( c d) ", s2.Comm; want != got { - t.Errorf("want comm %s, got %s", want, got) - } -} - -func TestProcStatVirtualMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 56274944, s.VirtualMemory(); want != got { - t.Errorf("want virtual memory %d, got %d", want, got) - } -} - -func TestProcStatResidentMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 1981*4096, s.ResidentMemory(); want != got { - t.Errorf("want resident memory %d, got %d", want, got) - } -} - -func TestProcStatStartTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - time, err := s.StartTime() - if err != nil { - t.Fatal(err) - } - if want, got := 1418184099.75, time; want != got { - t.Errorf("want start time %f, got %f", want, got) - } -} - -func TestProcStatCPUTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 17.21, s.CPUTime(); want != got { - t.Errorf("want cpu time %f, got %f", want, got) - } -} - -func testProcStat(pid int) (ProcStat, error) { - p, err := testProcess(pid) - if err != nil { - return ProcStat{}, err - } - - return p.NewStat() -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/proc_test.go deleted file mode 100644 index bd234a14c..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package procfs - -import ( - "os" - "reflect" - "sort" - "testing" -) - -func TestSelf(t *testing.T) { - p1, err := NewProc(os.Getpid()) - if err != nil { - t.Fatal(err) - } - p2, err := Self() - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(p1, p2) { - t.Errorf("want process %v to equal %v", p1, p2) - } -} - -func TestAllProcs(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - procs, err := fs.AllProcs() - if err != nil { - t.Fatal(err) - } - sort.Sort(procs) - for i, p := range []*Proc{{PID: 584}, {PID: 26231}} { - if want, got := p.PID, procs[i].PID; want != got { - t.Errorf("want processes %d, got %d", want, got) - } - } -} - -func TestCmdLine(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - c, err := p1.CmdLine() - if err != nil { - t.Fatal(err) - } - if want := []string{"vim", "test.go", "+10"}; !reflect.DeepEqual(want, c) { - t.Errorf("want cmdline %v, got %v", want, c) - } -} - -func TestFileDescriptors(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptors() - if err != nil { - t.Fatal(err) - } - sort.Sort(byUintptr(fds)) - if want := []uintptr{0, 1, 2, 3, 4}; !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, got %v", want, fds) - } - - p2, err := Self() - if err != nil { - t.Fatal(err) - } - - fdsBefore, err := p2.FileDescriptors() - if err != nil { - t.Fatal(err) - } - - s, err := os.Open("fixtures") - if err != nil { - t.Fatal(err) - } - defer s.Close() - - fdsAfter, err := p2.FileDescriptors() - if err != nil { - t.Fatal(err) - } - - if len(fdsBefore)+1 != len(fdsAfter) { - t.Errorf("want fds %v+1 to equal %v", fdsBefore, fdsAfter) - } -} - -func TestFileDescriptorsLen(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - l, err := p1.FileDescriptorsLen() - if err != nil { - t.Fatal(err) - } - if want, got := 5, l; want != got { - t.Errorf("want fds %d, got %d", want, got) - } -} - -func testProcess(pid int) (Proc, error) { - fs, err := NewFS("fixtures") - if err != nil { - return Proc{}, err - } - - return fs.NewProc(pid) -} - -type byUintptr []uintptr - -func (a byUintptr) Len() int { return len(a) } -func (a byUintptr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byUintptr) Less(i, j int) bool { return a[i] < a[j] } diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/stat_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/stat_test.go deleted file mode 100644 index 24b5d61f8..000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/stat_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package procfs - -import "testing" - -func TestStat(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - s, err := fs.NewStat() - if err != nil { - t.Fatal(err) - } - - if want, got := int64(1418183276), s.BootTime; want != got { - t.Errorf("want boot time %d, got %d", want, got) - } -} diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go b/Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go deleted file mode 100644 index b726c070c..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go +++ /dev/null @@ -1,1296 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Unit tests for block parsing -// - -package blackfriday - -import ( - "testing" -) - -func runMarkdownBlockWithRenderer(input string, extensions int, renderer Renderer) string { - return string(Markdown([]byte(input), renderer, extensions)) -} - -func runMarkdownBlock(input string, extensions int) string { - htmlFlags := 0 - htmlFlags |= HTML_USE_XHTML - - renderer := HtmlRenderer(htmlFlags, "", "") - - return runMarkdownBlockWithRenderer(input, extensions, renderer) -} - -func runnerWithRendererParameters(parameters HtmlRendererParameters) func(string, int) string { - return func(input string, extensions int) string { - htmlFlags := 0 - htmlFlags |= HTML_USE_XHTML - - renderer := HtmlRendererWithParameters(htmlFlags, "", "", parameters) - - return runMarkdownBlockWithRenderer(input, extensions, renderer) - } -} - -func doTestsBlock(t *testing.T, tests []string, extensions int) { - doTestsBlockWithRunner(t, tests, extensions, runMarkdownBlock) -} - -func doTestsBlockWithRunner(t *testing.T, tests []string, extensions int, runner func(string, int) string) { - // catch and report panics - var candidate string - defer func() { - if err := recover(); err != nil { - t.Errorf("\npanic while processing [%#v]: %s\n", candidate, err) - } - }() - - for i := 0; i+1 < len(tests); i += 2 { - input := tests[i] - candidate = input - expected := tests[i+1] - actual := runner(candidate, extensions) - if actual != expected { - t.Errorf("\nInput [%#v]\nExpected[%#v]\nActual [%#v]", - candidate, expected, actual) - } - - // now test every substring to stress test bounds checking - if !testing.Short() { - for start := 0; start < len(input); start++ { - for end := start + 1; end <= len(input); end++ { - candidate = input[start:end] - _ = runMarkdownBlock(candidate, extensions) - } - } - } - } -} - -func TestPrefixHeaderNoExtensions(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "
# Header 7
\n", - - "#Header 1\n", - "

Header 1

\n", - - "##Header 2\n", - "

Header 2

\n", - - "###Header 3\n", - "

Header 3

\n", - - "####Header 4\n", - "

Header 4

\n", - - "#####Header 5\n", - "
Header 5
\n", - - "######Header 6\n", - "
Header 6
\n", - - "#######Header 7\n", - "
#Header 7
\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestPrefixHeaderSpaceExtension(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "

####### Header 7

\n", - - "#Header 1\n", - "

#Header 1

\n", - - "##Header 2\n", - "

##Header 2

\n", - - "###Header 3\n", - "

###Header 3

\n", - - "####Header 4\n", - "

####Header 4

\n", - - "#####Header 5\n", - "

#####Header 5

\n", - - "######Header 6\n", - "

######Header 6

\n", - - "#######Header 7\n", - "

#######Header 7

\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List\n#Header
  • \n
  • List
  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - doTestsBlock(t, tests, EXTENSION_SPACE_HEADERS) -} - -func TestPrefixHeaderIdExtension(t *testing.T) { - var tests = []string{ - "# Header 1 {#someid}\n", - "

Header 1

\n", - - "# Header 1 {#someid} \n", - "

Header 1

\n", - - "# Header 1 {#someid}\n", - "

Header 1

\n", - - "# Header 1 {#someid\n", - "

Header 1 {#someid

\n", - - "# Header 1 {#someid\n", - "

Header 1 {#someid

\n", - - "# Header 1 {#someid}}\n", - "

Header 1

\n\n

}

\n", - - "## Header 2 {#someid}\n", - "

Header 2

\n", - - "### Header 3 {#someid}\n", - "

Header 3

\n", - - "#### Header 4 {#someid}\n", - "

Header 4

\n", - - "##### Header 5 {#someid}\n", - "
Header 5
\n", - - "###### Header 6 {#someid}\n", - "
Header 6
\n", - - "####### Header 7 {#someid}\n", - "
# Header 7
\n", - - "# Header 1 # {#someid}\n", - "

Header 1

\n", - - "## Header 2 ## {#someid}\n", - "

Header 2

\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header {#someid}\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - doTestsBlock(t, tests, EXTENSION_HEADER_IDS) -} - -func TestPrefixHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) { - var tests = []string{ - "# header 1 {#someid}\n", - "

header 1

\n", - - "## header 2 {#someid}\n", - "

header 2

\n", - - "### header 3 {#someid}\n", - "

header 3

\n", - - "#### header 4 {#someid}\n", - "

header 4

\n", - - "##### header 5 {#someid}\n", - "
header 5
\n", - - "###### header 6 {#someid}\n", - "
header 6
\n", - - "####### header 7 {#someid}\n", - "
# header 7
\n", - - "# header 1 # {#someid}\n", - "

header 1

\n", - - "## header 2 ## {#someid}\n", - "

header 2

\n", - - "* List\n# Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header {#someid}\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - - parameters := HtmlRendererParameters{ - HeaderIDPrefix: "PRE:", - HeaderIDSuffix: ":POST", - } - - doTestsBlockWithRunner(t, tests, EXTENSION_HEADER_IDS, runnerWithRendererParameters(parameters)) -} - -func TestPrefixAutoHeaderIdExtension(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "# Header 1 \n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "
# Header 7
\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - - "# Header\n\n# Header\n", - "

Header

\n\n

Header

\n", - - "# Header 1\n\n# Header 1", - "

Header 1

\n\n

Header 1

\n", - - "# Header\n\n# Header 1\n\n# Header\n\n# Header", - "

Header

\n\n

Header 1

\n\n

Header

\n\n

Header

\n", - } - doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS) -} - -func TestPrefixAutoHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "# Header 1 \n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "
# Header 7
\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - - "# Header\n\n# Header\n", - "

Header

\n\n

Header

\n", - - "# Header 1\n\n# Header 1", - "

Header 1

\n\n

Header 1

\n", - - "# Header\n\n# Header 1\n\n# Header\n\n# Header", - "

Header

\n\n

Header 1

\n\n

Header

\n\n

Header

\n", - } - - parameters := HtmlRendererParameters{ - HeaderIDPrefix: "PRE:", - HeaderIDSuffix: ":POST", - } - - doTestsBlockWithRunner(t, tests, EXTENSION_AUTO_HEADER_IDS, runnerWithRendererParameters(parameters)) -} - -func TestPrefixMultipleHeaderExtensions(t *testing.T) { - var tests = []string{ - "# Header\n\n# Header {#header}\n\n# Header 1", - "

Header

\n\n

Header

\n\n

Header 1

\n", - } - doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS|EXTENSION_HEADER_IDS) -} - -func TestUnderlineHeaders(t *testing.T) { - var tests = []string{ - "Header 1\n========\n", - "

Header 1

\n", - - "Header 2\n--------\n", - "

Header 2

\n", - - "A\n=\n", - "

A

\n", - - "B\n-\n", - "

B

\n", - - "Paragraph\nHeader\n=\n", - "

Paragraph

\n\n

Header

\n", - - "Header\n===\nParagraph\n", - "

Header

\n\n

Paragraph

\n", - - "Header\n===\nAnother header\n---\n", - "

Header

\n\n

Another header

\n", - - " Header\n======\n", - "

Header

\n", - - " Code\n========\n", - "
Code\n
\n\n

========

\n", - - "Header with *inline*\n=====\n", - "

Header with inline

\n", - - "* List\n * Sublist\n Not a header\n ------\n", - "
    \n
  • List\n\n
      \n
    • Sublist\nNot a header\n------
    • \n
  • \n
\n", - - "Paragraph\n\n\n\n\nHeader\n===\n", - "

Paragraph

\n\n

Header

\n", - - "Trailing space \n==== \n\n", - "

Trailing space

\n", - - "Trailing spaces\n==== \n\n", - "

Trailing spaces

\n", - - "Double underline\n=====\n=====\n", - "

Double underline

\n\n

=====

\n", - } - doTestsBlock(t, tests, 0) -} - -func TestUnderlineHeadersAutoIDs(t *testing.T) { - var tests = []string{ - "Header 1\n========\n", - "

Header 1

\n", - - "Header 2\n--------\n", - "

Header 2

\n", - - "A\n=\n", - "

A

\n", - - "B\n-\n", - "

B

\n", - - "Paragraph\nHeader\n=\n", - "

Paragraph

\n\n

Header

\n", - - "Header\n===\nParagraph\n", - "

Header

\n\n

Paragraph

\n", - - "Header\n===\nAnother header\n---\n", - "

Header

\n\n

Another header

\n", - - " Header\n======\n", - "

Header

\n", - - "Header with *inline*\n=====\n", - "

Header with inline

\n", - - "Paragraph\n\n\n\n\nHeader\n===\n", - "

Paragraph

\n\n

Header

\n", - - "Trailing space \n==== \n\n", - "

Trailing space

\n", - - "Trailing spaces\n==== \n\n", - "

Trailing spaces

\n", - - "Double underline\n=====\n=====\n", - "

Double underline

\n\n

=====

\n", - - "Header\n======\n\nHeader\n======\n", - "

Header

\n\n

Header

\n", - - "Header 1\n========\n\nHeader 1\n========\n", - "

Header 1

\n\n

Header 1

\n", - } - doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS) -} - -func TestHorizontalRule(t *testing.T) { - var tests = []string{ - "-\n", - "

-

\n", - - "--\n", - "

--

\n", - - "---\n", - "
\n", - - "----\n", - "
\n", - - "*\n", - "

*

\n", - - "**\n", - "

**

\n", - - "***\n", - "
\n", - - "****\n", - "
\n", - - "_\n", - "

_

\n", - - "__\n", - "

__

\n", - - "___\n", - "
\n", - - "____\n", - "
\n", - - "-*-\n", - "

-*-

\n", - - "- - -\n", - "
\n", - - "* * *\n", - "
\n", - - "_ _ _\n", - "
\n", - - "-----*\n", - "

-----*

\n", - - " ------ \n", - "
\n", - - "Hello\n***\n", - "

Hello

\n\n
\n", - - "---\n***\n___\n", - "
\n\n
\n\n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestUnorderedList(t *testing.T) { - var tests = []string{ - "* Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "* Yin\n* Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "* Ting\n* Bong\n* Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "* Yin\n\n* Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "* Ting\n\n* Bong\n* Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "+ Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "+ Yin\n+ Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "+ Ting\n+ Bong\n+ Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "+ Yin\n\n+ Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "+ Ting\n\n+ Bong\n+ Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "- Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "- Yin\n- Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "- Ting\n- Bong\n- Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "- Yin\n\n- Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "- Ting\n\n- Bong\n- Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "*Hello\n", - "

*Hello

\n", - - "* Hello \n", - "
    \n
  • Hello
  • \n
\n", - - "* Hello \n Next line \n", - "
    \n
  • Hello\nNext line
  • \n
\n", - - "Paragraph\n* No linebreak\n", - "

Paragraph\n* No linebreak

\n", - - "Paragraph\n\n* Linebreak\n", - "

Paragraph

\n\n
    \n
  • Linebreak
  • \n
\n", - - "* List\n * Nested list\n", - "
    \n
  • List\n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n\n * Nested list\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n Second line\n\n + Nested\n", - "
    \n
  • List\nSecond line

    \n\n
      \n
    • Nested
    • \n
  • \n
\n", - - "* List\n + Nested\n\n Continued\n", - "
    \n
  • List

    \n\n
      \n
    • Nested
    • \n
    \n\n

    Continued

  • \n
\n", - - "* List\n * shallow indent\n", - "
    \n
  • List\n\n
      \n
    • shallow indent
    • \n
  • \n
\n", - - "* List\n" + - " * shallow indent\n" + - " * part of second list\n" + - " * still second\n" + - " * almost there\n" + - " * third level\n", - "
    \n" + - "
  • List\n\n" + - "
      \n" + - "
    • shallow indent
    • \n" + - "
    • part of second list
    • \n" + - "
    • still second
    • \n" + - "
    • almost there\n\n" + - "
        \n" + - "
      • third level
      • \n" + - "
    • \n" + - "
  • \n" + - "
\n", - - "* List\n extra indent, same paragraph\n", - "
    \n
  • List\n extra indent, same paragraph
  • \n
\n", - - "* List\n\n code block\n", - "
    \n
  • List

    \n\n
    code block\n
  • \n
\n", - - "* List\n\n code block with spaces\n", - "
    \n
  • List

    \n\n
      code block with spaces\n
  • \n
\n", - - "* List\n\n * sublist\n\n normal text\n\n * another sublist\n", - "
    \n
  • List

    \n\n
      \n
    • sublist
    • \n
    \n\n

    normal text

    \n\n
      \n
    • another sublist
    • \n
  • \n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestOrderedList(t *testing.T) { - var tests = []string{ - "1. Hello\n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Yin\n2. Yang\n", - "
    \n
  1. Yin
  2. \n
  3. Yang
  4. \n
\n", - - "1. Ting\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting
  2. \n
  3. Bong
  4. \n
  5. Goo
  6. \n
\n", - - "1. Yin\n\n2. Yang\n", - "
    \n
  1. Yin

  2. \n\n
  3. Yang

  4. \n
\n", - - "1. Ting\n\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting

  2. \n\n
  3. Bong

  4. \n\n
  5. Goo

  6. \n
\n", - - "1 Hello\n", - "

1 Hello

\n", - - "1.Hello\n", - "

1.Hello

\n", - - "1. Hello \n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Hello \n Next line \n", - "
    \n
  1. Hello\nNext line
  2. \n
\n", - - "Paragraph\n1. No linebreak\n", - "

Paragraph\n1. No linebreak

\n", - - "Paragraph\n\n1. Linebreak\n", - "

Paragraph

\n\n
    \n
  1. Linebreak
  2. \n
\n", - - "1. List\n 1. Nested list\n", - "
    \n
  1. List\n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n\n 1. Nested list\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n Second line\n\n 1. Nested\n", - "
    \n
  1. List\nSecond line

    \n\n
      \n
    1. Nested
    2. \n
  2. \n
\n", - - "1. List\n 1. Nested\n\n Continued\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested
    2. \n
    \n\n

    Continued

  2. \n
\n", - - "1. List\n 1. shallow indent\n", - "
    \n
  1. List\n\n
      \n
    1. shallow indent
    2. \n
  2. \n
\n", - - "1. List\n" + - " 1. shallow indent\n" + - " 2. part of second list\n" + - " 3. still second\n" + - " 4. almost there\n" + - " 1. third level\n", - "
    \n" + - "
  1. List\n\n" + - "
      \n" + - "
    1. shallow indent
    2. \n" + - "
    3. part of second list
    4. \n" + - "
    5. still second
    6. \n" + - "
    7. almost there\n\n" + - "
        \n" + - "
      1. third level
      2. \n" + - "
    8. \n" + - "
  2. \n" + - "
\n", - - "1. List\n extra indent, same paragraph\n", - "
    \n
  1. List\n extra indent, same paragraph
  2. \n
\n", - - "1. List\n\n code block\n", - "
    \n
  1. List

    \n\n
    code block\n
  2. \n
\n", - - "1. List\n\n code block with spaces\n", - "
    \n
  1. List

    \n\n
      code block with spaces\n
  2. \n
\n", - - "1. List\n * Mixted list\n", - "
    \n
  1. List\n\n
      \n
    • Mixted list
    • \n
  2. \n
\n", - - "1. List\n * Mixed list\n", - "
    \n
  1. List\n\n
      \n
    • Mixed list
    • \n
  2. \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "1. numbers\n1. are ignored\n", - "
    \n
  1. numbers
  2. \n
  3. are ignored
  4. \n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestPreformattedHtml(t *testing.T) { - var tests = []string{ - "
\n", - "
\n", - - "
\n
\n", - "
\n
\n", - - "
\n
\nParagraph\n", - "

\n
\nParagraph

\n", - - "
\n
\n", - "
\n
\n", - - "
\nAnything here\n
\n", - "
\nAnything here\n
\n", - - "
\n Anything here\n
\n", - "
\n Anything here\n
\n", - - "
\nAnything here\n
\n", - "
\nAnything here\n
\n", - - "
\nThis is *not* &proceessed\n
\n", - "
\nThis is *not* &proceessed\n
\n", - - "\n Something\n\n", - "

\n Something\n

\n", - - "
\n Something here\n\n", - "

\n Something here\n

\n", - - "Paragraph\n
\nHere? >&<\n
\n", - "

Paragraph\n

\nHere? >&<\n

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n", - - "Paragraph\n
\nHere? >&<\n
\nAnd here?\n", - "

Paragraph\n

\nHere? >&<\n
\nAnd here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\nAnd here?\n", - "

Paragraph

\n\n

\nHow about here? >&<\n
\nAnd here?

\n", - - "Paragraph\n
\nHere? >&<\n
\n\nAnd here?\n", - "

Paragraph\n

\nHere? >&<\n

\n\n

And here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n\nAnd here?\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", - } - doTestsBlock(t, tests, 0) -} - -func TestPreformattedHtmlLax(t *testing.T) { - var tests = []string{ - "Paragraph\n
\nHere? >&<\n
\n", - "

Paragraph

\n\n
\nHere? >&<\n
\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n", - - "Paragraph\n
\nHere? >&<\n
\nAnd here?\n", - "

Paragraph

\n\n
\nHere? >&<\n
\n\n

And here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\nAnd here?\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", - - "Paragraph\n
\nHere? >&<\n
\n\nAnd here?\n", - "

Paragraph

\n\n
\nHere? >&<\n
\n\n

And here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n\nAnd here?\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", - } - doTestsBlock(t, tests, EXTENSION_LAX_HTML_BLOCKS) -} - -func TestFencedCodeBlock(t *testing.T) { - var tests = []string{ - "``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n", - "
func foo() bool {\n\treturn true;\n}\n
\n", - - "``` c\n/* special & char < > \" escaping */\n```\n", - "
/* special & char < > " escaping */\n
\n", - - "``` c\nno *inline* processing ~~of text~~\n```\n", - "
no *inline* processing ~~of text~~\n
\n", - - "```\nNo language\n```\n", - "
No language\n
\n", - - "``` {ocaml}\nlanguage in braces\n```\n", - "
language in braces\n
\n", - - "``` {ocaml} \nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "```{ ocaml }\nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "~ ~~ java\nWith whitespace\n~~~\n", - "

~ ~~ java\nWith whitespace\n~~~

\n", - - "~~\nonly two\n~~\n", - "

~~\nonly two\n~~

\n", - - "```` python\nextra\n````\n", - "
extra\n
\n", - - "~~~ perl\nthree to start, four to end\n~~~~\n", - "

~~~ perl\nthree to start, four to end\n~~~~

\n", - - "~~~~ perl\nfour to start, three to end\n~~~\n", - "

~~~~ perl\nfour to start, three to end\n~~~

\n", - - "~~~ bash\ntildes\n~~~\n", - "
tildes\n
\n", - - "``` lisp\nno ending\n", - "

``` lisp\nno ending

\n", - - "~~~ lisp\nend with language\n~~~ lisp\n", - "

~~~ lisp\nend with language\n~~~ lisp

\n", - - "```\nmismatched begin and end\n~~~\n", - "

```\nmismatched begin and end\n~~~

\n", - - "~~~\nmismatched begin and end\n```\n", - "

~~~\nmismatched begin and end\n```

\n", - - " ``` oz\nleading spaces\n```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - "``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
``` oz\n
\n\n

leading spaces\n ```

\n", - - "Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n", - "

Bla bla

\n\n
code blocks breakup paragraphs\n
\n\n

Bla Bla

\n", - - "Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nAnd some text after a fenced code block", - "

Some text before a fenced code block

\n\n
code blocks breakup paragraphs\n
\n\n

And some text after a fenced code block

\n", - - "`", - "

`

\n", - - "Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n\n``` oz\nmultiple code blocks work okay\n```\n\nBla Bla\n", - "

Bla bla

\n\n
code blocks breakup paragraphs\n
\n\n

Bla Bla

\n\n
multiple code blocks work okay\n
\n\n

Bla Bla

\n", - - "Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nSome text in between\n``` oz\nmultiple code blocks work okay\n```\nAnd some text after a fenced code block", - "

Some text before a fenced code block

\n\n
code blocks breakup paragraphs\n
\n\n

Some text in between

\n\n
multiple code blocks work okay\n
\n\n

And some text after a fenced code block

\n", - } - doTestsBlock(t, tests, EXTENSION_FENCED_CODE) -} - -func TestTable(t *testing.T) { - var tests = []string{ - "a | b\n---|---\nc | d\n", - "\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n
ab
cd
\n", - - "a | b\n---|--\nc | d\n", - "

a | b\n---|--\nc | d

\n", - - "|a|b|c|d|\n|----|----|----|---|\n|e|f|g|h|\n", - "\n\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n\n
abcd
efgh
\n", - - "*a*|__b__|[c](C)|d\n---|---|---|---\ne|f|g|h\n", - "\n\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n\n
abcd
efgh
\n", - - "a|b|c\n---|---|---\nd|e|f\ng|h\ni|j|k|l|m\nn|o|p\n", - "\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n" + - "\n\n\n\n\n\n" + - "\n\n\n\n\n\n
abc
def
gh
ijk
nop
\n", - - "a|b|c\n---|---|---\n*d*|__e__|f\n", - "\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n
abc
def
\n", - - "a|b|c|d\n:--|--:|:-:|---\ne|f|g|h\n", - "\n\n\n\n\n" + - "\n\n\n\n\n" + - "\n\n\n\n" + - "\n\n\n\n
abcd
efgh
\n", - - "a|b|c\n---|---|---\n", - "\n\n\n\n\n\n\n\n\n\n\n
abc
\n", - - "a| b|c | d | e\n---|---|---|---|---\nf| g|h | i |j\n", - "\n\n\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n\n\n
abcde
fghij
\n", - - "a|b\\|c|d\n---|---|---\nf|g\\|h|i\n", - "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ab|cd
fg|hi
\n", - } - doTestsBlock(t, tests, EXTENSION_TABLES) -} - -func TestUnorderedListWith_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - var tests = []string{ - "* Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "* Yin\n* Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "* Ting\n* Bong\n* Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "* Yin\n\n* Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "* Ting\n\n* Bong\n* Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "+ Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "+ Yin\n+ Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "+ Ting\n+ Bong\n+ Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "+ Yin\n\n+ Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "+ Ting\n\n+ Bong\n+ Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "- Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "- Yin\n- Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "- Ting\n- Bong\n- Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "- Yin\n\n- Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "- Ting\n\n- Bong\n- Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "*Hello\n", - "

*Hello

\n", - - "* Hello \n", - "
    \n
  • Hello
  • \n
\n", - - "* Hello \n Next line \n", - "
    \n
  • Hello\nNext line
  • \n
\n", - - "Paragraph\n* No linebreak\n", - "

Paragraph

\n\n
    \n
  • No linebreak
  • \n
\n", - - "Paragraph\n\n* Linebreak\n", - "

Paragraph

\n\n
    \n
  • Linebreak
  • \n
\n", - - "* List\n * Nested list\n", - "
    \n
  • List\n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n\n * Nested list\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n Second line\n\n + Nested\n", - "
    \n
  • List\nSecond line

    \n\n
      \n
    • Nested
    • \n
  • \n
\n", - - "* List\n + Nested\n\n Continued\n", - "
    \n
  • List

    \n\n
      \n
    • Nested
    • \n
    \n\n

    Continued

  • \n
\n", - - "* List\n * shallow indent\n", - "
    \n
  • List\n\n
      \n
    • shallow indent
    • \n
  • \n
\n", - - "* List\n" + - " * shallow indent\n" + - " * part of second list\n" + - " * still second\n" + - " * almost there\n" + - " * third level\n", - "
    \n" + - "
  • List\n\n" + - "
      \n" + - "
    • shallow indent
    • \n" + - "
    • part of second list
    • \n" + - "
    • still second
    • \n" + - "
    • almost there\n\n" + - "
        \n" + - "
      • third level
      • \n" + - "
    • \n" + - "
  • \n" + - "
\n", - - "* List\n extra indent, same paragraph\n", - "
    \n
  • List\n extra indent, same paragraph
  • \n
\n", - - "* List\n\n code block\n", - "
    \n
  • List

    \n\n
    code block\n
  • \n
\n", - - "* List\n\n code block with spaces\n", - "
    \n
  • List

    \n\n
      code block with spaces\n
  • \n
\n", - - "* List\n\n * sublist\n\n normal text\n\n * another sublist\n", - "
    \n
  • List

    \n\n
      \n
    • sublist
    • \n
    \n\n

    normal text

    \n\n
      \n
    • another sublist
    • \n
  • \n
\n", - } - doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} - -func TestOrderedList_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - var tests = []string{ - "1. Hello\n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Yin\n2. Yang\n", - "
    \n
  1. Yin
  2. \n
  3. Yang
  4. \n
\n", - - "1. Ting\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting
  2. \n
  3. Bong
  4. \n
  5. Goo
  6. \n
\n", - - "1. Yin\n\n2. Yang\n", - "
    \n
  1. Yin

  2. \n\n
  3. Yang

  4. \n
\n", - - "1. Ting\n\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting

  2. \n\n
  3. Bong

  4. \n\n
  5. Goo

  6. \n
\n", - - "1 Hello\n", - "

1 Hello

\n", - - "1.Hello\n", - "

1.Hello

\n", - - "1. Hello \n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Hello \n Next line \n", - "
    \n
  1. Hello\nNext line
  2. \n
\n", - - "Paragraph\n1. No linebreak\n", - "

Paragraph

\n\n
    \n
  1. No linebreak
  2. \n
\n", - - "Paragraph\n\n1. Linebreak\n", - "

Paragraph

\n\n
    \n
  1. Linebreak
  2. \n
\n", - - "1. List\n 1. Nested list\n", - "
    \n
  1. List\n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n\n 1. Nested list\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n Second line\n\n 1. Nested\n", - "
    \n
  1. List\nSecond line

    \n\n
      \n
    1. Nested
    2. \n
  2. \n
\n", - - "1. List\n 1. Nested\n\n Continued\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested
    2. \n
    \n\n

    Continued

  2. \n
\n", - - "1. List\n 1. shallow indent\n", - "
    \n
  1. List\n\n
      \n
    1. shallow indent
    2. \n
  2. \n
\n", - - "1. List\n" + - " 1. shallow indent\n" + - " 2. part of second list\n" + - " 3. still second\n" + - " 4. almost there\n" + - " 1. third level\n", - "
    \n" + - "
  1. List\n\n" + - "
      \n" + - "
    1. shallow indent
    2. \n" + - "
    3. part of second list
    4. \n" + - "
    5. still second
    6. \n" + - "
    7. almost there\n\n" + - "
        \n" + - "
      1. third level
      2. \n" + - "
    8. \n" + - "
  2. \n" + - "
\n", - - "1. List\n extra indent, same paragraph\n", - "
    \n
  1. List\n extra indent, same paragraph
  2. \n
\n", - - "1. List\n\n code block\n", - "
    \n
  1. List

    \n\n
    code block\n
  2. \n
\n", - - "1. List\n\n code block with spaces\n", - "
    \n
  1. List

    \n\n
      code block with spaces\n
  2. \n
\n", - - "1. List\n * Mixted list\n", - "
    \n
  1. List\n\n
      \n
    • Mixted list
    • \n
  2. \n
\n", - - "1. List\n * Mixed list\n", - "
    \n
  1. List\n\n
      \n
    • Mixed list
    • \n
  2. \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "1. numbers\n1. are ignored\n", - "
    \n
  1. numbers
  2. \n
  3. are ignored
  4. \n
\n", - } - doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} - -func TestFencedCodeBlock_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - var tests = []string{ - "``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n", - "
func foo() bool {\n\treturn true;\n}\n
\n", - - "``` c\n/* special & char < > \" escaping */\n```\n", - "
/* special & char < > " escaping */\n
\n", - - "``` c\nno *inline* processing ~~of text~~\n```\n", - "
no *inline* processing ~~of text~~\n
\n", - - "```\nNo language\n```\n", - "
No language\n
\n", - - "``` {ocaml}\nlanguage in braces\n```\n", - "
language in braces\n
\n", - - "``` {ocaml} \nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "```{ ocaml }\nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "~ ~~ java\nWith whitespace\n~~~\n", - "

~ ~~ java\nWith whitespace\n~~~

\n", - - "~~\nonly two\n~~\n", - "

~~\nonly two\n~~

\n", - - "```` python\nextra\n````\n", - "
extra\n
\n", - - "~~~ perl\nthree to start, four to end\n~~~~\n", - "

~~~ perl\nthree to start, four to end\n~~~~

\n", - - "~~~~ perl\nfour to start, three to end\n~~~\n", - "

~~~~ perl\nfour to start, three to end\n~~~

\n", - - "~~~ bash\ntildes\n~~~\n", - "
tildes\n
\n", - - "``` lisp\nno ending\n", - "

``` lisp\nno ending

\n", - - "~~~ lisp\nend with language\n~~~ lisp\n", - "

~~~ lisp\nend with language\n~~~ lisp

\n", - - "```\nmismatched begin and end\n~~~\n", - "

```\nmismatched begin and end\n~~~

\n", - - "~~~\nmismatched begin and end\n```\n", - "

~~~\nmismatched begin and end\n```

\n", - - " ``` oz\nleading spaces\n```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - "``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
``` oz\n
\n\n

leading spaces

\n\n
```\n
\n", - } - doTestsBlock(t, tests, EXTENSION_FENCED_CODE|EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} - -func TestTitleBlock_EXTENSION_TITLEBLOCK(t *testing.T) { - var tests = []string{ - "% Some title\n" + - "% Another title line\n" + - "% Yep, more here too\n", - "

" + - "Some title\n" + - "Another title line\n" + - "Yep, more here too\n" + - "

", - } - - doTestsBlock(t, tests, EXTENSION_TITLEBLOCK) - -} diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go b/Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go deleted file mode 100644 index fb3bdec8c..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go +++ /dev/null @@ -1,859 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Unit tests for inline parsing -// - -package blackfriday - -import ( - "regexp" - "testing" - - "strings" -) - -func runMarkdownInline(input string, extensions, htmlFlags int, params HtmlRendererParameters) string { - extensions |= EXTENSION_AUTOLINK - extensions |= EXTENSION_STRIKETHROUGH - - htmlFlags |= HTML_USE_XHTML - - renderer := HtmlRendererWithParameters(htmlFlags, "", "", params) - - return string(Markdown([]byte(input), renderer, extensions)) -} - -func doTestsInline(t *testing.T, tests []string) { - doTestsInlineParam(t, tests, 0, 0, HtmlRendererParameters{}) -} - -func doLinkTestsInline(t *testing.T, tests []string) { - doTestsInline(t, tests) - - prefix := "http://localhost" - params := HtmlRendererParameters{AbsolutePrefix: prefix} - transformTests := transformLinks(tests, prefix) - doTestsInlineParam(t, transformTests, 0, 0, params) - doTestsInlineParam(t, transformTests, 0, commonHtmlFlags, params) -} - -func doSafeTestsInline(t *testing.T, tests []string) { - doTestsInlineParam(t, tests, 0, HTML_SAFELINK, HtmlRendererParameters{}) - - // All the links in this test should not have the prefix appended, so - // just rerun it with different parameters and the same expectations. - prefix := "http://localhost" - params := HtmlRendererParameters{AbsolutePrefix: prefix} - transformTests := transformLinks(tests, prefix) - doTestsInlineParam(t, transformTests, 0, HTML_SAFELINK, params) -} - -func doTestsInlineParam(t *testing.T, tests []string, extensions, htmlFlags int, - params HtmlRendererParameters) { - // catch and report panics - var candidate string - /* - defer func() { - if err := recover(); err != nil { - t.Errorf("\npanic while processing [%#v] (%v)\n", candidate, err) - } - }() - */ - - for i := 0; i+1 < len(tests); i += 2 { - input := tests[i] - candidate = input - expected := tests[i+1] - actual := runMarkdownInline(candidate, extensions, htmlFlags, params) - if actual != expected { - t.Errorf("\nInput [%#v]\nExpected[%#v]\nActual [%#v]", - candidate, expected, actual) - } - - // now test every substring to stress test bounds checking - if !testing.Short() { - for start := 0; start < len(input); start++ { - for end := start + 1; end <= len(input); end++ { - candidate = input[start:end] - _ = runMarkdownInline(candidate, extensions, htmlFlags, params) - } - } - } - } -} - -func transformLinks(tests []string, prefix string) []string { - newTests := make([]string, len(tests)) - anchorRe := regexp.MustCompile(`nothing inline

\n", - - "simple *inline* test\n", - "

simple inline test

\n", - - "*at the* beginning\n", - "

at the beginning

\n", - - "at the *end*\n", - "

at the end

\n", - - "*try two* in *one line*\n", - "

try two in one line

\n", - - "over *two\nlines* test\n", - "

over two\nlines test

\n", - - "odd *number of* markers* here\n", - "

odd number of markers* here

\n", - - "odd *number\nof* markers* here\n", - "

odd number\nof markers* here

\n", - - "simple _inline_ test\n", - "

simple inline test

\n", - - "_at the_ beginning\n", - "

at the beginning

\n", - - "at the _end_\n", - "

at the end

\n", - - "_try two_ in _one line_\n", - "

try two in one line

\n", - - "over _two\nlines_ test\n", - "

over two\nlines test

\n", - - "odd _number of_ markers_ here\n", - "

odd number of markers_ here

\n", - - "odd _number\nof_ markers_ here\n", - "

odd number\nof markers_ here

\n", - - "mix of *markers_\n", - "

mix of *markers_

\n", - } - doTestsInline(t, tests) -} - -func TestStrong(t *testing.T) { - var tests = []string{ - "nothing inline\n", - "

nothing inline

\n", - - "simple **inline** test\n", - "

simple inline test

\n", - - "**at the** beginning\n", - "

at the beginning

\n", - - "at the **end**\n", - "

at the end

\n", - - "**try two** in **one line**\n", - "

try two in one line

\n", - - "over **two\nlines** test\n", - "

over two\nlines test

\n", - - "odd **number of** markers** here\n", - "

odd number of markers** here

\n", - - "odd **number\nof** markers** here\n", - "

odd number\nof markers** here

\n", - - "simple __inline__ test\n", - "

simple inline test

\n", - - "__at the__ beginning\n", - "

at the beginning

\n", - - "at the __end__\n", - "

at the end

\n", - - "__try two__ in __one line__\n", - "

try two in one line

\n", - - "over __two\nlines__ test\n", - "

over two\nlines test

\n", - - "odd __number of__ markers__ here\n", - "

odd number of markers__ here

\n", - - "odd __number\nof__ markers__ here\n", - "

odd number\nof markers__ here

\n", - - "mix of **markers__\n", - "

mix of **markers__

\n", - } - doTestsInline(t, tests) -} - -func TestEmphasisMix(t *testing.T) { - var tests = []string{ - "***triple emphasis***\n", - "

triple emphasis

\n", - - "***triple\nemphasis***\n", - "

triple\nemphasis

\n", - - "___triple emphasis___\n", - "

triple emphasis

\n", - - "***triple emphasis___\n", - "

***triple emphasis___

\n", - - "*__triple emphasis__*\n", - "

triple emphasis

\n", - - "__*triple emphasis*__\n", - "

triple emphasis

\n", - - "**improper *nesting** is* bad\n", - "

improper *nesting is* bad

\n", - - "*improper **nesting* is** bad\n", - "

improper **nesting is** bad

\n", - } - doTestsInline(t, tests) -} - -func TestEmphasisLink(t *testing.T) { - var tests = []string{ - "[first](before) *text[second] (inside)text* [third](after)\n", - "

first textsecondtext third

\n", - - "*incomplete [link] definition*\n", - "

incomplete [link] definition

\n", - - "*it's [emphasis*] (not link)\n", - "

it's [emphasis] (not link)

\n", - - "*it's [emphasis*] and *[asterisk]\n", - "

it's [emphasis] and *[asterisk]

\n", - } - doTestsInline(t, tests) -} - -func TestStrikeThrough(t *testing.T) { - var tests = []string{ - "nothing inline\n", - "

nothing inline

\n", - - "simple ~~inline~~ test\n", - "

simple inline test

\n", - - "~~at the~~ beginning\n", - "

at the beginning

\n", - - "at the ~~end~~\n", - "

at the end

\n", - - "~~try two~~ in ~~one line~~\n", - "

try two in one line

\n", - - "over ~~two\nlines~~ test\n", - "

over two\nlines test

\n", - - "odd ~~number of~~ markers~~ here\n", - "

odd number of markers~~ here

\n", - - "odd ~~number\nof~~ markers~~ here\n", - "

odd number\nof markers~~ here

\n", - } - doTestsInline(t, tests) -} - -func TestCodeSpan(t *testing.T) { - var tests = []string{ - "`source code`\n", - "

source code

\n", - - "` source code with spaces `\n", - "

source code with spaces

\n", - - "` source code with spaces `not here\n", - "

source code with spacesnot here

\n", - - "a `single marker\n", - "

a `single marker

\n", - - "a single multi-tick marker with ``` no text\n", - "

a single multi-tick marker with ``` no text

\n", - - "markers with ` ` a space\n", - "

markers with a space

\n", - - "`source code` and a `stray\n", - "

source code and a `stray

\n", - - "`source *with* _awkward characters_ in it`\n", - "

source *with* _awkward characters_ in it

\n", - - "`split over\ntwo lines`\n", - "

split over\ntwo lines

\n", - - "```multiple ticks``` for the marker\n", - "

multiple ticks for the marker

\n", - - "```multiple ticks `with` ticks inside```\n", - "

multiple ticks `with` ticks inside

\n", - } - doTestsInline(t, tests) -} - -func TestLineBreak(t *testing.T) { - var tests = []string{ - "this line \nhas a break\n", - "

this line
\nhas a break

\n", - - "this line \ndoes not\n", - "

this line\ndoes not

\n", - - "this has an \nextra space\n", - "

this has an
\nextra space

\n", - } - doTestsInline(t, tests) -} - -func TestInlineLink(t *testing.T) { - var tests = []string{ - "[foo](/bar/)\n", - "

foo

\n", - - "[foo with a title](/bar/ \"title\")\n", - "

foo with a title

\n", - - "[foo with a title](/bar/\t\"title\")\n", - "

foo with a title

\n", - - "[foo with a title](/bar/ \"title\" )\n", - "

foo with a title

\n", - - "[foo with a title](/bar/ title with no quotes)\n", - "

foo with a title

\n", - - "[foo]()\n", - "

[foo]()

\n", - - "![foo](/bar/)\n", - "

\"foo\"\n

\n", - - "![foo with a title](/bar/ \"title\")\n", - "

\"foo\n

\n", - - "![foo with a title](/bar/\t\"title\")\n", - "

\"foo\n

\n", - - "![foo with a title](/bar/ \"title\" )\n", - "

\"foo\n

\n", - - "![foo with a title](/bar/ title with no quotes)\n", - "

\"foo\n

\n", - - "![](img.jpg)\n", - "

\"\"\n

\n", - - "[link](url)\n", - "

link

\n", - - "![foo]()\n", - "

![foo]()

\n", - - "[a link]\t(/with_a_tab/)\n", - "

a link

\n", - - "[a link] (/with_spaces/)\n", - "

a link

\n", - - "[text (with) [[nested] (brackets)]](/url/)\n", - "

text (with) [[nested] (brackets)]

\n", - - "[text (with) [broken nested] (brackets)]](/url/)\n", - "

[text (with) broken nested]](/url/)

\n", - - "[text\nwith a newline](/link/)\n", - "

text\nwith a newline

\n", - - "[text in brackets] [followed](/by a link/)\n", - "

[text in brackets] followed

\n", - - "[link with\\] a closing bracket](/url/)\n", - "

link with] a closing bracket

\n", - - "[link with\\[ an opening bracket](/url/)\n", - "

link with[ an opening bracket

\n", - - "[link with\\) a closing paren](/url/)\n", - "

link with) a closing paren

\n", - - "[link with\\( an opening paren](/url/)\n", - "

link with( an opening paren

\n", - - "[link]( with whitespace)\n", - "

link

\n", - - "[link]( with whitespace )\n", - "

link

\n", - - "[![image](someimage)](with image)\n", - "

\"image\"\n

\n", - - "[link](url \"one quote)\n", - "

link

\n", - - "[link](url 'one quote)\n", - "

link

\n", - - "[link]()\n", - "

link

\n", - - "[link & ampersand](/url/)\n", - "

link & ampersand

\n", - - "[link & ampersand](/url/)\n", - "

link & ampersand

\n", - - "[link](/url/&query)\n", - "

link

\n", - - "[[t]](/t)\n", - "

[t]

\n", - } - doLinkTestsInline(t, tests) - -} - -func TestNofollowLink(t *testing.T) { - var tests = []string{ - "[foo](http://bar.com/foo/)\n", - "

foo

\n", - - "[foo](/bar/)\n", - "

foo

\n", - } - doTestsInlineParam(t, tests, 0, HTML_SAFELINK|HTML_NOFOLLOW_LINKS, - HtmlRendererParameters{}) -} - -func TestHrefTargetBlank(t *testing.T) { - var tests = []string{ - // internal link - "[foo](/bar/)\n", - "

foo

\n", - - "[foo](http://example.com)\n", - "

foo

\n", - } - doTestsInlineParam(t, tests, 0, HTML_SAFELINK|HTML_HREF_TARGET_BLANK, HtmlRendererParameters{}) -} - -func TestSafeInlineLink(t *testing.T) { - var tests = []string{ - "[foo](/bar/)\n", - "

foo

\n", - - "[foo](http://bar/)\n", - "

foo

\n", - - "[foo](https://bar/)\n", - "

foo

\n", - - "[foo](ftp://bar/)\n", - "

foo

\n", - - "[foo](mailto://bar/)\n", - "

foo

\n", - - // Not considered safe - "[foo](baz://bar/)\n", - "

foo

\n", - } - doSafeTestsInline(t, tests) -} - -func TestReferenceLink(t *testing.T) { - var tests = []string{ - "[link][ref]\n", - "

[link][ref]

\n", - - "[link][ref]\n [ref]: /url/ \"title\"\n", - "

link

\n", - - "[link][ref]\n [ref]: /url/\n", - "

link

\n", - - " [ref]: /url/\n", - "", - - " [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n", - "", - - " [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n [4spaces]: /url/\n", - "
[4spaces]: /url/\n
\n", - - "[hmm](ref2)\n [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n", - "

hmm

\n", - - "[ref]\n", - "

[ref]

\n", - - "[ref]\n [ref]: /url/ \"title\"\n", - "

ref

\n", - } - doLinkTestsInline(t, tests) -} - -func TestTags(t *testing.T) { - var tests = []string{ - "a tag\n", - "

a tag

\n", - - "tag\n", - "

tag

\n", - - "mismatch\n", - "

mismatch

\n", - - "a tag\n", - "

a tag

\n", - } - doTestsInline(t, tests) -} - -func TestAutoLink(t *testing.T) { - var tests = []string{ - "http://foo.com/\n", - "

http://foo.com/

\n", - - "1 http://foo.com/\n", - "

1 http://foo.com/

\n", - - "1http://foo.com/\n", - "

1http://foo.com/

\n", - - "1.http://foo.com/\n", - "

1.http://foo.com/

\n", - - "1. http://foo.com/\n", - "
    \n
  1. http://foo.com/
  2. \n
\n", - - "-http://foo.com/\n", - "

-http://foo.com/

\n", - - "- http://foo.com/\n", - "\n", - - "_http://foo.com/\n", - "

_http://foo.com/

\n", - - "令狐http://foo.com/\n", - "

令狐http://foo.com/

\n", - - "令狐 http://foo.com/\n", - "

令狐 http://foo.com/

\n", - - "ahttp://foo.com/\n", - "

ahttp://foo.com/

\n", - - ">http://foo.com/\n", - "
\n

http://foo.com/

\n
\n", - - "> http://foo.com/\n", - "
\n

http://foo.com/

\n
\n", - - "go to \n", - "

go to http://foo.com/

\n", - - "a secure \n", - "

a secure https://link.org

\n", - - "an email \n", - "

an email some@one.com

\n", - - "an email \n", - "

an email some@one.com

\n", - - "an email \n", - "

an email some@one.com

\n", - - "an ftp \n", - "

an ftp ftp://old.com

\n", - - "an ftp \n", - "

an ftp ftp:old.com

\n", - - "a link with \n", - "

a link with " + - "http://new.com?query=foo&bar

\n", - - "quotes mean a tag \n", - "

quotes mean a tag

\n", - - "quotes mean a tag \n", - "

quotes mean a tag

\n", - - "unless escaped \n", - "

unless escaped " + - "http://new.com?query="foo"&bar

\n", - - "even a > can be escaped &etc>\n", - "

even a > can be escaped " + - "http://new.com?q=>&etc

\n", - - "http://fancy.com\n", - "

http://fancy.com

\n", - - "This is a link\n", - "

This is a link

\n", - - "http://www.fancy.com/A_B.pdf\n", - "

http://www.fancy.com/A_B.pdf

\n", - - "(http://www.fancy.com/A_B (\n", - "

(http://www.fancy.com/A_B (

\n", - - "(http://www.fancy.com/A_B (part two: http://www.fancy.com/A_B)).\n", - "

(http://www.fancy.com/A_B (part two: http://www.fancy.com/A_B)).

\n", - - "http://www.foo.com
\n", - "

http://www.foo.com

\n", - - "http://foo.com/viewtopic.php?f=18&t=297", - "

http://foo.com/viewtopic.php?f=18&t=297

\n", - - "http://foo.com/viewtopic.php?param="18"zz", - "

http://foo.com/viewtopic.php?param="18"zz

\n", - - "http://foo.com/viewtopic.php?param="18"", - "

http://foo.com/viewtopic.php?param="18"

\n", - } - doLinkTestsInline(t, tests) -} - -var footnoteTests = []string{ - "testing footnotes.[^a]\n\n[^a]: This is the note\n", - `

testing footnotes.1

-
- -
- -
    -
  1. This is the note -
  2. -
-
-`, - - `testing long[^b] notes. - -[^b]: Paragraph 1 - - Paragraph 2 - - ` + "```\n\tsome code\n\t```" + ` - - Paragraph 3 - -No longer in the footnote -`, - `

testing long1 notes.

- -

No longer in the footnote

-
- -
- -
    -
  1. Paragraph 1

    - -

    Paragraph 2

    - -

    -some code -

    - -

    Paragraph 3

    -
  2. -
-
-`, - - `testing[^c] multiple[^d] notes. - -[^c]: this is [note] c - - -omg - -[^d]: this is note d - -what happens here - -[note]: /link/c - -`, - `

testing1 multiple2 notes.

- -

omg

- -

what happens here

-
- -
- -
    -
  1. this is note c -
  2. -
  3. this is note d -
  4. -
-
-`, - - "testing inline^[this is the note] notes.\n", - `

testing inline1 notes.

-
- -
- -
    -
  1. this is the note
  2. -
-
-`, - - "testing multiple[^1] types^[inline note] of notes[^2]\n\n[^2]: the second deferred note\n[^1]: the first deferred note\n\n\twhich happens to be a block\n", - `

testing multiple1 types2 of notes3

-
- -
- -
    -
  1. the first deferred note

    - -

    which happens to be a block

    -
  2. -
  3. inline note
  4. -
  5. the second deferred note -
  6. -
-
-`, - - `This is a footnote[^1]^[and this is an inline footnote] - -[^1]: the footnote text. - - may be multiple paragraphs. -`, - `

This is a footnote12

-
- -
- -
    -
  1. the footnote text.

    - -

    may be multiple paragraphs.

    -
  2. -
  3. and this is an inline footnote
  4. -
-
-`, - - "empty footnote[^]\n\n[^]: fn text", - "

empty footnote1

\n
\n\n
\n\n
    \n
  1. fn text\n
  2. \n
\n
\n", -} - -func TestFootnotes(t *testing.T) { - doTestsInlineParam(t, footnoteTests, EXTENSION_FOOTNOTES, 0, HtmlRendererParameters{}) -} - -func TestFootnotesWithParameters(t *testing.T) { - tests := make([]string, len(footnoteTests)) - - prefix := "testPrefix" - returnText := "ret" - re := regexp.MustCompile(`(?ms)
  • (.*?)
  • `) - - // Transform the test expectations to match the parameters we're using. - for i, test := range footnoteTests { - if i%2 == 1 { - test = strings.Replace(test, "fn:", "fn:"+prefix, -1) - test = strings.Replace(test, "fnref:", "fnref:"+prefix, -1) - test = re.ReplaceAllString(test, `
  • $2 ret
  • `) - } - tests[i] = test - } - - params := HtmlRendererParameters{ - FootnoteAnchorPrefix: prefix, - FootnoteReturnLinkContents: returnText, - } - - doTestsInlineParam(t, tests, EXTENSION_FOOTNOTES, HTML_FOOTNOTE_RETURN_LINKS, params) -} - -func TestSmartDoubleQuotes(t *testing.T) { - var tests = []string{ - "this should be normal \"quoted\" text.\n", - "

    this should be normal “quoted” text.

    \n", - "this \" single double\n", - "

    this “ single double

    \n", - "two pair of \"some\" quoted \"text\".\n", - "

    two pair of “some” quoted “text”.

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS, HtmlRendererParameters{}) -} - -func TestSmartAngledDoubleQuotes(t *testing.T) { - var tests = []string{ - "this should be angled \"quoted\" text.\n", - "

    this should be angled «quoted» text.

    \n", - "this \" single double\n", - "

    this « single double

    \n", - "two pair of \"some\" quoted \"text\".\n", - "

    two pair of «some» quoted «text».

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_ANGLED_QUOTES, HtmlRendererParameters{}) -} - -func TestSmartFractions(t *testing.T) { - var tests = []string{ - "1/2, 1/4 and 3/4; 1/4th and 3/4ths\n", - "

    ½, ¼ and ¾; ¼th and ¾ths

    \n", - "1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.\n", - "

    1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS, HtmlRendererParameters{}) - - tests = []string{ - "1/2, 2/3, 81/100 and 1000000/1048576.\n", - "

    12, 23, 81100 and 10000001048576.

    \n", - "1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.\n", - "

    1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_FRACTIONS, HtmlRendererParameters{}) -} diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Amps and angle encoding.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Amps and angle encoding.html deleted file mode 100644 index 483f8ffa1..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Amps and angle encoding.html +++ /dev/null @@ -1,17 +0,0 @@ -

    AT&T has an ampersand in their name.

    - -

    AT&T is another way to write it.

    - -

    This & that.

    - -

    4 < 5.

    - -

    6 > 5.

    - -

    Here's a link with an ampersand in the URL.

    - -

    Here's a link with an amersand in the link text: AT&T.

    - -

    Here's an inline link.

    - -

    Here's an inline link.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Amps and angle encoding.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Amps and angle encoding.text deleted file mode 100644 index 0e9527f93..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Amps and angle encoding.text +++ /dev/null @@ -1,21 +0,0 @@ -AT&T has an ampersand in their name. - -AT&T is another way to write it. - -This & that. - -4 < 5. - -6 > 5. - -Here's a [link] [1] with an ampersand in the URL. - -Here's a link with an amersand in the link text: [AT&T] [2]. - -Here's an inline [link](/script?foo=1&bar=2). - -Here's an inline [link](). - - -[1]: http://example.com/?foo=1&bar=2 -[2]: http://att.com/ "AT&T" \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Auto links.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Auto links.html deleted file mode 100644 index b1791e7f9..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Auto links.html +++ /dev/null @@ -1,18 +0,0 @@ -

    Link: http://example.com/.

    - -

    With an ampersand: http://example.com/?foo=1&bar=2

    - - - -
    -

    Blockquoted: http://example.com/

    -
    - -

    Auto-links should not occur here: <http://example.com/>

    - -
    or here: <http://example.com/>
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Auto links.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Auto links.text deleted file mode 100644 index abbc48869..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Auto links.text +++ /dev/null @@ -1,13 +0,0 @@ -Link: . - -With an ampersand: - -* In a list? -* -* It should. - -> Blockquoted: - -Auto-links should not occur here: `` - - or here: \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Backslash escapes.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Backslash escapes.html deleted file mode 100644 index a73c998f6..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Backslash escapes.html +++ /dev/null @@ -1,123 +0,0 @@ -

    These should all get escaped:

    - -

    Backslash: \

    - -

    Backtick: `

    - -

    Asterisk: *

    - -

    Underscore: _

    - -

    Left brace: {

    - -

    Right brace: }

    - -

    Left bracket: [

    - -

    Right bracket: ]

    - -

    Left paren: (

    - -

    Right paren: )

    - -

    Greater-than: >

    - -

    Hash: #

    - -

    Period: .

    - -

    Bang: !

    - -

    Plus: +

    - -

    Minus: -

    - -

    Tilde: ~

    - -

    These should not, because they occur within a code block:

    - -
    Backslash: \\
    -
    -Backtick: \`
    -
    -Asterisk: \*
    -
    -Underscore: \_
    -
    -Left brace: \{
    -
    -Right brace: \}
    -
    -Left bracket: \[
    -
    -Right bracket: \]
    -
    -Left paren: \(
    -
    -Right paren: \)
    -
    -Greater-than: \>
    -
    -Hash: \#
    -
    -Period: \.
    -
    -Bang: \!
    -
    -Plus: \+
    -
    -Minus: \-
    -
    -Tilde: \~
    -
    - -

    Nor should these, which occur in code spans:

    - -

    Backslash: \\

    - -

    Backtick: \`

    - -

    Asterisk: \*

    - -

    Underscore: \_

    - -

    Left brace: \{

    - -

    Right brace: \}

    - -

    Left bracket: \[

    - -

    Right bracket: \]

    - -

    Left paren: \(

    - -

    Right paren: \)

    - -

    Greater-than: \>

    - -

    Hash: \#

    - -

    Period: \.

    - -

    Bang: \!

    - -

    Plus: \+

    - -

    Minus: \-

    - -

    Tilde: \~

    - -

    These should get escaped, even though they're matching pairs for -other Markdown constructs:

    - -

    *asterisks*

    - -

    _underscores_

    - -

    `backticks`

    - -

    This is a code span with a literal backslash-backtick sequence: \`

    - -

    This is a tag with unescaped backticks bar.

    - -

    This is a tag with backslashes bar.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Backslash escapes.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Backslash escapes.text deleted file mode 100644 index 04c20bd3b..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Backslash escapes.text +++ /dev/null @@ -1,126 +0,0 @@ -These should all get escaped: - -Backslash: \\ - -Backtick: \` - -Asterisk: \* - -Underscore: \_ - -Left brace: \{ - -Right brace: \} - -Left bracket: \[ - -Right bracket: \] - -Left paren: \( - -Right paren: \) - -Greater-than: \> - -Hash: \# - -Period: \. - -Bang: \! - -Plus: \+ - -Minus: \- - -Tilde: \~ - - - -These should not, because they occur within a code block: - - Backslash: \\ - - Backtick: \` - - Asterisk: \* - - Underscore: \_ - - Left brace: \{ - - Right brace: \} - - Left bracket: \[ - - Right bracket: \] - - Left paren: \( - - Right paren: \) - - Greater-than: \> - - Hash: \# - - Period: \. - - Bang: \! - - Plus: \+ - - Minus: \- - - Tilde: \~ - - -Nor should these, which occur in code spans: - -Backslash: `\\` - -Backtick: `` \` `` - -Asterisk: `\*` - -Underscore: `\_` - -Left brace: `\{` - -Right brace: `\}` - -Left bracket: `\[` - -Right bracket: `\]` - -Left paren: `\(` - -Right paren: `\)` - -Greater-than: `\>` - -Hash: `\#` - -Period: `\.` - -Bang: `\!` - -Plus: `\+` - -Minus: `\-` - -Tilde: `\~` - - -These should get escaped, even though they're matching pairs for -other Markdown constructs: - -\*asterisks\* - -\_underscores\_ - -\`backticks\` - -This is a code span with a literal backslash-backtick sequence: `` \` `` - -This is a tag with unescaped backticks bar. - -This is a tag with backslashes bar. diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Blockquotes with code blocks.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Blockquotes with code blocks.html deleted file mode 100644 index 360fa9b14..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Blockquotes with code blocks.html +++ /dev/null @@ -1,15 +0,0 @@ -
    -

    Example:

    - -
    sub status {
    -    print "working";
    -}
    -
    - -

    Or:

    - -
    sub status {
    -    return "working";
    -}
    -
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Blockquotes with code blocks.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Blockquotes with code blocks.text deleted file mode 100644 index c31d17104..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Blockquotes with code blocks.text +++ /dev/null @@ -1,11 +0,0 @@ -> Example: -> -> sub status { -> print "working"; -> } -> -> Or: -> -> sub status { -> return "working"; -> } diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Blocks.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Blocks.html deleted file mode 100644 index 32703f5cb..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Blocks.html +++ /dev/null @@ -1,18 +0,0 @@ -
    code block on the first line
    -
    - -

    Regular text.

    - -
    code block indented by spaces
    -
    - -

    Regular text.

    - -
    the lines in this block  
    -all contain trailing spaces  
    -
    - -

    Regular Text.

    - -
    code block on the last line
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Blocks.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Blocks.text deleted file mode 100644 index b54b09285..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Blocks.text +++ /dev/null @@ -1,14 +0,0 @@ - code block on the first line - -Regular text. - - code block indented by spaces - -Regular text. - - the lines in this block - all contain trailing spaces - -Regular Text. - - code block on the last line \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Spans.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Spans.html deleted file mode 100644 index ef85f95e7..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Spans.html +++ /dev/null @@ -1,5 +0,0 @@ -

    <test a=" content of attribute ">

    - -

    Fix for backticks within HTML tag: like this

    - -

    Here's how you put `backticks` in a code span.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Spans.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Spans.text deleted file mode 100644 index 750a1973d..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Code Spans.text +++ /dev/null @@ -1,6 +0,0 @@ -`` - -Fix for backticks within HTML tag: like this - -Here's how you put `` `backticks` `` in a code span. - diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines no empty line before block.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines no empty line before block.html deleted file mode 100644 index fc253194c..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines no empty line before block.html +++ /dev/null @@ -1,14 +0,0 @@ -

    In Markdown 1.0.0 and earlier. Version

    - -
      -
    1. This line turns into a list item. -Because a hard-wrapped line in the -middle of a paragraph looked like a -list item.
    2. -
    - -

    Here's one with a bullet.

    - -
      -
    • criminey.
    • -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines no empty line before block.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines no empty line before block.text deleted file mode 100644 index f8a5b27bf..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines no empty line before block.text +++ /dev/null @@ -1,8 +0,0 @@ -In Markdown 1.0.0 and earlier. Version -8. This line turns into a list item. -Because a hard-wrapped line in the -middle of a paragraph looked like a -list item. - -Here's one with a bullet. -* criminey. diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines.html deleted file mode 100644 index e21ac79a2..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines.html +++ /dev/null @@ -1,8 +0,0 @@ -

    In Markdown 1.0.0 and earlier. Version -8. This line turns into a list item. -Because a hard-wrapped line in the -middle of a paragraph looked like a -list item.

    - -

    Here's one with a bullet. -* criminey.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines.text deleted file mode 100644 index f8a5b27bf..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Hard-wrapped paragraphs with list-like lines.text +++ /dev/null @@ -1,8 +0,0 @@ -In Markdown 1.0.0 and earlier. Version -8. This line turns into a list item. -Because a hard-wrapped line in the -middle of a paragraph looked like a -list item. - -Here's one with a bullet. -* criminey. diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Horizontal rules.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Horizontal rules.html deleted file mode 100644 index e60d4ba25..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Horizontal rules.html +++ /dev/null @@ -1,71 +0,0 @@ -

    Dashes:

    - -
    - -
    - -
    - -
    - -
    ---
    -
    - -
    - -
    - -
    - -
    - -
    - - -
    -
    - -

    Asterisks:

    - -
    - -
    - -
    - -
    - -
    ***
    -
    - -
    - -
    - -
    - -
    - -
    * * *
    -
    - -

    Underscores:

    - -
    - -
    - -
    - -
    - -
    ___
    -
    - -
    - -
    - -
    - -
    - -
    _ _ _
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Horizontal rules.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Horizontal rules.text deleted file mode 100644 index 1594bda27..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Horizontal rules.text +++ /dev/null @@ -1,67 +0,0 @@ -Dashes: - ---- - - --- - - --- - - --- - - --- - -- - - - - - - - - - - - - - - - - - - - - - - - - -Asterisks: - -*** - - *** - - *** - - *** - - *** - -* * * - - * * * - - * * * - - * * * - - * * * - - -Underscores: - -___ - - ___ - - ___ - - ___ - - ___ - -_ _ _ - - _ _ _ - - _ _ _ - - _ _ _ - - _ _ _ diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Advanced).html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Advanced).html deleted file mode 100644 index 3af9cafb1..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Advanced).html +++ /dev/null @@ -1,15 +0,0 @@ -

    Simple block on one line:

    - -
    foo
    - -

    And nested without indentation:

    - -
    -
    -
    -foo -
    -
    -
    -
    bar
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Advanced).text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Advanced).text deleted file mode 100644 index 86b7206d2..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Advanced).text +++ /dev/null @@ -1,15 +0,0 @@ -Simple block on one line: - -
    foo
    - -And nested without indentation: - -
    -
    -
    -foo -
    -
    -
    -
    bar
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Simple).html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Simple).html deleted file mode 100644 index 6bf78f8fc..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Simple).html +++ /dev/null @@ -1,72 +0,0 @@ -

    Here's a simple block:

    - -
    - foo -
    - -

    This should be a code block, though:

    - -
    <div>
    -    foo
    -</div>
    -
    - -

    As should this:

    - -
    <div>foo</div>
    -
    - -

    Now, nested:

    - -
    -
    -
    - foo -
    -
    -
    - -

    This should just be an HTML comment:

    - - - -

    Multiline:

    - - - -

    Code block:

    - -
    <!-- Comment -->
    -
    - -

    Just plain comment, with trailing spaces on the line:

    - - - -

    Code:

    - -
    <hr />
    -
    - -

    Hr's:

    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Simple).text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Simple).text deleted file mode 100644 index 14aa2dc27..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML (Simple).text +++ /dev/null @@ -1,69 +0,0 @@ -Here's a simple block: - -
    - foo -
    - -This should be a code block, though: - -
    - foo -
    - -As should this: - -
    foo
    - -Now, nested: - -
    -
    -
    - foo -
    -
    -
    - -This should just be an HTML comment: - - - -Multiline: - - - -Code block: - - - -Just plain comment, with trailing spaces on the line: - - - -Code: - -
    - -Hr's: - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML comments.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML comments.html deleted file mode 100644 index 3f167a161..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML comments.html +++ /dev/null @@ -1,13 +0,0 @@ -

    Paragraph one.

    - - - - - -

    Paragraph two.

    - - - -

    The end.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML comments.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML comments.text deleted file mode 100644 index 41d830d03..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Inline HTML comments.text +++ /dev/null @@ -1,13 +0,0 @@ -Paragraph one. - - - - - -Paragraph two. - - - -The end. diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, inline style.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, inline style.html deleted file mode 100644 index 5802f2deb..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, inline style.html +++ /dev/null @@ -1,11 +0,0 @@ -

    Just a URL.

    - -

    URL and title.

    - -

    URL and title.

    - -

    URL and title.

    - -

    URL and title.

    - -

    [Empty]().

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, inline style.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, inline style.text deleted file mode 100644 index 09017a90c..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, inline style.text +++ /dev/null @@ -1,12 +0,0 @@ -Just a [URL](/url/). - -[URL and title](/url/ "title"). - -[URL and title](/url/ "title preceded by two spaces"). - -[URL and title](/url/ "title preceded by a tab"). - -[URL and title](/url/ "title has spaces afterward" ). - - -[Empty](). diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, reference style.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, reference style.html deleted file mode 100644 index bebefdee2..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, reference style.html +++ /dev/null @@ -1,52 +0,0 @@ -

    Foo bar.

    - -

    Foo bar.

    - -

    Foo bar.

    - -

    With embedded [brackets].

    - -

    Indented once.

    - -

    Indented twice.

    - -

    Indented thrice.

    - -

    Indented [four][] times.

    - -
    [four]: /url
    -
    - -
    - -

    this should work

    - -

    So should this.

    - -

    And this.

    - -

    And this.

    - -

    And this.

    - -

    But not [that] [].

    - -

    Nor [that][].

    - -

    Nor [that].

    - -

    [Something in brackets like this should work]

    - -

    [Same with this.]

    - -

    In this case, this points to something else.

    - -

    Backslashing should suppress [this] and [this].

    - -
    - -

    Here's one where the link -breaks across lines.

    - -

    Here's another where the link -breaks across lines, but with a line-ending space.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, reference style.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, reference style.text deleted file mode 100644 index 341ec88e3..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, reference style.text +++ /dev/null @@ -1,71 +0,0 @@ -Foo [bar] [1]. - -Foo [bar][1]. - -Foo [bar] -[1]. - -[1]: /url/ "Title" - - -With [embedded [brackets]] [b]. - - -Indented [once][]. - -Indented [twice][]. - -Indented [thrice][]. - -Indented [four][] times. - - [once]: /url - - [twice]: /url - - [thrice]: /url - - [four]: /url - - -[b]: /url/ - -* * * - -[this] [this] should work - -So should [this][this]. - -And [this] []. - -And [this][]. - -And [this]. - -But not [that] []. - -Nor [that][]. - -Nor [that]. - -[Something in brackets like [this][] should work] - -[Same with [this].] - -In this case, [this](/somethingelse/) points to something else. - -Backslashing should suppress \[this] and [this\]. - -[this]: foo - - -* * * - -Here's one where the [link -breaks] across lines. - -Here's another where the [link -breaks] across lines, but with a line-ending space. - - -[link breaks]: /url/ diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, shortcut references.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, shortcut references.html deleted file mode 100644 index 0b5e1d64e..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, shortcut references.html +++ /dev/null @@ -1,9 +0,0 @@ -

    This is the simple case.

    - -

    This one has a line -break.

    - -

    This one has a line -break with a line-ending space.

    - -

    this and the other

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, shortcut references.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, shortcut references.text deleted file mode 100644 index 8c44c98fe..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Links, shortcut references.text +++ /dev/null @@ -1,20 +0,0 @@ -This is the [simple case]. - -[simple case]: /simple - - - -This one has a [line -break]. - -This one has a [line -break] with a line-ending space. - -[line break]: /foo - - -[this] [that] and the [other] - -[this]: /this -[that]: /that -[other]: /other diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Literal quotes in titles.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Literal quotes in titles.html deleted file mode 100644 index 611c1ac61..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Literal quotes in titles.html +++ /dev/null @@ -1,3 +0,0 @@ -

    Foo bar.

    - -

    Foo bar.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Literal quotes in titles.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Literal quotes in titles.text deleted file mode 100644 index 29d0e4235..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Literal quotes in titles.text +++ /dev/null @@ -1,7 +0,0 @@ -Foo [bar][]. - -Foo [bar](/url/ "Title with "quotes" inside"). - - - [bar]: /url/ "Title with "quotes" inside" - diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Basics.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Basics.html deleted file mode 100644 index ea3a61c39..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Basics.html +++ /dev/null @@ -1,314 +0,0 @@ -

    Markdown: Basics

    - - - -

    Getting the Gist of Markdown's Formatting Syntax

    - -

    This page offers a brief overview of what it's like to use Markdown. -The syntax page provides complete, detailed documentation for -every feature, but Markdown should be very easy to pick up simply by -looking at a few examples of it in action. The examples on this page -are written in a before/after style, showing example syntax and the -HTML output produced by Markdown.

    - -

    It's also helpful to simply try Markdown out; the Dingus is a -web application that allows you type your own Markdown-formatted text -and translate it to XHTML.

    - -

    Note: This document is itself written using Markdown; you -can see the source for it by adding '.text' to the URL.

    - -

    Paragraphs, Headers, Blockquotes

    - -

    A paragraph is simply one or more consecutive lines of text, separated -by one or more blank lines. (A blank line is any line that looks like a -blank line -- a line containing nothing spaces or tabs is considered -blank.) Normal paragraphs should not be intended with spaces or tabs.

    - -

    Markdown offers two styles of headers: Setext and atx. -Setext-style headers for <h1> and <h2> are created by -"underlining" with equal signs (=) and hyphens (-), respectively. -To create an atx-style header, you put 1-6 hash marks (#) at the -beginning of the line -- the number of hashes equals the resulting -HTML header level.

    - -

    Blockquotes are indicated using email-style '>' angle brackets.

    - -

    Markdown:

    - -
    A First Level Header
    -====================
    -
    -A Second Level Header
    ----------------------
    -
    -Now is the time for all good men to come to
    -the aid of their country. This is just a
    -regular paragraph.
    -
    -The quick brown fox jumped over the lazy
    -dog's back.
    -
    -### Header 3
    -
    -> This is a blockquote.
    -> 
    -> This is the second paragraph in the blockquote.
    ->
    -> ## This is an H2 in a blockquote
    -
    - -

    Output:

    - -
    <h1>A First Level Header</h1>
    -
    -<h2>A Second Level Header</h2>
    -
    -<p>Now is the time for all good men to come to
    -the aid of their country. This is just a
    -regular paragraph.</p>
    -
    -<p>The quick brown fox jumped over the lazy
    -dog's back.</p>
    -
    -<h3>Header 3</h3>
    -
    -<blockquote>
    -    <p>This is a blockquote.</p>
    -
    -    <p>This is the second paragraph in the blockquote.</p>
    -
    -    <h2>This is an H2 in a blockquote</h2>
    -</blockquote>
    -
    - -

    Phrase Emphasis

    - -

    Markdown uses asterisks and underscores to indicate spans of emphasis.

    - -

    Markdown:

    - -
    Some of these words *are emphasized*.
    -Some of these words _are emphasized also_.
    -
    -Use two asterisks for **strong emphasis**.
    -Or, if you prefer, __use two underscores instead__.
    -
    - -

    Output:

    - -
    <p>Some of these words <em>are emphasized</em>.
    -Some of these words <em>are emphasized also</em>.</p>
    -
    -<p>Use two asterisks for <strong>strong emphasis</strong>.
    -Or, if you prefer, <strong>use two underscores instead</strong>.</p>
    -
    - -

    Lists

    - -

    Unordered (bulleted) lists use asterisks, pluses, and hyphens (*, -+, and -) as list markers. These three markers are -interchangable; this:

    - -
    *   Candy.
    -*   Gum.
    -*   Booze.
    -
    - -

    this:

    - -
    +   Candy.
    -+   Gum.
    -+   Booze.
    -
    - -

    and this:

    - -
    -   Candy.
    --   Gum.
    --   Booze.
    -
    - -

    all produce the same output:

    - -
    <ul>
    -<li>Candy.</li>
    -<li>Gum.</li>
    -<li>Booze.</li>
    -</ul>
    -
    - -

    Ordered (numbered) lists use regular numbers, followed by periods, as -list markers:

    - -
    1.  Red
    -2.  Green
    -3.  Blue
    -
    - -

    Output:

    - -
    <ol>
    -<li>Red</li>
    -<li>Green</li>
    -<li>Blue</li>
    -</ol>
    -
    - -

    If you put blank lines between items, you'll get <p> tags for the -list item text. You can create multi-paragraph list items by indenting -the paragraphs by 4 spaces or 1 tab:

    - -
    *   A list item.
    -
    -    With multiple paragraphs.
    -
    -*   Another item in the list.
    -
    - -

    Output:

    - -
    <ul>
    -<li><p>A list item.</p>
    -<p>With multiple paragraphs.</p></li>
    -<li><p>Another item in the list.</p></li>
    -</ul>
    -
    - -

    Links

    - -

    Markdown supports two styles for creating links: inline and -reference. With both styles, you use square brackets to delimit the -text you want to turn into a link.

    - -

    Inline-style links use parentheses immediately after the link text. -For example:

    - -
    This is an [example link](http://example.com/).
    -
    - -

    Output:

    - -
    <p>This is an <a href="http://example.com/">
    -example link</a>.</p>
    -
    - -

    Optionally, you may include a title attribute in the parentheses:

    - -
    This is an [example link](http://example.com/ "With a Title").
    -
    - -

    Output:

    - -
    <p>This is an <a href="http://example.com/" title="With a Title">
    -example link</a>.</p>
    -
    - -

    Reference-style links allow you to refer to your links by names, which -you define elsewhere in your document:

    - -
    I get 10 times more traffic from [Google][1] than from
    -[Yahoo][2] or [MSN][3].
    -
    -[1]: http://google.com/        "Google"
    -[2]: http://search.yahoo.com/  "Yahoo Search"
    -[3]: http://search.msn.com/    "MSN Search"
    -
    - -

    Output:

    - -
    <p>I get 10 times more traffic from <a href="http://google.com/"
    -title="Google">Google</a> than from <a href="http://search.yahoo.com/"
    -title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/"
    -title="MSN Search">MSN</a>.</p>
    -
    - -

    The title attribute is optional. Link names may contain letters, -numbers and spaces, but are not case sensitive:

    - -
    I start my morning with a cup of coffee and
    -[The New York Times][NY Times].
    -
    -[ny times]: http://www.nytimes.com/
    -
    - -

    Output:

    - -
    <p>I start my morning with a cup of coffee and
    -<a href="http://www.nytimes.com/">The New York Times</a>.</p>
    -
    - -

    Images

    - -

    Image syntax is very much like link syntax.

    - -

    Inline (titles are optional):

    - -
    ![alt text](/path/to/img.jpg "Title")
    -
    - -

    Reference-style:

    - -
    ![alt text][id]
    -
    -[id]: /path/to/img.jpg "Title"
    -
    - -

    Both of the above examples produce the same output:

    - -
    <img src="/path/to/img.jpg" alt="alt text" title="Title" />
    -
    - -

    Code

    - -

    In a regular paragraph, you can create code span by wrapping text in -backtick quotes. Any ampersands (&) and angle brackets (< or ->) will automatically be translated into HTML entities. This makes -it easy to use Markdown to write about HTML example code:

    - -
    I strongly recommend against using any `<blink>` tags.
    -
    -I wish SmartyPants used named entities like `&mdash;`
    -instead of decimal-encoded entites like `&#8212;`.
    -
    - -

    Output:

    - -
    <p>I strongly recommend against using any
    -<code>&lt;blink&gt;</code> tags.</p>
    -
    -<p>I wish SmartyPants used named entities like
    -<code>&amp;mdash;</code> instead of decimal-encoded
    -entites like <code>&amp;#8212;</code>.</p>
    -
    - -

    To specify an entire block of pre-formatted code, indent every line of -the block by 4 spaces or 1 tab. Just like with code spans, &, <, -and > characters will be escaped automatically.

    - -

    Markdown:

    - -
    If you want your page to validate under XHTML 1.0 Strict,
    -you've got to put paragraph tags in your blockquotes:
    -
    -    <blockquote>
    -        <p>For example.</p>
    -    </blockquote>
    -
    - -

    Output:

    - -
    <p>If you want your page to validate under XHTML 1.0 Strict,
    -you've got to put paragraph tags in your blockquotes:</p>
    -
    -<pre><code>&lt;blockquote&gt;
    -    &lt;p&gt;For example.&lt;/p&gt;
    -&lt;/blockquote&gt;
    -</code></pre>
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Basics.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Basics.text deleted file mode 100644 index 486055ca7..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Basics.text +++ /dev/null @@ -1,306 +0,0 @@ -Markdown: Basics -================ - - - - -Getting the Gist of Markdown's Formatting Syntax ------------------------------------------------- - -This page offers a brief overview of what it's like to use Markdown. -The [syntax page] [s] provides complete, detailed documentation for -every feature, but Markdown should be very easy to pick up simply by -looking at a few examples of it in action. The examples on this page -are written in a before/after style, showing example syntax and the -HTML output produced by Markdown. - -It's also helpful to simply try Markdown out; the [Dingus] [d] is a -web application that allows you type your own Markdown-formatted text -and translate it to XHTML. - -**Note:** This document is itself written using Markdown; you -can [see the source for it by adding '.text' to the URL] [src]. - - [s]: /projects/markdown/syntax "Markdown Syntax" - [d]: /projects/markdown/dingus "Markdown Dingus" - [src]: /projects/markdown/basics.text - - -## Paragraphs, Headers, Blockquotes ## - -A paragraph is simply one or more consecutive lines of text, separated -by one or more blank lines. (A blank line is any line that looks like a -blank line -- a line containing nothing spaces or tabs is considered -blank.) Normal paragraphs should not be intended with spaces or tabs. - -Markdown offers two styles of headers: *Setext* and *atx*. -Setext-style headers for `

    ` and `

    ` are created by -"underlining" with equal signs (`=`) and hyphens (`-`), respectively. -To create an atx-style header, you put 1-6 hash marks (`#`) at the -beginning of the line -- the number of hashes equals the resulting -HTML header level. - -Blockquotes are indicated using email-style '`>`' angle brackets. - -Markdown: - - A First Level Header - ==================== - - A Second Level Header - --------------------- - - Now is the time for all good men to come to - the aid of their country. This is just a - regular paragraph. - - The quick brown fox jumped over the lazy - dog's back. - - ### Header 3 - - > This is a blockquote. - > - > This is the second paragraph in the blockquote. - > - > ## This is an H2 in a blockquote - - -Output: - -

    A First Level Header

    - -

    A Second Level Header

    - -

    Now is the time for all good men to come to - the aid of their country. This is just a - regular paragraph.

    - -

    The quick brown fox jumped over the lazy - dog's back.

    - -

    Header 3

    - -
    -

    This is a blockquote.

    - -

    This is the second paragraph in the blockquote.

    - -

    This is an H2 in a blockquote

    -
    - - - -### Phrase Emphasis ### - -Markdown uses asterisks and underscores to indicate spans of emphasis. - -Markdown: - - Some of these words *are emphasized*. - Some of these words _are emphasized also_. - - Use two asterisks for **strong emphasis**. - Or, if you prefer, __use two underscores instead__. - -Output: - -

    Some of these words are emphasized. - Some of these words are emphasized also.

    - -

    Use two asterisks for strong emphasis. - Or, if you prefer, use two underscores instead.

    - - - -## Lists ## - -Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`, -`+`, and `-`) as list markers. These three markers are -interchangable; this: - - * Candy. - * Gum. - * Booze. - -this: - - + Candy. - + Gum. - + Booze. - -and this: - - - Candy. - - Gum. - - Booze. - -all produce the same output: - -
      -
    • Candy.
    • -
    • Gum.
    • -
    • Booze.
    • -
    - -Ordered (numbered) lists use regular numbers, followed by periods, as -list markers: - - 1. Red - 2. Green - 3. Blue - -Output: - -
      -
    1. Red
    2. -
    3. Green
    4. -
    5. Blue
    6. -
    - -If you put blank lines between items, you'll get `

    ` tags for the -list item text. You can create multi-paragraph list items by indenting -the paragraphs by 4 spaces or 1 tab: - - * A list item. - - With multiple paragraphs. - - * Another item in the list. - -Output: - -

      -
    • A list item.

      -

      With multiple paragraphs.

    • -
    • Another item in the list.

    • -
    - - - -### Links ### - -Markdown supports two styles for creating links: *inline* and -*reference*. With both styles, you use square brackets to delimit the -text you want to turn into a link. - -Inline-style links use parentheses immediately after the link text. -For example: - - This is an [example link](http://example.com/). - -Output: - -

    This is an - example link.

    - -Optionally, you may include a title attribute in the parentheses: - - This is an [example link](http://example.com/ "With a Title"). - -Output: - -

    This is an - example link.

    - -Reference-style links allow you to refer to your links by names, which -you define elsewhere in your document: - - I get 10 times more traffic from [Google][1] than from - [Yahoo][2] or [MSN][3]. - - [1]: http://google.com/ "Google" - [2]: http://search.yahoo.com/ "Yahoo Search" - [3]: http://search.msn.com/ "MSN Search" - -Output: - -

    I get 10 times more traffic from Google than from Yahoo or MSN.

    - -The title attribute is optional. Link names may contain letters, -numbers and spaces, but are *not* case sensitive: - - I start my morning with a cup of coffee and - [The New York Times][NY Times]. - - [ny times]: http://www.nytimes.com/ - -Output: - -

    I start my morning with a cup of coffee and - The New York Times.

    - - -### Images ### - -Image syntax is very much like link syntax. - -Inline (titles are optional): - - ![alt text](/path/to/img.jpg "Title") - -Reference-style: - - ![alt text][id] - - [id]: /path/to/img.jpg "Title" - -Both of the above examples produce the same output: - - alt text - - - -### Code ### - -In a regular paragraph, you can create code span by wrapping text in -backtick quotes. Any ampersands (`&`) and angle brackets (`<` or -`>`) will automatically be translated into HTML entities. This makes -it easy to use Markdown to write about HTML example code: - - I strongly recommend against using any `` tags. - - I wish SmartyPants used named entities like `—` - instead of decimal-encoded entites like `—`. - -Output: - -

    I strongly recommend against using any - <blink> tags.

    - -

    I wish SmartyPants used named entities like - &mdash; instead of decimal-encoded - entites like &#8212;.

    - - -To specify an entire block of pre-formatted code, indent every line of -the block by 4 spaces or 1 tab. Just like with code spans, `&`, `<`, -and `>` characters will be escaped automatically. - -Markdown: - - If you want your page to validate under XHTML 1.0 Strict, - you've got to put paragraph tags in your blockquotes: - -
    -

    For example.

    -
    - -Output: - -

    If you want your page to validate under XHTML 1.0 Strict, - you've got to put paragraph tags in your blockquotes:

    - -
    <blockquote>
    -        <p>For example.</p>
    -    </blockquote>
    -    
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Syntax.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Syntax.html deleted file mode 100644 index 61dde593d..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Syntax.html +++ /dev/null @@ -1,946 +0,0 @@ -

    Markdown: Syntax

    - - - - - -

    Note: This document is itself written using Markdown; you -can see the source for it by adding '.text' to the URL.

    - -
    - -

    Overview

    - -

    Philosophy

    - -

    Markdown is intended to be as easy-to-read and easy-to-write as is feasible.

    - -

    Readability, however, is emphasized above all else. A Markdown-formatted -document should be publishable as-is, as plain text, without looking -like it's been marked up with tags or formatting instructions. While -Markdown's syntax has been influenced by several existing text-to-HTML -filters -- including Setext, atx, Textile, reStructuredText, -Grutatext, and EtText -- the single biggest source of -inspiration for Markdown's syntax is the format of plain text email.

    - -

    To this end, Markdown's syntax is comprised entirely of punctuation -characters, which punctuation characters have been carefully chosen so -as to look like what they mean. E.g., asterisks around a word actually -look like *emphasis*. Markdown lists look like, well, lists. Even -blockquotes look like quoted passages of text, assuming you've ever -used email.

    - -

    Inline HTML

    - -

    Markdown's syntax is intended for one purpose: to be used as a -format for writing for the web.

    - -

    Markdown is not a replacement for HTML, or even close to it. Its -syntax is very small, corresponding only to a very small subset of -HTML tags. The idea is not to create a syntax that makes it easier -to insert HTML tags. In my opinion, HTML tags are already easy to -insert. The idea for Markdown is to make it easy to read, write, and -edit prose. HTML is a publishing format; Markdown is a writing -format. Thus, Markdown's formatting syntax only addresses issues that -can be conveyed in plain text.

    - -

    For any markup that is not covered by Markdown's syntax, you simply -use HTML itself. There's no need to preface it or delimit it to -indicate that you're switching from Markdown to HTML; you just use -the tags.

    - -

    The only restrictions are that block-level HTML elements -- e.g. <div>, -<table>, <pre>, <p>, etc. -- must be separated from surrounding -content by blank lines, and the start and end tags of the block should -not be indented with tabs or spaces. Markdown is smart enough not -to add extra (unwanted) <p> tags around HTML block-level tags.

    - -

    For example, to add an HTML table to a Markdown article:

    - -
    This is a regular paragraph.
    -
    -<table>
    -    <tr>
    -        <td>Foo</td>
    -    </tr>
    -</table>
    -
    -This is another regular paragraph.
    -
    - -

    Note that Markdown formatting syntax is not processed within block-level -HTML tags. E.g., you can't use Markdown-style *emphasis* inside an -HTML block.

    - -

    Span-level HTML tags -- e.g. <span>, <cite>, or <del> -- can be -used anywhere in a Markdown paragraph, list item, or header. If you -want, you can even use HTML tags instead of Markdown formatting; e.g. if -you'd prefer to use HTML <a> or <img> tags instead of Markdown's -link or image syntax, go right ahead.

    - -

    Unlike block-level HTML tags, Markdown syntax is processed within -span-level tags.

    - -

    Automatic Escaping for Special Characters

    - -

    In HTML, there are two characters that demand special treatment: < -and &. Left angle brackets are used to start tags; ampersands are -used to denote HTML entities. If you want to use them as literal -characters, you must escape them as entities, e.g. &lt;, and -&amp;.

    - -

    Ampersands in particular are bedeviling for web writers. If you want to -write about 'AT&T', you need to write 'AT&amp;T'. You even need to -escape ampersands within URLs. Thus, if you want to link to:

    - -
    http://images.google.com/images?num=30&q=larry+bird
    -
    - -

    you need to encode the URL as:

    - -
    http://images.google.com/images?num=30&amp;q=larry+bird
    -
    - -

    in your anchor tag href attribute. Needless to say, this is easy to -forget, and is probably the single most common source of HTML validation -errors in otherwise well-marked-up web sites.

    - -

    Markdown allows you to use these characters naturally, taking care of -all the necessary escaping for you. If you use an ampersand as part of -an HTML entity, it remains unchanged; otherwise it will be translated -into &amp;.

    - -

    So, if you want to include a copyright symbol in your article, you can write:

    - -
    &copy;
    -
    - -

    and Markdown will leave it alone. But if you write:

    - -
    AT&T
    -
    - -

    Markdown will translate it to:

    - -
    AT&amp;T
    -
    - -

    Similarly, because Markdown supports inline HTML, if you use -angle brackets as delimiters for HTML tags, Markdown will treat them as -such. But if you write:

    - -
    4 < 5
    -
    - -

    Markdown will translate it to:

    - -
    4 &lt; 5
    -
    - -

    However, inside Markdown code spans and blocks, angle brackets and -ampersands are always encoded automatically. This makes it easy to use -Markdown to write about HTML code. (As opposed to raw HTML, which is a -terrible format for writing about HTML syntax, because every single < -and & in your example code needs to be escaped.)

    - -
    - -

    Block Elements

    - -

    Paragraphs and Line Breaks

    - -

    A paragraph is simply one or more consecutive lines of text, separated -by one or more blank lines. (A blank line is any line that looks like a -blank line -- a line containing nothing but spaces or tabs is considered -blank.) Normal paragraphs should not be intended with spaces or tabs.

    - -

    The implication of the "one or more consecutive lines of text" rule is -that Markdown supports "hard-wrapped" text paragraphs. This differs -significantly from most other text-to-HTML formatters (including Movable -Type's "Convert Line Breaks" option) which translate every line break -character in a paragraph into a <br /> tag.

    - -

    When you do want to insert a <br /> break tag using Markdown, you -end a line with two or more spaces, then type return.

    - -

    Yes, this takes a tad more effort to create a <br />, but a simplistic -"every line break is a <br />" rule wouldn't work for Markdown. -Markdown's email-style blockquoting and multi-paragraph list items -work best -- and look better -- when you format them with hard breaks.

    - - - -

    Markdown supports two styles of headers, Setext and atx.

    - -

    Setext-style headers are "underlined" using equal signs (for first-level -headers) and dashes (for second-level headers). For example:

    - -
    This is an H1
    -=============
    -
    -This is an H2
    --------------
    -
    - -

    Any number of underlining ='s or -'s will work.

    - -

    Atx-style headers use 1-6 hash characters at the start of the line, -corresponding to header levels 1-6. For example:

    - -
    # This is an H1
    -
    -## This is an H2
    -
    -###### This is an H6
    -
    - -

    Optionally, you may "close" atx-style headers. This is purely -cosmetic -- you can use this if you think it looks better. The -closing hashes don't even need to match the number of hashes -used to open the header. (The number of opening hashes -determines the header level.) :

    - -
    # This is an H1 #
    -
    -## This is an H2 ##
    -
    -### This is an H3 ######
    -
    - -

    Blockquotes

    - -

    Markdown uses email-style > characters for blockquoting. If you're -familiar with quoting passages of text in an email message, then you -know how to create a blockquote in Markdown. It looks best if you hard -wrap the text and put a > before every line:

    - -
    > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
    -> consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
    -> Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
    -> 
    -> Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
    -> id sem consectetuer libero luctus adipiscing.
    -
    - -

    Markdown allows you to be lazy and only put the > before the first -line of a hard-wrapped paragraph:

    - -
    > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
    -consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
    -Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
    -
    -> Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
    -id sem consectetuer libero luctus adipiscing.
    -
    - -

    Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by -adding additional levels of >:

    - -
    > This is the first level of quoting.
    ->
    -> > This is nested blockquote.
    ->
    -> Back to the first level.
    -
    - -

    Blockquotes can contain other Markdown elements, including headers, lists, -and code blocks:

    - -
    > ## This is a header.
    -> 
    -> 1.   This is the first list item.
    -> 2.   This is the second list item.
    -> 
    -> Here's some example code:
    -> 
    ->     return shell_exec("echo $input | $markdown_script");
    -
    - -

    Any decent text editor should make email-style quoting easy. For -example, with BBEdit, you can make a selection and choose Increase -Quote Level from the Text menu.

    - -

    Lists

    - -

    Markdown supports ordered (numbered) and unordered (bulleted) lists.

    - -

    Unordered lists use asterisks, pluses, and hyphens -- interchangably --- as list markers:

    - -
    *   Red
    -*   Green
    -*   Blue
    -
    - -

    is equivalent to:

    - -
    +   Red
    -+   Green
    -+   Blue
    -
    - -

    and:

    - -
    -   Red
    --   Green
    --   Blue
    -
    - -

    Ordered lists use numbers followed by periods:

    - -
    1.  Bird
    -2.  McHale
    -3.  Parish
    -
    - -

    It's important to note that the actual numbers you use to mark the -list have no effect on the HTML output Markdown produces. The HTML -Markdown produces from the above list is:

    - -
    <ol>
    -<li>Bird</li>
    -<li>McHale</li>
    -<li>Parish</li>
    -</ol>
    -
    - -

    If you instead wrote the list in Markdown like this:

    - -
    1.  Bird
    -1.  McHale
    -1.  Parish
    -
    - -

    or even:

    - -
    3. Bird
    -1. McHale
    -8. Parish
    -
    - -

    you'd get the exact same HTML output. The point is, if you want to, -you can use ordinal numbers in your ordered Markdown lists, so that -the numbers in your source match the numbers in your published HTML. -But if you want to be lazy, you don't have to.

    - -

    If you do use lazy list numbering, however, you should still start the -list with the number 1. At some point in the future, Markdown may support -starting ordered lists at an arbitrary number.

    - -

    List markers typically start at the left margin, but may be indented by -up to three spaces. List markers must be followed by one or more spaces -or a tab.

    - -

    To make lists look nice, you can wrap items with hanging indents:

    - -
    *   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    -    Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
    -    viverra nec, fringilla in, laoreet vitae, risus.
    -*   Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
    -    Suspendisse id sem consectetuer libero luctus adipiscing.
    -
    - -

    But if you want to be lazy, you don't have to:

    - -
    *   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    -Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
    -viverra nec, fringilla in, laoreet vitae, risus.
    -*   Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
    -Suspendisse id sem consectetuer libero luctus adipiscing.
    -
    - -

    If list items are separated by blank lines, Markdown will wrap the -items in <p> tags in the HTML output. For example, this input:

    - -
    *   Bird
    -*   Magic
    -
    - -

    will turn into:

    - -
    <ul>
    -<li>Bird</li>
    -<li>Magic</li>
    -</ul>
    -
    - -

    But this:

    - -
    *   Bird
    -
    -*   Magic
    -
    - -

    will turn into:

    - -
    <ul>
    -<li><p>Bird</p></li>
    -<li><p>Magic</p></li>
    -</ul>
    -
    - -

    List items may consist of multiple paragraphs. Each subsequent -paragraph in a list item must be intended by either 4 spaces -or one tab:

    - -
    1.  This is a list item with two paragraphs. Lorem ipsum dolor
    -    sit amet, consectetuer adipiscing elit. Aliquam hendrerit
    -    mi posuere lectus.
    -
    -    Vestibulum enim wisi, viverra nec, fringilla in, laoreet
    -    vitae, risus. Donec sit amet nisl. Aliquam semper ipsum
    -    sit amet velit.
    -
    -2.  Suspendisse id sem consectetuer libero luctus adipiscing.
    -
    - -

    It looks nice if you indent every line of the subsequent -paragraphs, but here again, Markdown will allow you to be -lazy:

    - -
    *   This is a list item with two paragraphs.
    -
    -    This is the second paragraph in the list item. You're
    -only required to indent the first line. Lorem ipsum dolor
    -sit amet, consectetuer adipiscing elit.
    -
    -*   Another item in the same list.
    -
    - -

    To put a blockquote within a list item, the blockquote's > -delimiters need to be indented:

    - -
    *   A list item with a blockquote:
    -
    -    > This is a blockquote
    -    > inside a list item.
    -
    - -

    To put a code block within a list item, the code block needs -to be indented twice -- 8 spaces or two tabs:

    - -
    *   A list item with a code block:
    -
    -        <code goes here>
    -
    - -

    It's worth noting that it's possible to trigger an ordered list by -accident, by writing something like this:

    - -
    1986. What a great season.
    -
    - -

    In other words, a number-period-space sequence at the beginning of a -line. To avoid this, you can backslash-escape the period:

    - -
    1986\. What a great season.
    -
    - -

    Code Blocks

    - -

    Pre-formatted code blocks are used for writing about programming or -markup source code. Rather than forming normal paragraphs, the lines -of a code block are interpreted literally. Markdown wraps a code block -in both <pre> and <code> tags.

    - -

    To produce a code block in Markdown, simply indent every line of the -block by at least 4 spaces or 1 tab. For example, given this input:

    - -
    This is a normal paragraph:
    -
    -    This is a code block.
    -
    - -

    Markdown will generate:

    - -
    <p>This is a normal paragraph:</p>
    -
    -<pre><code>This is a code block.
    -</code></pre>
    -
    - -

    One level of indentation -- 4 spaces or 1 tab -- is removed from each -line of the code block. For example, this:

    - -
    Here is an example of AppleScript:
    -
    -    tell application "Foo"
    -        beep
    -    end tell
    -
    - -

    will turn into:

    - -
    <p>Here is an example of AppleScript:</p>
    -
    -<pre><code>tell application "Foo"
    -    beep
    -end tell
    -</code></pre>
    -
    - -

    A code block continues until it reaches a line that is not indented -(or the end of the article).

    - -

    Within a code block, ampersands (&) and angle brackets (< and >) -are automatically converted into HTML entities. This makes it very -easy to include example HTML source code using Markdown -- just paste -it and indent it, and Markdown will handle the hassle of encoding the -ampersands and angle brackets. For example, this:

    - -
        <div class="footer">
    -        &copy; 2004 Foo Corporation
    -    </div>
    -
    - -

    will turn into:

    - -
    <pre><code>&lt;div class="footer"&gt;
    -    &amp;copy; 2004 Foo Corporation
    -&lt;/div&gt;
    -</code></pre>
    -
    - -

    Regular Markdown syntax is not processed within code blocks. E.g., -asterisks are just literal asterisks within a code block. This means -it's also easy to use Markdown to write about Markdown's own syntax.

    - -

    Horizontal Rules

    - -

    You can produce a horizontal rule tag (<hr />) by placing three or -more hyphens, asterisks, or underscores on a line by themselves. If you -wish, you may use spaces between the hyphens or asterisks. Each of the -following lines will produce a horizontal rule:

    - -
    * * *
    -
    -***
    -
    -*****
    -
    -- - -
    -
    ----------------------------------------
    -
    -_ _ _
    -
    - -
    - -

    Span Elements

    - - - -

    Markdown supports two style of links: inline and reference.

    - -

    In both styles, the link text is delimited by [square brackets].

    - -

    To create an inline link, use a set of regular parentheses immediately -after the link text's closing square bracket. Inside the parentheses, -put the URL where you want the link to point, along with an optional -title for the link, surrounded in quotes. For example:

    - -
    This is [an example](http://example.com/ "Title") inline link.
    -
    -[This link](http://example.net/) has no title attribute.
    -
    - -

    Will produce:

    - -
    <p>This is <a href="http://example.com/" title="Title">
    -an example</a> inline link.</p>
    -
    -<p><a href="http://example.net/">This link</a> has no
    -title attribute.</p>
    -
    - -

    If you're referring to a local resource on the same server, you can -use relative paths:

    - -
    See my [About](/about/) page for details.
    -
    - -

    Reference-style links use a second set of square brackets, inside -which you place a label of your choosing to identify the link:

    - -
    This is [an example][id] reference-style link.
    -
    - -

    You can optionally use a space to separate the sets of brackets:

    - -
    This is [an example] [id] reference-style link.
    -
    - -

    Then, anywhere in the document, you define your link label like this, -on a line by itself:

    - -
    [id]: http://example.com/  "Optional Title Here"
    -
    - -

    That is:

    - -
      -
    • Square brackets containing the link identifier (optionally -indented from the left margin using up to three spaces);
    • -
    • followed by a colon;
    • -
    • followed by one or more spaces (or tabs);
    • -
    • followed by the URL for the link;
    • -
    • optionally followed by a title attribute for the link, enclosed -in double or single quotes.
    • -
    - -

    The link URL may, optionally, be surrounded by angle brackets:

    - -
    [id]: <http://example.com/>  "Optional Title Here"
    -
    - -

    You can put the title attribute on the next line and use extra spaces -or tabs for padding, which tends to look better with longer URLs:

    - -
    [id]: http://example.com/longish/path/to/resource/here
    -    "Optional Title Here"
    -
    - -

    Link definitions are only used for creating links during Markdown -processing, and are stripped from your document in the HTML output.

    - -

    Link definition names may constist of letters, numbers, spaces, and punctuation -- but they are not case sensitive. E.g. these two links:

    - -
    [link text][a]
    -[link text][A]
    -
    - -

    are equivalent.

    - -

    The implicit link name shortcut allows you to omit the name of the -link, in which case the link text itself is used as the name. -Just use an empty set of square brackets -- e.g., to link the word -"Google" to the google.com web site, you could simply write:

    - -
    [Google][]
    -
    - -

    And then define the link:

    - -
    [Google]: http://google.com/
    -
    - -

    Because link names may contain spaces, this shortcut even works for -multiple words in the link text:

    - -
    Visit [Daring Fireball][] for more information.
    -
    - -

    And then define the link:

    - -
    [Daring Fireball]: http://daringfireball.net/
    -
    - -

    Link definitions can be placed anywhere in your Markdown document. I -tend to put them immediately after each paragraph in which they're -used, but if you want, you can put them all at the end of your -document, sort of like footnotes.

    - -

    Here's an example of reference links in action:

    - -
    I get 10 times more traffic from [Google] [1] than from
    -[Yahoo] [2] or [MSN] [3].
    -
    -  [1]: http://google.com/        "Google"
    -  [2]: http://search.yahoo.com/  "Yahoo Search"
    -  [3]: http://search.msn.com/    "MSN Search"
    -
    - -

    Using the implicit link name shortcut, you could instead write:

    - -
    I get 10 times more traffic from [Google][] than from
    -[Yahoo][] or [MSN][].
    -
    -  [google]: http://google.com/        "Google"
    -  [yahoo]:  http://search.yahoo.com/  "Yahoo Search"
    -  [msn]:    http://search.msn.com/    "MSN Search"
    -
    - -

    Both of the above examples will produce the following HTML output:

    - -
    <p>I get 10 times more traffic from <a href="http://google.com/"
    -title="Google">Google</a> than from
    -<a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a>
    -or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>
    -
    - -

    For comparison, here is the same paragraph written using -Markdown's inline link style:

    - -
    I get 10 times more traffic from [Google](http://google.com/ "Google")
    -than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or
    -[MSN](http://search.msn.com/ "MSN Search").
    -
    - -

    The point of reference-style links is not that they're easier to -write. The point is that with reference-style links, your document -source is vastly more readable. Compare the above examples: using -reference-style links, the paragraph itself is only 81 characters -long; with inline-style links, it's 176 characters; and as raw HTML, -it's 234 characters. In the raw HTML, there's more markup than there -is text.

    - -

    With Markdown's reference-style links, a source document much more -closely resembles the final output, as rendered in a browser. By -allowing you to move the markup-related metadata out of the paragraph, -you can add links without interrupting the narrative flow of your -prose.

    - -

    Emphasis

    - -

    Markdown treats asterisks (*) and underscores (_) as indicators of -emphasis. Text wrapped with one * or _ will be wrapped with an -HTML <em> tag; double *'s or _'s will be wrapped with an HTML -<strong> tag. E.g., this input:

    - -
    *single asterisks*
    -
    -_single underscores_
    -
    -**double asterisks**
    -
    -__double underscores__
    -
    - -

    will produce:

    - -
    <em>single asterisks</em>
    -
    -<em>single underscores</em>
    -
    -<strong>double asterisks</strong>
    -
    -<strong>double underscores</strong>
    -
    - -

    You can use whichever style you prefer; the lone restriction is that -the same character must be used to open and close an emphasis span.

    - -

    Emphasis can be used in the middle of a word:

    - -
    un*fucking*believable
    -
    - -

    But if you surround an * or _ with spaces, it'll be treated as a -literal asterisk or underscore.

    - -

    To produce a literal asterisk or underscore at a position where it -would otherwise be used as an emphasis delimiter, you can backslash -escape it:

    - -
    \*this text is surrounded by literal asterisks\*
    -
    - -

    Code

    - -

    To indicate a span of code, wrap it with backtick quotes (`). -Unlike a pre-formatted code block, a code span indicates code within a -normal paragraph. For example:

    - -
    Use the `printf()` function.
    -
    - -

    will produce:

    - -
    <p>Use the <code>printf()</code> function.</p>
    -
    - -

    To include a literal backtick character within a code span, you can use -multiple backticks as the opening and closing delimiters:

    - -
    ``There is a literal backtick (`) here.``
    -
    - -

    which will produce this:

    - -
    <p><code>There is a literal backtick (`) here.</code></p>
    -
    - -

    The backtick delimiters surrounding a code span may include spaces -- -one after the opening, one before the closing. This allows you to place -literal backtick characters at the beginning or end of a code span:

    - -
    A single backtick in a code span: `` ` ``
    -
    -A backtick-delimited string in a code span: `` `foo` ``
    -
    - -

    will produce:

    - -
    <p>A single backtick in a code span: <code>`</code></p>
    -
    -<p>A backtick-delimited string in a code span: <code>`foo`</code></p>
    -
    - -

    With a code span, ampersands and angle brackets are encoded as HTML -entities automatically, which makes it easy to include example HTML -tags. Markdown will turn this:

    - -
    Please don't use any `<blink>` tags.
    -
    - -

    into:

    - -
    <p>Please don't use any <code>&lt;blink&gt;</code> tags.</p>
    -
    - -

    You can write this:

    - -
    `&#8212;` is the decimal-encoded equivalent of `&mdash;`.
    -
    - -

    to produce:

    - -
    <p><code>&amp;#8212;</code> is the decimal-encoded
    -equivalent of <code>&amp;mdash;</code>.</p>
    -
    - -

    Images

    - -

    Admittedly, it's fairly difficult to devise a "natural" syntax for -placing images into a plain text document format.

    - -

    Markdown uses an image syntax that is intended to resemble the syntax -for links, allowing for two styles: inline and reference.

    - -

    Inline image syntax looks like this:

    - -
    ![Alt text](/path/to/img.jpg)
    -
    -![Alt text](/path/to/img.jpg "Optional title")
    -
    - -

    That is:

    - -
      -
    • An exclamation mark: !;
    • -
    • followed by a set of square brackets, containing the alt -attribute text for the image;
    • -
    • followed by a set of parentheses, containing the URL or path to -the image, and an optional title attribute enclosed in double -or single quotes.
    • -
    - -

    Reference-style image syntax looks like this:

    - -
    ![Alt text][id]
    -
    - -

    Where "id" is the name of a defined image reference. Image references -are defined using syntax identical to link references:

    - -
    [id]: url/to/image  "Optional title attribute"
    -
    - -

    As of this writing, Markdown has no syntax for specifying the -dimensions of an image; if this is important to you, you can simply -use regular HTML <img> tags.

    - -
    - -

    Miscellaneous

    - - - -

    Markdown supports a shortcut style for creating "automatic" links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:

    - -
    <http://example.com/>
    -
    - -

    Markdown will turn this into:

    - -
    <a href="http://example.com/">http://example.com/</a>
    -
    - -

    Automatic links for email addresses work similarly, except that -Markdown will also perform a bit of randomized decimal and hex -entity-encoding to help obscure your address from address-harvesting -spambots. For example, Markdown will turn this:

    - -
    <address@example.com>
    -
    - -

    into something like this:

    - -
    <a href="&#x6D;&#x61;i&#x6C;&#x74;&#x6F;:&#x61;&#x64;&#x64;&#x72;&#x65;
    -&#115;&#115;&#64;&#101;&#120;&#x61;&#109;&#x70;&#x6C;e&#x2E;&#99;&#111;
    -&#109;">&#x61;&#x64;&#x64;&#x72;&#x65;&#115;&#115;&#64;&#101;&#120;&#x61;
    -&#109;&#x70;&#x6C;e&#x2E;&#99;&#111;&#109;</a>
    -
    - -

    which will render in a browser as a clickable link to "address@example.com".

    - -

    (This sort of entity-encoding trick will indeed fool many, if not -most, address-harvesting bots, but it definitely won't fool all of -them. It's better than nothing, but an address published in this way -will probably eventually start receiving spam.)

    - -

    Backslash Escapes

    - -

    Markdown allows you to use backslash escapes to generate literal -characters which would otherwise have special meaning in Markdown's -formatting syntax. For example, if you wanted to surround a word with -literal asterisks (instead of an HTML <em> tag), you can backslashes -before the asterisks, like this:

    - -
    \*literal asterisks\*
    -
    - -

    Markdown provides backslash escapes for the following characters:

    - -
    \   backslash
    -`   backtick
    -*   asterisk
    -_   underscore
    -{}  curly braces
    -[]  square brackets
    -()  parentheses
    -#   hash mark
    -+   plus sign
    --   minus sign (hyphen)
    -.   dot
    -!   exclamation mark
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Syntax.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Syntax.text deleted file mode 100644 index 57360a16c..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Markdown Documentation - Syntax.text +++ /dev/null @@ -1,888 +0,0 @@ -Markdown: Syntax -================ - - - - -* [Overview](#overview) - * [Philosophy](#philosophy) - * [Inline HTML](#html) - * [Automatic Escaping for Special Characters](#autoescape) -* [Block Elements](#block) - * [Paragraphs and Line Breaks](#p) - * [Headers](#header) - * [Blockquotes](#blockquote) - * [Lists](#list) - * [Code Blocks](#precode) - * [Horizontal Rules](#hr) -* [Span Elements](#span) - * [Links](#link) - * [Emphasis](#em) - * [Code](#code) - * [Images](#img) -* [Miscellaneous](#misc) - * [Backslash Escapes](#backslash) - * [Automatic Links](#autolink) - - -**Note:** This document is itself written using Markdown; you -can [see the source for it by adding '.text' to the URL][src]. - - [src]: /projects/markdown/syntax.text - -* * * - -

    Overview

    - -

    Philosophy

    - -Markdown is intended to be as easy-to-read and easy-to-write as is feasible. - -Readability, however, is emphasized above all else. A Markdown-formatted -document should be publishable as-is, as plain text, without looking -like it's been marked up with tags or formatting instructions. While -Markdown's syntax has been influenced by several existing text-to-HTML -filters -- including [Setext] [1], [atx] [2], [Textile] [3], [reStructuredText] [4], -[Grutatext] [5], and [EtText] [6] -- the single biggest source of -inspiration for Markdown's syntax is the format of plain text email. - - [1]: http://docutils.sourceforge.net/mirror/setext.html - [2]: http://www.aaronsw.com/2002/atx/ - [3]: http://textism.com/tools/textile/ - [4]: http://docutils.sourceforge.net/rst.html - [5]: http://www.triptico.com/software/grutatxt.html - [6]: http://ettext.taint.org/doc/ - -To this end, Markdown's syntax is comprised entirely of punctuation -characters, which punctuation characters have been carefully chosen so -as to look like what they mean. E.g., asterisks around a word actually -look like \*emphasis\*. Markdown lists look like, well, lists. Even -blockquotes look like quoted passages of text, assuming you've ever -used email. - - - -

    Inline HTML

    - -Markdown's syntax is intended for one purpose: to be used as a -format for *writing* for the web. - -Markdown is not a replacement for HTML, or even close to it. Its -syntax is very small, corresponding only to a very small subset of -HTML tags. The idea is *not* to create a syntax that makes it easier -to insert HTML tags. In my opinion, HTML tags are already easy to -insert. The idea for Markdown is to make it easy to read, write, and -edit prose. HTML is a *publishing* format; Markdown is a *writing* -format. Thus, Markdown's formatting syntax only addresses issues that -can be conveyed in plain text. - -For any markup that is not covered by Markdown's syntax, you simply -use HTML itself. There's no need to preface it or delimit it to -indicate that you're switching from Markdown to HTML; you just use -the tags. - -The only restrictions are that block-level HTML elements -- e.g. `
    `, -``, `
    `, `

    `, etc. -- must be separated from surrounding -content by blank lines, and the start and end tags of the block should -not be indented with tabs or spaces. Markdown is smart enough not -to add extra (unwanted) `

    ` tags around HTML block-level tags. - -For example, to add an HTML table to a Markdown article: - - This is a regular paragraph. - -

    - - - -
    Foo
    - - This is another regular paragraph. - -Note that Markdown formatting syntax is not processed within block-level -HTML tags. E.g., you can't use Markdown-style `*emphasis*` inside an -HTML block. - -Span-level HTML tags -- e.g. ``, ``, or `` -- can be -used anywhere in a Markdown paragraph, list item, or header. If you -want, you can even use HTML tags instead of Markdown formatting; e.g. if -you'd prefer to use HTML `` or `` tags instead of Markdown's -link or image syntax, go right ahead. - -Unlike block-level HTML tags, Markdown syntax *is* processed within -span-level tags. - - -

    Automatic Escaping for Special Characters

    - -In HTML, there are two characters that demand special treatment: `<` -and `&`. Left angle brackets are used to start tags; ampersands are -used to denote HTML entities. If you want to use them as literal -characters, you must escape them as entities, e.g. `<`, and -`&`. - -Ampersands in particular are bedeviling for web writers. If you want to -write about 'AT&T', you need to write '`AT&T`'. You even need to -escape ampersands within URLs. Thus, if you want to link to: - - http://images.google.com/images?num=30&q=larry+bird - -you need to encode the URL as: - - http://images.google.com/images?num=30&q=larry+bird - -in your anchor tag `href` attribute. Needless to say, this is easy to -forget, and is probably the single most common source of HTML validation -errors in otherwise well-marked-up web sites. - -Markdown allows you to use these characters naturally, taking care of -all the necessary escaping for you. If you use an ampersand as part of -an HTML entity, it remains unchanged; otherwise it will be translated -into `&`. - -So, if you want to include a copyright symbol in your article, you can write: - - © - -and Markdown will leave it alone. But if you write: - - AT&T - -Markdown will translate it to: - - AT&T - -Similarly, because Markdown supports [inline HTML](#html), if you use -angle brackets as delimiters for HTML tags, Markdown will treat them as -such. But if you write: - - 4 < 5 - -Markdown will translate it to: - - 4 < 5 - -However, inside Markdown code spans and blocks, angle brackets and -ampersands are *always* encoded automatically. This makes it easy to use -Markdown to write about HTML code. (As opposed to raw HTML, which is a -terrible format for writing about HTML syntax, because every single `<` -and `&` in your example code needs to be escaped.) - - -* * * - - -

    Block Elements

    - - -

    Paragraphs and Line Breaks

    - -A paragraph is simply one or more consecutive lines of text, separated -by one or more blank lines. (A blank line is any line that looks like a -blank line -- a line containing nothing but spaces or tabs is considered -blank.) Normal paragraphs should not be intended with spaces or tabs. - -The implication of the "one or more consecutive lines of text" rule is -that Markdown supports "hard-wrapped" text paragraphs. This differs -significantly from most other text-to-HTML formatters (including Movable -Type's "Convert Line Breaks" option) which translate every line break -character in a paragraph into a `
    ` tag. - -When you *do* want to insert a `
    ` break tag using Markdown, you -end a line with two or more spaces, then type return. - -Yes, this takes a tad more effort to create a `
    `, but a simplistic -"every line break is a `
    `" rule wouldn't work for Markdown. -Markdown's email-style [blockquoting][bq] and multi-paragraph [list items][l] -work best -- and look better -- when you format them with hard breaks. - - [bq]: #blockquote - [l]: #list - - - - - -Markdown supports two styles of headers, [Setext] [1] and [atx] [2]. - -Setext-style headers are "underlined" using equal signs (for first-level -headers) and dashes (for second-level headers). For example: - - This is an H1 - ============= - - This is an H2 - ------------- - -Any number of underlining `=`'s or `-`'s will work. - -Atx-style headers use 1-6 hash characters at the start of the line, -corresponding to header levels 1-6. For example: - - # This is an H1 - - ## This is an H2 - - ###### This is an H6 - -Optionally, you may "close" atx-style headers. This is purely -cosmetic -- you can use this if you think it looks better. The -closing hashes don't even need to match the number of hashes -used to open the header. (The number of opening hashes -determines the header level.) : - - # This is an H1 # - - ## This is an H2 ## - - ### This is an H3 ###### - - -

    Blockquotes

    - -Markdown uses email-style `>` characters for blockquoting. If you're -familiar with quoting passages of text in an email message, then you -know how to create a blockquote in Markdown. It looks best if you hard -wrap the text and put a `>` before every line: - - > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet, - > consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. - > Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus. - > - > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse - > id sem consectetuer libero luctus adipiscing. - -Markdown allows you to be lazy and only put the `>` before the first -line of a hard-wrapped paragraph: - - > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet, - consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. - Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus. - - > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse - id sem consectetuer libero luctus adipiscing. - -Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by -adding additional levels of `>`: - - > This is the first level of quoting. - > - > > This is nested blockquote. - > - > Back to the first level. - -Blockquotes can contain other Markdown elements, including headers, lists, -and code blocks: - - > ## This is a header. - > - > 1. This is the first list item. - > 2. This is the second list item. - > - > Here's some example code: - > - > return shell_exec("echo $input | $markdown_script"); - -Any decent text editor should make email-style quoting easy. For -example, with BBEdit, you can make a selection and choose Increase -Quote Level from the Text menu. - - -

    Lists

    - -Markdown supports ordered (numbered) and unordered (bulleted) lists. - -Unordered lists use asterisks, pluses, and hyphens -- interchangably --- as list markers: - - * Red - * Green - * Blue - -is equivalent to: - - + Red - + Green - + Blue - -and: - - - Red - - Green - - Blue - -Ordered lists use numbers followed by periods: - - 1. Bird - 2. McHale - 3. Parish - -It's important to note that the actual numbers you use to mark the -list have no effect on the HTML output Markdown produces. The HTML -Markdown produces from the above list is: - -
      -
    1. Bird
    2. -
    3. McHale
    4. -
    5. Parish
    6. -
    - -If you instead wrote the list in Markdown like this: - - 1. Bird - 1. McHale - 1. Parish - -or even: - - 3. Bird - 1. McHale - 8. Parish - -you'd get the exact same HTML output. The point is, if you want to, -you can use ordinal numbers in your ordered Markdown lists, so that -the numbers in your source match the numbers in your published HTML. -But if you want to be lazy, you don't have to. - -If you do use lazy list numbering, however, you should still start the -list with the number 1. At some point in the future, Markdown may support -starting ordered lists at an arbitrary number. - -List markers typically start at the left margin, but may be indented by -up to three spaces. List markers must be followed by one or more spaces -or a tab. - -To make lists look nice, you can wrap items with hanging indents: - - * Lorem ipsum dolor sit amet, consectetuer adipiscing elit. - Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, - viverra nec, fringilla in, laoreet vitae, risus. - * Donec sit amet nisl. Aliquam semper ipsum sit amet velit. - Suspendisse id sem consectetuer libero luctus adipiscing. - -But if you want to be lazy, you don't have to: - - * Lorem ipsum dolor sit amet, consectetuer adipiscing elit. - Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, - viverra nec, fringilla in, laoreet vitae, risus. - * Donec sit amet nisl. Aliquam semper ipsum sit amet velit. - Suspendisse id sem consectetuer libero luctus adipiscing. - -If list items are separated by blank lines, Markdown will wrap the -items in `

    ` tags in the HTML output. For example, this input: - - * Bird - * Magic - -will turn into: - -

      -
    • Bird
    • -
    • Magic
    • -
    - -But this: - - * Bird - - * Magic - -will turn into: - -
      -
    • Bird

    • -
    • Magic

    • -
    - -List items may consist of multiple paragraphs. Each subsequent -paragraph in a list item must be intended by either 4 spaces -or one tab: - - 1. This is a list item with two paragraphs. Lorem ipsum dolor - sit amet, consectetuer adipiscing elit. Aliquam hendrerit - mi posuere lectus. - - Vestibulum enim wisi, viverra nec, fringilla in, laoreet - vitae, risus. Donec sit amet nisl. Aliquam semper ipsum - sit amet velit. - - 2. Suspendisse id sem consectetuer libero luctus adipiscing. - -It looks nice if you indent every line of the subsequent -paragraphs, but here again, Markdown will allow you to be -lazy: - - * This is a list item with two paragraphs. - - This is the second paragraph in the list item. You're - only required to indent the first line. Lorem ipsum dolor - sit amet, consectetuer adipiscing elit. - - * Another item in the same list. - -To put a blockquote within a list item, the blockquote's `>` -delimiters need to be indented: - - * A list item with a blockquote: - - > This is a blockquote - > inside a list item. - -To put a code block within a list item, the code block needs -to be indented *twice* -- 8 spaces or two tabs: - - * A list item with a code block: - - - - -It's worth noting that it's possible to trigger an ordered list by -accident, by writing something like this: - - 1986. What a great season. - -In other words, a *number-period-space* sequence at the beginning of a -line. To avoid this, you can backslash-escape the period: - - 1986\. What a great season. - - - -

    Code Blocks

    - -Pre-formatted code blocks are used for writing about programming or -markup source code. Rather than forming normal paragraphs, the lines -of a code block are interpreted literally. Markdown wraps a code block -in both `
    ` and `` tags.
    -
    -To produce a code block in Markdown, simply indent every line of the
    -block by at least 4 spaces or 1 tab. For example, given this input:
    -
    -    This is a normal paragraph:
    -
    -        This is a code block.
    -
    -Markdown will generate:
    -
    -    

    This is a normal paragraph:

    - -
    This is a code block.
    -    
    - -One level of indentation -- 4 spaces or 1 tab -- is removed from each -line of the code block. For example, this: - - Here is an example of AppleScript: - - tell application "Foo" - beep - end tell - -will turn into: - -

    Here is an example of AppleScript:

    - -
    tell application "Foo"
    -        beep
    -    end tell
    -    
    - -A code block continues until it reaches a line that is not indented -(or the end of the article). - -Within a code block, ampersands (`&`) and angle brackets (`<` and `>`) -are automatically converted into HTML entities. This makes it very -easy to include example HTML source code using Markdown -- just paste -it and indent it, and Markdown will handle the hassle of encoding the -ampersands and angle brackets. For example, this: - - - -will turn into: - -
    <div class="footer">
    -        &copy; 2004 Foo Corporation
    -    </div>
    -    
    - -Regular Markdown syntax is not processed within code blocks. E.g., -asterisks are just literal asterisks within a code block. This means -it's also easy to use Markdown to write about Markdown's own syntax. - - - -

    Horizontal Rules

    - -You can produce a horizontal rule tag (`
    `) by placing three or -more hyphens, asterisks, or underscores on a line by themselves. If you -wish, you may use spaces between the hyphens or asterisks. Each of the -following lines will produce a horizontal rule: - - * * * - - *** - - ***** - - - - - - - --------------------------------------- - - _ _ _ - - -* * * - -

    Span Elements

    - - - -Markdown supports two style of links: *inline* and *reference*. - -In both styles, the link text is delimited by [square brackets]. - -To create an inline link, use a set of regular parentheses immediately -after the link text's closing square bracket. Inside the parentheses, -put the URL where you want the link to point, along with an *optional* -title for the link, surrounded in quotes. For example: - - This is [an example](http://example.com/ "Title") inline link. - - [This link](http://example.net/) has no title attribute. - -Will produce: - -

    This is - an example inline link.

    - -

    This link has no - title attribute.

    - -If you're referring to a local resource on the same server, you can -use relative paths: - - See my [About](/about/) page for details. - -Reference-style links use a second set of square brackets, inside -which you place a label of your choosing to identify the link: - - This is [an example][id] reference-style link. - -You can optionally use a space to separate the sets of brackets: - - This is [an example] [id] reference-style link. - -Then, anywhere in the document, you define your link label like this, -on a line by itself: - - [id]: http://example.com/ "Optional Title Here" - -That is: - -* Square brackets containing the link identifier (optionally - indented from the left margin using up to three spaces); -* followed by a colon; -* followed by one or more spaces (or tabs); -* followed by the URL for the link; -* optionally followed by a title attribute for the link, enclosed - in double or single quotes. - -The link URL may, optionally, be surrounded by angle brackets: - - [id]: "Optional Title Here" - -You can put the title attribute on the next line and use extra spaces -or tabs for padding, which tends to look better with longer URLs: - - [id]: http://example.com/longish/path/to/resource/here - "Optional Title Here" - -Link definitions are only used for creating links during Markdown -processing, and are stripped from your document in the HTML output. - -Link definition names may constist of letters, numbers, spaces, and punctuation -- but they are *not* case sensitive. E.g. these two links: - - [link text][a] - [link text][A] - -are equivalent. - -The *implicit link name* shortcut allows you to omit the name of the -link, in which case the link text itself is used as the name. -Just use an empty set of square brackets -- e.g., to link the word -"Google" to the google.com web site, you could simply write: - - [Google][] - -And then define the link: - - [Google]: http://google.com/ - -Because link names may contain spaces, this shortcut even works for -multiple words in the link text: - - Visit [Daring Fireball][] for more information. - -And then define the link: - - [Daring Fireball]: http://daringfireball.net/ - -Link definitions can be placed anywhere in your Markdown document. I -tend to put them immediately after each paragraph in which they're -used, but if you want, you can put them all at the end of your -document, sort of like footnotes. - -Here's an example of reference links in action: - - I get 10 times more traffic from [Google] [1] than from - [Yahoo] [2] or [MSN] [3]. - - [1]: http://google.com/ "Google" - [2]: http://search.yahoo.com/ "Yahoo Search" - [3]: http://search.msn.com/ "MSN Search" - -Using the implicit link name shortcut, you could instead write: - - I get 10 times more traffic from [Google][] than from - [Yahoo][] or [MSN][]. - - [google]: http://google.com/ "Google" - [yahoo]: http://search.yahoo.com/ "Yahoo Search" - [msn]: http://search.msn.com/ "MSN Search" - -Both of the above examples will produce the following HTML output: - -

    I get 10 times more traffic from Google than from - Yahoo - or MSN.

    - -For comparison, here is the same paragraph written using -Markdown's inline link style: - - I get 10 times more traffic from [Google](http://google.com/ "Google") - than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or - [MSN](http://search.msn.com/ "MSN Search"). - -The point of reference-style links is not that they're easier to -write. The point is that with reference-style links, your document -source is vastly more readable. Compare the above examples: using -reference-style links, the paragraph itself is only 81 characters -long; with inline-style links, it's 176 characters; and as raw HTML, -it's 234 characters. In the raw HTML, there's more markup than there -is text. - -With Markdown's reference-style links, a source document much more -closely resembles the final output, as rendered in a browser. By -allowing you to move the markup-related metadata out of the paragraph, -you can add links without interrupting the narrative flow of your -prose. - - -

    Emphasis

    - -Markdown treats asterisks (`*`) and underscores (`_`) as indicators of -emphasis. Text wrapped with one `*` or `_` will be wrapped with an -HTML `` tag; double `*`'s or `_`'s will be wrapped with an HTML -`` tag. E.g., this input: - - *single asterisks* - - _single underscores_ - - **double asterisks** - - __double underscores__ - -will produce: - - single asterisks - - single underscores - - double asterisks - - double underscores - -You can use whichever style you prefer; the lone restriction is that -the same character must be used to open and close an emphasis span. - -Emphasis can be used in the middle of a word: - - un*fucking*believable - -But if you surround an `*` or `_` with spaces, it'll be treated as a -literal asterisk or underscore. - -To produce a literal asterisk or underscore at a position where it -would otherwise be used as an emphasis delimiter, you can backslash -escape it: - - \*this text is surrounded by literal asterisks\* - - - -

    Code

    - -To indicate a span of code, wrap it with backtick quotes (`` ` ``). -Unlike a pre-formatted code block, a code span indicates code within a -normal paragraph. For example: - - Use the `printf()` function. - -will produce: - -

    Use the printf() function.

    - -To include a literal backtick character within a code span, you can use -multiple backticks as the opening and closing delimiters: - - ``There is a literal backtick (`) here.`` - -which will produce this: - -

    There is a literal backtick (`) here.

    - -The backtick delimiters surrounding a code span may include spaces -- -one after the opening, one before the closing. This allows you to place -literal backtick characters at the beginning or end of a code span: - - A single backtick in a code span: `` ` `` - - A backtick-delimited string in a code span: `` `foo` `` - -will produce: - -

    A single backtick in a code span: `

    - -

    A backtick-delimited string in a code span: `foo`

    - -With a code span, ampersands and angle brackets are encoded as HTML -entities automatically, which makes it easy to include example HTML -tags. Markdown will turn this: - - Please don't use any `` tags. - -into: - -

    Please don't use any <blink> tags.

    - -You can write this: - - `—` is the decimal-encoded equivalent of `—`. - -to produce: - -

    &#8212; is the decimal-encoded - equivalent of &mdash;.

    - - - -

    Images

    - -Admittedly, it's fairly difficult to devise a "natural" syntax for -placing images into a plain text document format. - -Markdown uses an image syntax that is intended to resemble the syntax -for links, allowing for two styles: *inline* and *reference*. - -Inline image syntax looks like this: - - ![Alt text](/path/to/img.jpg) - - ![Alt text](/path/to/img.jpg "Optional title") - -That is: - -* An exclamation mark: `!`; -* followed by a set of square brackets, containing the `alt` - attribute text for the image; -* followed by a set of parentheses, containing the URL or path to - the image, and an optional `title` attribute enclosed in double - or single quotes. - -Reference-style image syntax looks like this: - - ![Alt text][id] - -Where "id" is the name of a defined image reference. Image references -are defined using syntax identical to link references: - - [id]: url/to/image "Optional title attribute" - -As of this writing, Markdown has no syntax for specifying the -dimensions of an image; if this is important to you, you can simply -use regular HTML `` tags. - - -* * * - - -

    Miscellaneous

    - - - -Markdown supports a shortcut style for creating "automatic" links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this: - - - -Markdown will turn this into: - - http://example.com/ - -Automatic links for email addresses work similarly, except that -Markdown will also perform a bit of randomized decimal and hex -entity-encoding to help obscure your address from address-harvesting -spambots. For example, Markdown will turn this: - - - -into something like this: - - address@exa - mple.com - -which will render in a browser as a clickable link to "address@example.com". - -(This sort of entity-encoding trick will indeed fool many, if not -most, address-harvesting bots, but it definitely won't fool all of -them. It's better than nothing, but an address published in this way -will probably eventually start receiving spam.) - - - -

    Backslash Escapes

    - -Markdown allows you to use backslash escapes to generate literal -characters which would otherwise have special meaning in Markdown's -formatting syntax. For example, if you wanted to surround a word with -literal asterisks (instead of an HTML `` tag), you can backslashes -before the asterisks, like this: - - \*literal asterisks\* - -Markdown provides backslash escapes for the following characters: - - \ backslash - ` backtick - * asterisk - _ underscore - {} curly braces - [] square brackets - () parentheses - # hash mark - + plus sign - - minus sign (hyphen) - . dot - ! exclamation mark - diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Nested blockquotes.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Nested blockquotes.html deleted file mode 100644 index 538bb4fe7..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Nested blockquotes.html +++ /dev/null @@ -1,9 +0,0 @@ -
    -

    foo

    - -
    -

    bar

    -
    - -

    foo

    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Nested blockquotes.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Nested blockquotes.text deleted file mode 100644 index ed3c624ff..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Nested blockquotes.text +++ /dev/null @@ -1,5 +0,0 @@ -> foo -> -> > bar -> -> foo diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Ordered and unordered lists.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Ordered and unordered lists.html deleted file mode 100644 index d6fa42780..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Ordered and unordered lists.html +++ /dev/null @@ -1,166 +0,0 @@ -

    Unordered

    - -

    Asterisks tight:

    - -
      -
    • asterisk 1
    • -
    • asterisk 2
    • -
    • asterisk 3
    • -
    - -

    Asterisks loose:

    - -
      -
    • asterisk 1

    • - -
    • asterisk 2

    • - -
    • asterisk 3

    • -
    - -
    - -

    Pluses tight:

    - -
      -
    • Plus 1
    • -
    • Plus 2
    • -
    • Plus 3
    • -
    - -

    Pluses loose:

    - -
      -
    • Plus 1

    • - -
    • Plus 2

    • - -
    • Plus 3

    • -
    - -
    - -

    Minuses tight:

    - -
      -
    • Minus 1
    • -
    • Minus 2
    • -
    • Minus 3
    • -
    - -

    Minuses loose:

    - -
      -
    • Minus 1

    • - -
    • Minus 2

    • - -
    • Minus 3

    • -
    - -

    Ordered

    - -

    Tight:

    - -
      -
    1. First
    2. -
    3. Second
    4. -
    5. Third
    6. -
    - -

    and:

    - -
      -
    1. One
    2. -
    3. Two
    4. -
    5. Three
    6. -
    - -

    Loose using tabs:

    - -
      -
    1. First

    2. - -
    3. Second

    4. - -
    5. Third

    6. -
    - -

    and using spaces:

    - -
      -
    1. One

    2. - -
    3. Two

    4. - -
    5. Three

    6. -
    - -

    Multiple paragraphs:

    - -
      -
    1. Item 1, graf one.

      - -

      Item 2. graf two. The quick brown fox jumped over the lazy dog's -back.

    2. - -
    3. Item 2.

    4. - -
    5. Item 3.

    6. -
    - -

    Nested

    - -
      -
    • Tab - -
        -
      • Tab - -
          -
        • Tab
        • -
      • -
    • -
    - -

    Here's another:

    - -
      -
    1. First
    2. -
    3. Second: - -
        -
      • Fee
      • -
      • Fie
      • -
      • Foe
      • -
    4. -
    5. Third
    6. -
    - -

    Same thing but with paragraphs:

    - -
      -
    1. First

    2. - -
    3. Second:

      - -
        -
      • Fee
      • -
      • Fie
      • -
      • Foe
      • -
    4. - -
    5. Third

    6. -
    - -

    This was an error in Markdown 1.0.1:

    - -
      -
    • this

      - -
        -
      • sub
      • -
      - -

      that

    • -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Ordered and unordered lists.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Ordered and unordered lists.text deleted file mode 100644 index 7f3b49777..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Ordered and unordered lists.text +++ /dev/null @@ -1,131 +0,0 @@ -## Unordered - -Asterisks tight: - -* asterisk 1 -* asterisk 2 -* asterisk 3 - - -Asterisks loose: - -* asterisk 1 - -* asterisk 2 - -* asterisk 3 - -* * * - -Pluses tight: - -+ Plus 1 -+ Plus 2 -+ Plus 3 - - -Pluses loose: - -+ Plus 1 - -+ Plus 2 - -+ Plus 3 - -* * * - - -Minuses tight: - -- Minus 1 -- Minus 2 -- Minus 3 - - -Minuses loose: - -- Minus 1 - -- Minus 2 - -- Minus 3 - - -## Ordered - -Tight: - -1. First -2. Second -3. Third - -and: - -1. One -2. Two -3. Three - - -Loose using tabs: - -1. First - -2. Second - -3. Third - -and using spaces: - -1. One - -2. Two - -3. Three - -Multiple paragraphs: - -1. Item 1, graf one. - - Item 2. graf two. The quick brown fox jumped over the lazy dog's - back. - -2. Item 2. - -3. Item 3. - - - -## Nested - -* Tab - * Tab - * Tab - -Here's another: - -1. First -2. Second: - * Fee - * Fie - * Foe -3. Third - -Same thing but with paragraphs: - -1. First - -2. Second: - * Fee - * Fie - * Foe - -3. Third - - -This was an error in Markdown 1.0.1: - -* this - - * sub - - that diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Strong and em together.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Strong and em together.html deleted file mode 100644 index 71ec78c70..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Strong and em together.html +++ /dev/null @@ -1,7 +0,0 @@ -

    This is strong and em.

    - -

    So is this word.

    - -

    This is strong and em.

    - -

    So is this word.

    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Strong and em together.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Strong and em together.text deleted file mode 100644 index 95ee690db..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Strong and em together.text +++ /dev/null @@ -1,7 +0,0 @@ -***This is strong and em.*** - -So is ***this*** word. - -___This is strong and em.___ - -So is ___this___ word. diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tabs.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tabs.html deleted file mode 100644 index 64006d96a..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tabs.html +++ /dev/null @@ -1,26 +0,0 @@ -
      -
    • this is a list item -indented with tabs

    • - -
    • this is a list item -indented with spaces

    • -
    - -

    Code:

    - -
    this code block is indented by one tab
    -
    - -

    And:

    - -
        this code block is indented by two tabs
    -
    - -

    And:

    - -
    +   this is an example list item
    -    indented with tabs
    -
    -+   this is an example list item
    -    indented with spaces
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tabs.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tabs.text deleted file mode 100644 index 589d1136e..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tabs.text +++ /dev/null @@ -1,21 +0,0 @@ -+ this is a list item - indented with tabs - -+ this is a list item - indented with spaces - -Code: - - this code block is indented by one tab - -And: - - this code block is indented by two tabs - -And: - - + this is an example list item - indented with tabs - - + this is an example list item - indented with spaces diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tidyness.html b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tidyness.html deleted file mode 100644 index 9c45b69c2..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tidyness.html +++ /dev/null @@ -1,9 +0,0 @@ -
    -

    A list within a blockquote:

    - -
      -
    • asterisk 1
    • -
    • asterisk 2
    • -
    • asterisk 3
    • -
    -
    diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tidyness.text b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tidyness.text deleted file mode 100644 index 5f18b8da2..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref/Tidyness.text +++ /dev/null @@ -1,5 +0,0 @@ -> A list within a blockquote: -> -> * asterisk 1 -> * asterisk 2 -> * asterisk 3 diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref_test.go b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref_test.go deleted file mode 100644 index 42a0bdd52..000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref_test.go +++ /dev/null @@ -1,128 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Markdown 1.0.3 reference tests -// - -package blackfriday - -import ( - "io/ioutil" - "path/filepath" - "testing" -) - -func runMarkdownReference(input string, flag int) string { - renderer := HtmlRenderer(0, "", "") - return string(Markdown([]byte(input), renderer, flag)) -} - -func doTestsReference(t *testing.T, files []string, flag int) { - // catch and report panics - var candidate string - defer func() { - if err := recover(); err != nil { - t.Errorf("\npanic while processing [%#v]\n", candidate) - } - }() - - for _, basename := range files { - filename := filepath.Join("upskirtref", basename+".text") - inputBytes, err := ioutil.ReadFile(filename) - if err != nil { - t.Errorf("Couldn't open '%s', error: %v\n", filename, err) - continue - } - input := string(inputBytes) - - filename = filepath.Join("upskirtref", basename+".html") - expectedBytes, err := ioutil.ReadFile(filename) - if err != nil { - t.Errorf("Couldn't open '%s', error: %v\n", filename, err) - continue - } - expected := string(expectedBytes) - - // fmt.Fprintf(os.Stderr, "processing %s ...", filename) - actual := string(runMarkdownReference(input, flag)) - if actual != expected { - t.Errorf("\n [%#v]\nExpected[%#v]\nActual [%#v]", - basename+".text", expected, actual) - } - // fmt.Fprintf(os.Stderr, " ok\n") - - // now test every prefix of every input to check for - // bounds checking - if !testing.Short() { - start, max := 0, len(input) - for end := start + 1; end <= max; end++ { - candidate = input[start:end] - // fmt.Fprintf(os.Stderr, " %s %d:%d/%d\n", filename, start, end, max) - _ = runMarkdownReference(candidate, flag) - } - } - } -} - -func TestReference(t *testing.T) { - files := []string{ - "Amps and angle encoding", - "Auto links", - "Backslash escapes", - "Blockquotes with code blocks", - "Code Blocks", - "Code Spans", - "Hard-wrapped paragraphs with list-like lines", - "Horizontal rules", - "Inline HTML (Advanced)", - "Inline HTML (Simple)", - "Inline HTML comments", - "Links, inline style", - "Links, reference style", - "Links, shortcut references", - "Literal quotes in titles", - "Markdown Documentation - Basics", - "Markdown Documentation - Syntax", - "Nested blockquotes", - "Ordered and unordered lists", - "Strong and em together", - "Tabs", - "Tidyness", - } - doTestsReference(t, files, 0) -} - -func TestReference_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - files := []string{ - "Amps and angle encoding", - "Auto links", - "Backslash escapes", - "Blockquotes with code blocks", - "Code Blocks", - "Code Spans", - "Hard-wrapped paragraphs with list-like lines no empty line before block", - "Horizontal rules", - "Inline HTML (Advanced)", - "Inline HTML (Simple)", - "Inline HTML comments", - "Links, inline style", - "Links, reference style", - "Links, shortcut references", - "Literal quotes in titles", - "Markdown Documentation - Basics", - "Markdown Documentation - Syntax", - "Nested blockquotes", - "Ordered and unordered lists", - "Strong and em together", - "Tabs", - "Tidyness", - } - doTestsReference(t, files, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/example_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/example_test.go deleted file mode 100644 index 7fa554c08..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/example_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package gcfg_test - -import ( - "fmt" - "log" -) - -import "github.com/scalingdata/gcfg" - -func ExampleReadStringInto() { - cfgStr := `; Comment line -[section] -name=value # comment` - cfg := struct { - Section struct { - Name string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Name) - // Output: value -} - -func ExampleReadStringInto_bool() { - cfgStr := `; Comment line -[section] -switch=on` - cfg := struct { - Section struct { - Switch bool - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Switch) - // Output: true -} - -func ExampleReadStringInto_hyphens() { - cfgStr := `; Comment line -[section-name] -variable-name=value # comment` - cfg := struct { - Section_Name struct { - Variable_Name string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section_Name.Variable_Name) - // Output: value -} - -func ExampleReadStringInto_tags() { - cfgStr := `; Comment line -[section] -var-name=value # comment` - cfg := struct { - Section struct { - FieldName string `gcfg:"var-name"` - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.FieldName) - // Output: value -} - -func ExampleReadStringInto_subsections() { - cfgStr := `; Comment line -[profile "A"] -color = white - -[profile "B"] -color = black -` - cfg := struct { - Profile map[string]*struct { - Color string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Printf("%s %s\n", cfg.Profile["A"].Color, cfg.Profile["B"].Color) - // Output: white black -} - -func ExampleReadStringInto_multivalue() { - cfgStr := `; Comment line -[section] -multi=value1 -multi=value2` - cfg := struct { - Section struct { - Multi []string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Multi) - // Output: [value1 value2] -} - -func ExampleReadStringInto_unicode() { - cfgStr := `; Comment line -[甲] -乙=丙 # comment` - cfg := struct { - X甲 struct { - X乙 string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.X甲.X乙) - // Output: 丙 -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/issues_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/issues_test.go deleted file mode 100644 index 796dd10b6..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/issues_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package gcfg - -import ( - "fmt" - "math/big" - "strings" - "testing" -) - -type Config1 struct { - Section struct { - Int int - BigInt big.Int - } -} - -var testsIssue1 = []struct { - cfg string - typename string -}{ - {"[section]\nint=X", "int"}, - {"[section]\nint=", "int"}, - {"[section]\nint=1A", "int"}, - {"[section]\nbigint=X", "big.Int"}, - {"[section]\nbigint=", "big.Int"}, - {"[section]\nbigint=1A", "big.Int"}, -} - -// Value parse error should: -// - include plain type name -// - not include reflect internals -func TestIssue1(t *testing.T) { - for i, tt := range testsIssue1 { - var c Config1 - err := ReadStringInto(&c, tt.cfg) - switch { - case err == nil: - t.Errorf("%d fail: got ok; wanted error", i) - case !strings.Contains(err.Error(), tt.typename): - t.Errorf("%d fail: error message doesn't contain type name %q: %v", - i, tt.typename, err) - case strings.Contains(err.Error(), "reflect"): - t.Errorf("%d fail: error message includes reflect internals: %v", - i, err) - default: - t.Logf("%d pass: %v", i, err) - } - } -} - -type confIssue2 struct{ Main struct{ Foo string } } - -var testsIssue2 = []readtest{ - {"[main]\n;\nfoo = bar\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, - {"[main]\r\n;\r\nfoo = bar\r\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, -} - -func TestIssue2(t *testing.T) { - for i, tt := range testsIssue2 { - id := fmt.Sprintf("issue2:%d", i) - testRead(t, id, tt) - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/read_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/read_test.go deleted file mode 100644 index 4a7d8e191..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/read_test.go +++ /dev/null @@ -1,333 +0,0 @@ -package gcfg - -import ( - "fmt" - "math/big" - "os" - "reflect" - "testing" -) - -const ( - // 64 spaces - sp64 = " " - // 512 spaces - sp512 = sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 - // 4096 spaces - sp4096 = sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 -) - -type cBasic struct { - Section cBasicS1 - Hyphen_In_Section cBasicS2 - unexported cBasicS1 - Exported cBasicS3 - TagName cBasicS1 `gcfg:"tag-name"` -} -type cBasicS1 struct { - Name string - Int int - PName *string -} -type cBasicS2 struct { - Hyphen_In_Name string -} -type cBasicS3 struct { - unexported string -} - -type nonMulti []string - -type unmarshalable string - -func (u *unmarshalable) UnmarshalText(text []byte) error { - s := string(text) - if s == "error" { - return fmt.Errorf("%s", s) - } - *u = unmarshalable(s) - return nil -} - -var _ textUnmarshaler = new(unmarshalable) - -type cUni struct { - X甲 cUniS1 - XSection cUniS2 -} -type cUniS1 struct { - X乙 string -} -type cUniS2 struct { - XName string -} - -type cMulti struct { - M1 cMultiS1 - M2 cMultiS2 - M3 cMultiS3 -} -type cMultiS1 struct{ Multi []string } -type cMultiS2 struct{ NonMulti nonMulti } -type cMultiS3 struct{ MultiInt []int } - -type cSubs struct{ Sub map[string]*cSubsS1 } -type cSubsS1 struct{ Name string } - -type cBool struct{ Section cBoolS1 } -type cBoolS1 struct{ Bool bool } - -type cTxUnm struct{ Section cTxUnmS1 } -type cTxUnmS1 struct{ Name unmarshalable } - -type cNum struct { - N1 cNumS1 - N2 cNumS2 - N3 cNumS3 -} -type cNumS1 struct { - Int int - IntDHO int `gcfg:",int=dho"` - Big *big.Int -} -type cNumS2 struct { - MultiInt []int - MultiBig []*big.Int -} -type cNumS3 struct{ FileMode os.FileMode } -type readtest struct { - gcfg string - exp interface{} - ok bool -} - -func newString(s string) *string { - return &s -} - -var readtests = []struct { - group string - tests []readtest -}{{"scanning", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // hyphen in name - {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, - // quoted string value - {"[section]\nname=\"\"", &cBasic{Section: cBasicS1{Name: ""}}, true}, - {"[section]\nname=\" \"", &cBasic{Section: cBasicS1{Name: " "}}, true}, - {"[section]\nname=\"value\"", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=\" value \"", &cBasic{Section: cBasicS1{Name: " value "}}, true}, - {"\n[section]\nname=\"va ; lue\"", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, - {"[section]\nname=\"val\" \"ue\"", &cBasic{Section: cBasicS1{Name: "val ue"}}, true}, - {"[section]\nname=\"value", &cBasic{}, false}, - // escape sequences - {"[section]\nname=\"va\\\\lue\"", &cBasic{Section: cBasicS1{Name: "va\\lue"}}, true}, - {"[section]\nname=\"va\\\"lue\"", &cBasic{Section: cBasicS1{Name: "va\"lue"}}, true}, - {"[section]\nname=\"va\\nlue\"", &cBasic{Section: cBasicS1{Name: "va\nlue"}}, true}, - {"[section]\nname=\"va\\tlue\"", &cBasic{Section: cBasicS1{Name: "va\tlue"}}, true}, - {"\n[section]\nname=\\", &cBasic{}, false}, - {"\n[section]\nname=\\a", &cBasic{}, false}, - {"\n[section]\nname=\"val\\a\"", &cBasic{}, false}, - {"\n[section]\nname=val\\", &cBasic{}, false}, - {"\n[sub \"A\\\n\"]\nname=value", &cSubs{}, false}, - {"\n[sub \"A\\\t\"]\nname=value", &cSubs{}, false}, - // broken line - {"[section]\nname=value \\\n value", &cBasic{Section: cBasicS1{Name: "value value"}}, true}, - {"[section]\nname=\"value \\\n value\"", &cBasic{}, false}, -}}, {"scanning:whitespace", []readtest{ - {" \n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {" [section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\t[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[ section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section ]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\n name=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname =value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname= value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=value ", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\r\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {";cmnt\r\n[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // long lines - {sp4096 + "[section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[" + sp4096 + "section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section" + sp4096 + "]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]" + sp4096 + "\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\n" + sp4096 + "name=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname" + sp4096 + "=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=" + sp4096 + "value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=value\n" + sp4096, &cBasic{Section: cBasicS1{Name: "value"}}, true}, -}}, {"scanning:comments", []readtest{ - {"; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"# cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {" ; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\t; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section] ; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=\"value\" ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value ; \"cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=\"va ; lue\" ; cmnt", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, - {"\n[section]\nname=; cmnt", &cBasic{Section: cBasicS1{Name: ""}}, true}, -}}, {"scanning:subsections", []readtest{ - {"\n[sub \"A\"]\nname=value", &cSubs{map[string]*cSubsS1{"A": &cSubsS1{"value"}}}, true}, - {"\n[sub \"b\"]\nname=value", &cSubs{map[string]*cSubsS1{"b": &cSubsS1{"value"}}}, true}, - {"\n[sub \"A\\\\\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\\": &cSubsS1{"value"}}}, true}, - {"\n[sub \"A\\\"\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\"": &cSubsS1{"value"}}}, true}, -}}, {"syntax", []readtest{ - // invalid line - {"\n[section]\n=", &cBasic{}, false}, - // no section - {"name=value", &cBasic{}, false}, - // empty section - {"\n[]\nname=value", &cBasic{}, false}, - // empty subsection - {"\n[sub \"\"]\nname=value", &cSubs{}, false}, -}}, {"setting", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // pointer - {"[section]", &cBasic{Section: cBasicS1{PName: nil}}, true}, - {"[section]\npname=value", &cBasic{Section: cBasicS1{PName: newString("value")}}, true}, - // section name not matched - {"\n[nonexistent]\nname=value", &cBasic{}, false}, - // subsection name not matched - {"\n[section \"nonexistent\"]\nname=value", &cBasic{}, false}, - // variable name not matched - {"\n[section]\nnonexistent=value", &cBasic{}, false}, - // hyphen in name - {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, - // ignore unexported fields - {"[unexported]\nname=value", &cBasic{}, false}, - {"[exported]\nunexported=value", &cBasic{}, false}, - // 'X' prefix for non-upper/lower-case letters - {"[甲]\n乙=丙", &cUni{X甲: cUniS1{X乙: "丙"}}, true}, - //{"[section]\nxname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, - //{"[xsection]\nname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, - // name specified as struct tag - {"[tag-name]\nname=value", &cBasic{TagName: cBasicS1{Name: "value"}}, true}, -}}, {"multivalue", []readtest{ - // unnamed slice type: treat as multi-value - {"\n[m1]", &cMulti{M1: cMultiS1{}}, true}, - {"\n[m1]\nmulti=value", &cMulti{M1: cMultiS1{[]string{"value"}}}, true}, - {"\n[m1]\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, - // "blank" empties multi-valued slice -- here same result as above - {"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, - // named slice type: do not treat as multi-value - {"\n[m2]", &cMulti{}, true}, - {"\n[m2]\nmulti=value", &cMulti{}, false}, - {"\n[m2]\nmulti=value1\nmulti=value2", &cMulti{}, false}, -}}, {"type:string", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=", &cBasic{Section: cBasicS1{Name: ""}}, true}, -}}, {"type:bool", []readtest{ - // explicit values - {"[section]\nbool=true", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=yes", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=on", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=1", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=tRuE", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=false", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=no", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=off", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=0", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=NO", &cBool{cBoolS1{false}}, true}, - // "blank" value handled as true - {"[section]\nbool", &cBool{cBoolS1{true}}, true}, - // bool parse errors - {"[section]\nbool=maybe", &cBool{}, false}, - {"[section]\nbool=t", &cBool{}, false}, - {"[section]\nbool=truer", &cBool{}, false}, - {"[section]\nbool=2", &cBool{}, false}, - {"[section]\nbool=-1", &cBool{}, false}, -}}, {"type:numeric", []readtest{ - {"[section]\nint=0", &cBasic{Section: cBasicS1{Int: 0}}, true}, - {"[section]\nint=1", &cBasic{Section: cBasicS1{Int: 1}}, true}, - {"[section]\nint=-1", &cBasic{Section: cBasicS1{Int: -1}}, true}, - {"[section]\nint=0.2", &cBasic{}, false}, - {"[section]\nint=1e3", &cBasic{}, false}, - // primitive [u]int(|8|16|32|64) and big.Int is parsed as dec or hex (not octal) - {"[n1]\nint=010", &cNum{N1: cNumS1{Int: 10}}, true}, - {"[n1]\nint=0x10", &cNum{N1: cNumS1{Int: 0x10}}, true}, - {"[n1]\nbig=1", &cNum{N1: cNumS1{Big: big.NewInt(1)}}, true}, - {"[n1]\nbig=0x10", &cNum{N1: cNumS1{Big: big.NewInt(0x10)}}, true}, - {"[n1]\nbig=010", &cNum{N1: cNumS1{Big: big.NewInt(10)}}, true}, - {"[n2]\nmultiint=010", &cNum{N2: cNumS2{MultiInt: []int{10}}}, true}, - {"[n2]\nmultibig=010", &cNum{N2: cNumS2{MultiBig: []*big.Int{big.NewInt(10)}}}, true}, - // set parse mode for int types via struct tag - {"[n1]\nintdho=010", &cNum{N1: cNumS1{IntDHO: 010}}, true}, - // octal allowed for named type - {"[n3]\nfilemode=0777", &cNum{N3: cNumS3{FileMode: 0777}}, true}, -}}, {"type:textUnmarshaler", []readtest{ - {"[section]\nname=value", &cTxUnm{Section: cTxUnmS1{Name: "value"}}, true}, - {"[section]\nname=error", &cTxUnm{}, false}, -}}, -} - -func TestReadStringInto(t *testing.T) { - for _, tg := range readtests { - for i, tt := range tg.tests { - id := fmt.Sprintf("%s:%d", tg.group, i) - testRead(t, id, tt) - } - } -} - -func TestReadStringIntoMultiBlankPreset(t *testing.T) { - tt := readtest{"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true} - cfg := &cMulti{M1: cMultiS1{[]string{"preset1", "preset2"}}} - testReadInto(t, "multi:blank", tt, cfg) -} - -func testRead(t *testing.T, id string, tt readtest) { - // get the type of the expected result - restyp := reflect.TypeOf(tt.exp).Elem() - // create a new instance to hold the actual result - res := reflect.New(restyp).Interface() - testReadInto(t, id, tt, res) -} - -func testReadInto(t *testing.T, id string, tt readtest, res interface{}) { - err := ReadStringInto(res, tt.gcfg) - if tt.ok { - if err != nil { - t.Errorf("%s fail: got error %v, wanted ok", id, err) - return - } else if !reflect.DeepEqual(res, tt.exp) { - t.Errorf("%s fail: got value %#v, wanted value %#v", id, res, tt.exp) - return - } - if !testing.Short() { - t.Logf("%s pass: got value %#v", id, res) - } - } else { // !tt.ok - if err == nil { - t.Errorf("%s fail: got value %#v, wanted error", id, res) - return - } - if !testing.Short() { - t.Logf("%s pass: got error %v", id, err) - } - } -} - -func TestReadFileInto(t *testing.T) { - res := &struct{ Section struct{ Name string } }{} - err := ReadFileInto(res, "testdata/gcfg_test.gcfg") - if err != nil { - t.Errorf(err.Error()) - } - if "value" != res.Section.Name { - t.Errorf("got %q, wanted %q", res.Section.Name, "value") - } -} - -func TestReadFileIntoUnicode(t *testing.T) { - res := &struct{ X甲 struct{ X乙 string } }{} - err := ReadFileInto(res, "testdata/gcfg_unicode_test.gcfg") - if err != nil { - t.Errorf(err.Error()) - } - if "丙" != res.X甲.X乙 { - t.Errorf("got %q, wanted %q", res.X甲.X乙, "丙") - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/example_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/example_test.go deleted file mode 100644 index 1a15f6b78..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/example_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// 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 scanner_test - -import ( - "fmt" -) - -import ( - "github.com/scalingdata/gcfg/scanner" - "github.com/scalingdata/gcfg/token" -) - -func ExampleScanner_Scan() { - // src is the input that we want to tokenize. - src := []byte(`[profile "A"] -color = blue ; Comment`) - - // Initialize the scanner. - var s scanner.Scanner - fset := token.NewFileSet() // positions are relative to fset - file := fset.AddFile("", fset.Base(), len(src)) // register input "file" - s.Init(file, src, nil /* no error handler */, scanner.ScanComments) - - // Repeated calls to Scan yield the token sequence found in the input. - for { - pos, tok, lit := s.Scan() - if tok == token.EOF { - break - } - fmt.Printf("%s\t%q\t%q\n", fset.Position(pos), tok, lit) - } - - // output: - // 1:1 "[" "" - // 1:2 "IDENT" "profile" - // 1:10 "STRING" "\"A\"" - // 1:13 "]" "" - // 1:14 "\n" "" - // 2:1 "IDENT" "color" - // 2:7 "=" "" - // 2:9 "STRING" "blue" - // 2:14 "COMMENT" "; Comment" -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/scanner_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/scanner_test.go deleted file mode 100644 index e4015736e..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/scanner_test.go +++ /dev/null @@ -1,417 +0,0 @@ -// 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 scanner - -import ( - "os" - "strings" - "testing" -) - -import ( - "github.com/scalingdata/gcfg/token" -) - -var fset = token.NewFileSet() - -const /* class */ ( - special = iota - literal - operator -) - -func tokenclass(tok token.Token) int { - switch { - case tok.IsLiteral(): - return literal - case tok.IsOperator(): - return operator - } - return special -} - -type elt struct { - tok token.Token - lit string - class int - pre string - suf string -} - -var tokens = [...]elt{ - // Special tokens - {token.COMMENT, "; a comment", special, "", "\n"}, - {token.COMMENT, "# a comment", special, "", "\n"}, - - // Operators and delimiters - {token.ASSIGN, "=", operator, "", "value"}, - {token.LBRACK, "[", operator, "", ""}, - {token.RBRACK, "]", operator, "", ""}, - {token.EOL, "\n", operator, "", ""}, - - // Identifiers - {token.IDENT, "foobar", literal, "", ""}, - {token.IDENT, "a۰۱۸", literal, "", ""}, - {token.IDENT, "foo६४", literal, "", ""}, - {token.IDENT, "bar9876", literal, "", ""}, - {token.IDENT, "foo-bar", literal, "", ""}, - {token.IDENT, "foo", literal, ";\n", ""}, - // String literals (subsection names) - {token.STRING, `"foobar"`, literal, "", ""}, - {token.STRING, `"\""`, literal, "", ""}, - // String literals (values) - {token.STRING, `"\n"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "=", ""}, - {token.STRING, `"foo\nbar"`, literal, "=", ""}, - {token.STRING, `"foo\"bar"`, literal, "=", ""}, - {token.STRING, `"foo\\bar"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "= ", ""}, - {token.STRING, `"foobar"`, literal, "=", "\n"}, - {token.STRING, `"foobar"`, literal, "=", ";"}, - {token.STRING, `"foobar"`, literal, "=", " ;"}, - {token.STRING, `"foobar"`, literal, "=", "#"}, - {token.STRING, `"foobar"`, literal, "=", " #"}, - {token.STRING, "foobar", literal, "=", ""}, - {token.STRING, "foobar", literal, "= ", ""}, - {token.STRING, "foobar", literal, "=", " "}, - {token.STRING, `"foo" "bar"`, literal, "=", " "}, - {token.STRING, "foo\\\nbar", literal, "=", ""}, - {token.STRING, "foo\\\r\nbar", literal, "=", ""}, -} - -const whitespace = " \t \n\n\n" // to separate tokens - -var source = func() []byte { - var src []byte - for _, t := range tokens { - src = append(src, t.pre...) - src = append(src, t.lit...) - src = append(src, t.suf...) - src = append(src, whitespace...) - } - return src -}() - -func newlineCount(s string) int { - n := 0 - for i := 0; i < len(s); i++ { - if s[i] == '\n' { - n++ - } - } - return n -} - -func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) { - pos := fset.Position(p) - if pos.Filename != expected.Filename { - t.Errorf("bad filename for %q: got %s, expected %s", lit, pos.Filename, expected.Filename) - } - if pos.Offset != expected.Offset { - t.Errorf("bad position for %q: got %d, expected %d", lit, pos.Offset, expected.Offset) - } - if pos.Line != expected.Line { - t.Errorf("bad line for %q: got %d, expected %d", lit, pos.Line, expected.Line) - } - if pos.Column != expected.Column { - t.Errorf("bad column for %q: got %d, expected %d", lit, pos.Column, expected.Column) - } -} - -// Verify that calling Scan() provides the correct results. -func TestScan(t *testing.T) { - // make source - src_linecount := newlineCount(string(source)) - whitespace_linecount := newlineCount(whitespace) - - index := 0 - - // error handler - eh := func(_ token.Position, msg string) { - t.Errorf("%d: error handler called (msg = %s)", index, msg) - } - - // verify scan - var s Scanner - s.Init(fset.AddFile("", fset.Base(), len(source)), source, eh, ScanComments) - // epos is the expected position - epos := token.Position{ - Filename: "", - Offset: 0, - Line: 1, - Column: 1, - } - for { - pos, tok, lit := s.Scan() - if lit == "" { - // no literal value for non-literal tokens - lit = tok.String() - } - e := elt{token.EOF, "", special, "", ""} - if index < len(tokens) { - e = tokens[index] - } - if tok == token.EOF { - lit = "" - epos.Line = src_linecount - epos.Column = 2 - } - if e.pre != "" && strings.ContainsRune("=;#", rune(e.pre[0])) { - epos.Column = 1 - checkPos(t, lit, pos, epos) - var etok token.Token - if e.pre[0] == '=' { - etok = token.ASSIGN - } else { - etok = token.COMMENT - } - if tok != etok { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, etok) - } - pos, tok, lit = s.Scan() - } - epos.Offset += len(e.pre) - if tok != token.EOF { - epos.Column = 1 + len(e.pre) - } - if e.pre != "" && e.pre[len(e.pre)-1] == '\n' { - epos.Offset-- - epos.Column-- - checkPos(t, lit, pos, epos) - if tok != token.EOL { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) - } - epos.Line++ - epos.Offset++ - epos.Column = 1 - pos, tok, lit = s.Scan() - } - checkPos(t, lit, pos, epos) - if tok != e.tok { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, e.tok) - } - if e.tok.IsLiteral() { - // no CRs in value string literals - elit := e.lit - if strings.ContainsRune(e.pre, '=') { - elit = string(stripCR([]byte(elit))) - epos.Offset += len(e.lit) - len(lit) // correct position - } - if lit != elit { - t.Errorf("bad literal for %q: got %q, expected %q", lit, lit, elit) - } - } - if tokenclass(tok) != e.class { - t.Errorf("bad class for %q: got %d, expected %d", lit, tokenclass(tok), e.class) - } - epos.Offset += len(lit) + len(e.suf) + len(whitespace) - epos.Line += newlineCount(lit) + newlineCount(e.suf) + whitespace_linecount - index++ - if tok == token.EOF { - break - } - if e.suf == "value" { - pos, tok, lit = s.Scan() - if tok != token.STRING { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.STRING) - } - } else if strings.ContainsRune(e.suf, ';') || strings.ContainsRune(e.suf, '#') { - pos, tok, lit = s.Scan() - if tok != token.COMMENT { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.COMMENT) - } - } - // skip EOLs - for i := 0; i < whitespace_linecount+newlineCount(e.suf); i++ { - pos, tok, lit = s.Scan() - if tok != token.EOL { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) - } - } - } - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func TestScanValStringEOF(t *testing.T) { - var s Scanner - src := "= value" - f := fset.AddFile("src", fset.Base(), len(src)) - s.Init(f, []byte(src), nil, 0) - s.Scan() // = - s.Scan() // value - _, tok, _ := s.Scan() // EOF - if tok != token.EOF { - t.Errorf("bad token: got %s, expected %s", tok, token.EOF) - } - if s.ErrorCount > 0 { - t.Error("scanning error") - } -} - -// Verify that initializing the same scanner more then once works correctly. -func TestInit(t *testing.T) { - var s Scanner - - // 1st init - src1 := "\nname = value" - f1 := fset.AddFile("src1", fset.Base(), len(src1)) - s.Init(f1, []byte(src1), nil, 0) - if f1.Size() != len(src1) { - t.Errorf("bad file size: got %d, expected %d", f1.Size(), len(src1)) - } - s.Scan() // \n - s.Scan() // name - _, tok, _ := s.Scan() // = - if tok != token.ASSIGN { - t.Errorf("bad token: got %s, expected %s", tok, token.ASSIGN) - } - - // 2nd init - src2 := "[section]" - f2 := fset.AddFile("src2", fset.Base(), len(src2)) - s.Init(f2, []byte(src2), nil, 0) - if f2.Size() != len(src2) { - t.Errorf("bad file size: got %d, expected %d", f2.Size(), len(src2)) - } - _, tok, _ = s.Scan() // [ - if tok != token.LBRACK { - t.Errorf("bad token: got %s, expected %s", tok, token.LBRACK) - } - - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func TestStdErrorHandler(t *testing.T) { - const src = "@\n" + // illegal character, cause an error - "@ @\n" // two errors on the same line - - var list ErrorList - eh := func(pos token.Position, msg string) { list.Add(pos, msg) } - - var s Scanner - s.Init(fset.AddFile("File1", fset.Base(), len(src)), []byte(src), eh, 0) - for { - if _, tok, _ := s.Scan(); tok == token.EOF { - break - } - } - - if len(list) != s.ErrorCount { - t.Errorf("found %d errors, expected %d", len(list), s.ErrorCount) - } - - if len(list) != 3 { - t.Errorf("found %d raw errors, expected 3", len(list)) - PrintError(os.Stderr, list) - } - - list.Sort() - if len(list) != 3 { - t.Errorf("found %d sorted errors, expected 3", len(list)) - PrintError(os.Stderr, list) - } - - list.RemoveMultiples() - if len(list) != 2 { - t.Errorf("found %d one-per-line errors, expected 2", len(list)) - PrintError(os.Stderr, list) - } -} - -type errorCollector struct { - cnt int // number of errors encountered - msg string // last error message encountered - pos token.Position // last error position encountered -} - -func checkError(t *testing.T, src string, tok token.Token, pos int, err string) { - var s Scanner - var h errorCollector - eh := func(pos token.Position, msg string) { - h.cnt++ - h.msg = msg - h.pos = pos - } - s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), eh, ScanComments) - if src[0] == '=' { - _, _, _ = s.Scan() - } - _, tok0, _ := s.Scan() - _, tok1, _ := s.Scan() - if tok0 != tok { - t.Errorf("%q: got %s, expected %s", src, tok0, tok) - } - if tok1 != token.EOF { - t.Errorf("%q: got %s, expected EOF", src, tok1) - } - cnt := 0 - if err != "" { - cnt = 1 - } - if h.cnt != cnt { - t.Errorf("%q: got cnt %d, expected %d", src, h.cnt, cnt) - } - if h.msg != err { - t.Errorf("%q: got msg %q, expected %q", src, h.msg, err) - } - if h.pos.Offset != pos { - t.Errorf("%q: got offset %d, expected %d", src, h.pos.Offset, pos) - } -} - -var errors = []struct { - src string - tok token.Token - pos int - err string -}{ - {"\a", token.ILLEGAL, 0, "illegal character U+0007"}, - {"/", token.ILLEGAL, 0, "illegal character U+002F '/'"}, - {"_", token.ILLEGAL, 0, "illegal character U+005F '_'"}, - {`…`, token.ILLEGAL, 0, "illegal character U+2026 '…'"}, - {`""`, token.STRING, 0, ""}, - {`"`, token.STRING, 0, "string not terminated"}, - {"\"\n", token.STRING, 0, "string not terminated"}, - {`="`, token.STRING, 1, "string not terminated"}, - {"=\"\n", token.STRING, 1, "string not terminated"}, - {"=\\", token.STRING, 1, "unquoted '\\' must be followed by new line"}, - {"=\\\r", token.STRING, 1, "unquoted '\\' must be followed by new line"}, - {`"\z"`, token.STRING, 2, "unknown escape sequence"}, - {`"\a"`, token.STRING, 2, "unknown escape sequence"}, - {`"\b"`, token.STRING, 2, "unknown escape sequence"}, - {`"\f"`, token.STRING, 2, "unknown escape sequence"}, - {`"\r"`, token.STRING, 2, "unknown escape sequence"}, - {`"\t"`, token.STRING, 2, "unknown escape sequence"}, - {`"\v"`, token.STRING, 2, "unknown escape sequence"}, - {`"\0"`, token.STRING, 2, "unknown escape sequence"}, -} - -func TestScanErrors(t *testing.T) { - for _, e := range errors { - checkError(t, e.src, e.tok, e.pos, e.err) - } -} - -func BenchmarkScan(b *testing.B) { - b.StopTimer() - fset := token.NewFileSet() - file := fset.AddFile("", fset.Base(), len(source)) - var s Scanner - b.StartTimer() - for i := b.N - 1; i >= 0; i-- { - s.Init(file, source, nil, ScanComments) - for { - _, tok, _ := s.Scan() - if tok == token.EOF { - break - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_test.gcfg b/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_test.gcfg deleted file mode 100644 index cddff29ab..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_test.gcfg +++ /dev/null @@ -1,3 +0,0 @@ -; Comment line -[section] -name=value # comment diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_unicode_test.gcfg b/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_unicode_test.gcfg deleted file mode 100644 index 3762a201e..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_unicode_test.gcfg +++ /dev/null @@ -1,3 +0,0 @@ -; Comment line -[甲] -乙=丙 # comment diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/position_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/position_test.go deleted file mode 100644 index 160107df4..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/position_test.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2010 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 token - -import ( - "fmt" - "testing" -) - -func checkPos(t *testing.T, msg string, p, q Position) { - if p.Filename != q.Filename { - t.Errorf("%s: expected filename = %q; got %q", msg, q.Filename, p.Filename) - } - if p.Offset != q.Offset { - t.Errorf("%s: expected offset = %d; got %d", msg, q.Offset, p.Offset) - } - if p.Line != q.Line { - t.Errorf("%s: expected line = %d; got %d", msg, q.Line, p.Line) - } - if p.Column != q.Column { - t.Errorf("%s: expected column = %d; got %d", msg, q.Column, p.Column) - } -} - -func TestNoPos(t *testing.T) { - if NoPos.IsValid() { - t.Errorf("NoPos should not be valid") - } - var fset *FileSet - checkPos(t, "nil NoPos", fset.Position(NoPos), Position{}) - fset = NewFileSet() - checkPos(t, "fset NoPos", fset.Position(NoPos), Position{}) -} - -var tests = []struct { - filename string - source []byte // may be nil - size int - lines []int -}{ - {"a", []byte{}, 0, []int{}}, - {"b", []byte("01234"), 5, []int{0}}, - {"c", []byte("\n\n\n\n\n\n\n\n\n"), 9, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}}, - {"d", nil, 100, []int{0, 5, 10, 20, 30, 70, 71, 72, 80, 85, 90, 99}}, - {"e", nil, 777, []int{0, 80, 100, 120, 130, 180, 267, 455, 500, 567, 620}}, - {"f", []byte("package p\n\nimport \"fmt\""), 23, []int{0, 10, 11}}, - {"g", []byte("package p\n\nimport \"fmt\"\n"), 24, []int{0, 10, 11}}, - {"h", []byte("package p\n\nimport \"fmt\"\n "), 25, []int{0, 10, 11, 24}}, -} - -func linecol(lines []int, offs int) (int, int) { - prevLineOffs := 0 - for line, lineOffs := range lines { - if offs < lineOffs { - return line, offs - prevLineOffs + 1 - } - prevLineOffs = lineOffs - } - return len(lines), offs - prevLineOffs + 1 -} - -func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { - for offs := 0; offs < f.Size(); offs++ { - p := f.Pos(offs) - offs2 := f.Offset(p) - if offs2 != offs { - t.Errorf("%s, Offset: expected offset %d; got %d", f.Name(), offs, offs2) - } - line, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{f.Name(), offs, line, col}) - checkPos(t, msg, fset.Position(p), Position{f.Name(), offs, line, col}) - } -} - -func makeTestSource(size int, lines []int) []byte { - src := make([]byte, size) - for _, offs := range lines { - if offs > 0 { - src[offs-1] = '\n' - } - } - return src -} - -func TestPositions(t *testing.T) { - const delta = 7 // a non-zero base offset increment - fset := NewFileSet() - for _, test := range tests { - // verify consistency of test case - if test.source != nil && len(test.source) != test.size { - t.Errorf("%s: inconsistent test case: expected file size %d; got %d", test.filename, test.size, len(test.source)) - } - - // add file and verify name and size - f := fset.AddFile(test.filename, fset.Base()+delta, test.size) - if f.Name() != test.filename { - t.Errorf("expected filename %q; got %q", test.filename, f.Name()) - } - if f.Size() != test.size { - t.Errorf("%s: expected file size %d; got %d", f.Name(), test.size, f.Size()) - } - if fset.File(f.Pos(0)) != f { - t.Errorf("%s: f.Pos(0) was not found in f", f.Name()) - } - - // add lines individually and verify all positions - for i, offset := range test.lines { - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - // adding the same offset again should be ignored - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected unchanged line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - verifyPositions(t, fset, f, test.lines[0:i+1]) - } - - // add lines with SetLines and verify all positions - if ok := f.SetLines(test.lines); !ok { - t.Errorf("%s: SetLines failed", f.Name()) - } - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLines: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - - // add lines with SetLinesForContent and verify all positions - src := test.source - if src == nil { - // no test source available - create one from scratch - src = makeTestSource(test.size, test.lines) - } - f.SetLinesForContent(src) - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLinesForContent: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - } -} - -func TestLineInfo(t *testing.T) { - fset := NewFileSet() - f := fset.AddFile("foo", fset.Base(), 500) - lines := []int{0, 42, 77, 100, 210, 220, 277, 300, 333, 401} - // add lines individually and provide alternative line information - for _, offs := range lines { - f.AddLine(offs) - f.AddLineInfo(offs, "bar", 42) - } - // verify positions for all offsets - for offs := 0; offs <= f.Size(); offs++ { - p := f.Pos(offs) - _, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{"bar", offs, 42, col}) - checkPos(t, msg, fset.Position(p), Position{"bar", offs, 42, col}) - } -} - -func TestFiles(t *testing.T) { - fset := NewFileSet() - for i, test := range tests { - fset.AddFile(test.filename, fset.Base(), test.size) - j := 0 - fset.Iterate(func(f *File) bool { - if f.Name() != tests[j].filename { - t.Errorf("expected filename = %s; got %s", tests[j].filename, f.Name()) - } - j++ - return true - }) - if j != i+1 { - t.Errorf("expected %d files; got %d", i+1, j) - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/serialize_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/serialize_test.go deleted file mode 100644 index 4e925adb6..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/serialize_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// 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 token - -import ( - "bytes" - "encoding/gob" - "fmt" - "testing" -) - -// equal returns nil if p and q describe the same file set; -// otherwise it returns an error describing the discrepancy. -func equal(p, q *FileSet) error { - if p == q { - // avoid deadlock if p == q - return nil - } - - // not strictly needed for the test - p.mutex.Lock() - q.mutex.Lock() - defer q.mutex.Unlock() - defer p.mutex.Unlock() - - if p.base != q.base { - return fmt.Errorf("different bases: %d != %d", p.base, q.base) - } - - if len(p.files) != len(q.files) { - return fmt.Errorf("different number of files: %d != %d", len(p.files), len(q.files)) - } - - for i, f := range p.files { - g := q.files[i] - if f.set != p { - return fmt.Errorf("wrong fileset for %q", f.name) - } - if g.set != q { - return fmt.Errorf("wrong fileset for %q", g.name) - } - if f.name != g.name { - return fmt.Errorf("different filenames: %q != %q", f.name, g.name) - } - if f.base != g.base { - return fmt.Errorf("different base for %q: %d != %d", f.name, f.base, g.base) - } - if f.size != g.size { - return fmt.Errorf("different size for %q: %d != %d", f.name, f.size, g.size) - } - for j, l := range f.lines { - m := g.lines[j] - if l != m { - return fmt.Errorf("different offsets for %q", f.name) - } - } - for j, l := range f.infos { - m := g.infos[j] - if l.Offset != m.Offset || l.Filename != m.Filename || l.Line != m.Line { - return fmt.Errorf("different infos for %q", f.name) - } - } - } - - // we don't care about .last - it's just a cache - return nil -} - -func checkSerialize(t *testing.T, p *FileSet) { - var buf bytes.Buffer - encode := func(x interface{}) error { - return gob.NewEncoder(&buf).Encode(x) - } - if err := p.Write(encode); err != nil { - t.Errorf("writing fileset failed: %s", err) - return - } - q := NewFileSet() - decode := func(x interface{}) error { - return gob.NewDecoder(&buf).Decode(x) - } - if err := q.Read(decode); err != nil { - t.Errorf("reading fileset failed: %s", err) - return - } - if err := equal(p, q); err != nil { - t.Errorf("filesets not identical: %s", err) - } -} - -func TestSerialization(t *testing.T) { - p := NewFileSet() - checkSerialize(t, p) - // add some files - for i := 0; i < 10; i++ { - f := p.AddFile(fmt.Sprintf("file%d", i), p.Base()+i, i*100) - checkSerialize(t, p) - // add some lines and alternative file infos - line := 1000 - for offs := 0; offs < f.Size(); offs += 40 + i { - f.AddLine(offs) - if offs%7 == 0 { - f.AddLineInfo(offs, fmt.Sprintf("file%d", offs), line) - line += 33 - } - } - checkSerialize(t, p) - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/enum_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/enum_test.go deleted file mode 100644 index 4bf135e67..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/enum_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package types - -import ( - "testing" -) - -func TestEnumParserBool(t *testing.T) { - for _, tt := range []struct { - val string - res bool - ok bool - }{ - {val: "tRuE", res: true, ok: true}, - {val: "False", res: false, ok: true}, - {val: "t", ok: false}, - } { - b, err := ParseBool(tt.val) - switch { - case tt.ok && err != nil: - t.Errorf("%q: got error %v, want %v", tt.val, err, tt.res) - case !tt.ok && err == nil: - t.Errorf("%q: got %v, want error", tt.val, b) - case tt.ok && b != tt.res: - t.Errorf("%q: got %v, want %v", tt.val, b, tt.res) - default: - t.Logf("%q: got %v, %v", tt.val, b, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/int_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/int_test.go deleted file mode 100644 index b63dbcbae..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/int_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package types - -import ( - "reflect" - "testing" -) - -func elem(p interface{}) interface{} { - return reflect.ValueOf(p).Elem().Interface() -} - -func TestParseInt(t *testing.T) { - for _, tt := range []struct { - val string - mode IntMode - exp interface{} - ok bool - }{ - {"0", Dec, int(0), true}, - {"10", Dec, int(10), true}, - {"-10", Dec, int(-10), true}, - {"x", Dec, int(0), false}, - {"0xa", Hex, int(0xa), true}, - {"a", Hex, int(0xa), true}, - {"10", Hex, int(0x10), true}, - {"-0xa", Hex, int(-0xa), true}, - {"0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x - {"-0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x - {"-a", Hex, int(-0xa), true}, - {"-10", Hex, int(-0x10), true}, - {"x", Hex, int(0), false}, - {"10", Oct, int(010), true}, - {"010", Oct, int(010), true}, - {"-10", Oct, int(-010), true}, - {"-010", Oct, int(-010), true}, - {"10", Dec | Hex, int(10), true}, - {"010", Dec | Hex, int(10), true}, - {"0x10", Dec | Hex, int(0x10), true}, - {"10", Dec | Oct, int(10), true}, - {"010", Dec | Oct, int(010), true}, - {"0x10", Dec | Oct, int(0), false}, - {"10", Hex | Oct, int(0), false}, // need prefix to distinguish Hex/Oct - {"010", Hex | Oct, int(010), true}, - {"0x10", Hex | Oct, int(0x10), true}, - {"10", Dec | Hex | Oct, int(10), true}, - {"010", Dec | Hex | Oct, int(010), true}, - {"0x10", Dec | Hex | Oct, int(0x10), true}, - } { - typ := reflect.TypeOf(tt.exp) - res := reflect.New(typ).Interface() - err := ParseInt(res, tt.val, tt.mode) - switch { - case tt.ok && err != nil: - t.Errorf("ParseInt(%v, %#v, %v): fail; got error %v, want ok", - typ, tt.val, tt.mode, err) - case !tt.ok && err == nil: - t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want error", - typ, tt.val, tt.mode, elem(res)) - case tt.ok && !reflect.DeepEqual(elem(res), tt.exp): - t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want %v", - typ, tt.val, tt.mode, elem(res), tt.exp) - default: - t.Logf("ParseInt(%v, %#v, %s): pass; got %v, error %v", - typ, tt.val, tt.mode, elem(res), err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/scan_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/scan_test.go deleted file mode 100644 index a8083e04f..000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/scan_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import ( - "reflect" - "testing" -) - -func TestScanFully(t *testing.T) { - for _, tt := range []struct { - val string - verb byte - res interface{} - ok bool - }{ - {"a", 'v', int(0), false}, - {"0x", 'v', int(0), true}, - {"0x", 'd', int(0), false}, - } { - d := reflect.New(reflect.TypeOf(tt.res)).Interface() - err := ScanFully(d, tt.val, tt.verb) - switch { - case tt.ok && err != nil: - t.Errorf("ScanFully(%T, %q, '%c'): want ok, got error %v", - d, tt.val, tt.verb, err) - case !tt.ok && err == nil: - t.Errorf("ScanFully(%T, %q, '%c'): want error, got %v", - d, tt.val, tt.verb, elem(d)) - case tt.ok && err == nil && !reflect.DeepEqual(tt.res, elem(d)): - t.Errorf("ScanFully(%T, %q, '%c'): want %v, got %v", - d, tt.val, tt.verb, tt.res, elem(d)) - default: - t.Logf("ScanFully(%T, %q, '%c') = %v; *ptr==%v", - d, tt.val, tt.verb, err, elem(d)) - } - } -} diff --git a/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go b/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go deleted file mode 100644 index ad03201ca..000000000 --- a/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package sanitized_anchor_name_test - -import ( - "fmt" - - "github.com/shurcooL/sanitized_anchor_name" -) - -func ExampleCreate() { - anchorName := sanitized_anchor_name.Create("This is a header") - - fmt.Println(anchorName) - - // Output: - // this-is-a-header -} - -func ExampleCreate2() { - fmt.Println(sanitized_anchor_name.Create("This is a header")) - fmt.Println(sanitized_anchor_name.Create("This is also a header")) - fmt.Println(sanitized_anchor_name.Create("main.go")) - fmt.Println(sanitized_anchor_name.Create("Article 123")) - fmt.Println(sanitized_anchor_name.Create("<- Let's try this, shall we?")) - fmt.Printf("%q\n", sanitized_anchor_name.Create(" ")) - fmt.Println(sanitized_anchor_name.Create("Hello, 世界")) - - // Output: - // this-is-a-header - // this-is-also-a-header - // main-go - // article-123 - // let-s-try-this-shall-we - // "" - // hello-世界 -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go deleted file mode 100644 index 53656c7fd..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func checkOmit(t *testing.T, found, unexpected string) { - if strings.Contains(found, unexpected) { - t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected) - } -} - -func check(t *testing.T, found, expected string) { - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } -} - -// World worst custom function, just keep telling you to enter hello! -const ( - bash_completion_func = `__custom_func() { -COMPREPLY=( "hello" ) -} -` -) - -func TestBashCompletions(t *testing.T) { - c := initializeWithRootCmd() - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated) - - // custom completion function - c.BashCompletionFunction = bash_completion_func - - // required flag - c.MarkFlagRequired("introot") - - // valid nouns - validArgs := []string{"pods", "nodes", "services", "replicationControllers"} - c.ValidArgs = validArgs - - // filename - var flagval string - c.Flags().StringVar(&flagval, "filename", "", "Enter a filename") - c.MarkFlagFilename("filename", "json", "yaml", "yml") - - // persistent filename - var flagvalPersistent string - c.PersistentFlags().StringVar(&flagvalPersistent, "persistent-filename", "", "Enter a filename") - c.MarkPersistentFlagFilename("persistent-filename") - c.MarkPersistentFlagRequired("persistent-filename") - - // filename extensions - var flagvalExt string - c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)") - c.MarkFlagFilename("filename-ext") - - // subdirectories in a given directory - var flagvalTheme string - c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)") - c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) - - out := new(bytes.Buffer) - c.GenBashCompletion(out) - str := out.String() - - check(t, str, "_cobra-test") - check(t, str, "_cobra-test_echo") - check(t, str, "_cobra-test_echo_times") - check(t, str, "_cobra-test_print") - - // check for required flags - check(t, str, `must_have_one_flag+=("--introot=")`) - check(t, str, `must_have_one_flag+=("--persistent-filename=")`) - // check for custom completion function - check(t, str, `COMPREPLY=( "hello" )`) - // check for required nouns - check(t, str, `must_have_one_noun+=("pods")`) - // check for filename extension flags - check(t, str, `flags_completion+=("_filedir")`) - // check for filename extension flags - check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`) - // check for subdirs_in_dir flags - check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`) - - checkOmit(t, str, cmdDeprecated.Name()) -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/add.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/add.go deleted file mode 100644 index b89d4c474..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/add.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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 cmd - -import ( - "fmt" - "path/filepath" - "strings" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -func init() { - RootCmd.AddCommand(addCmd) -} - -var pName string - -// initialize Command -var addCmd = &cobra.Command{ - Use: "add [command name]", - Aliases: []string{"command"}, - Short: "Add a command to a Cobra Application", - Long: `Add (cobra add) will create a new command, with a license and -the appropriate structure for a Cobra-based CLI application, -and register it to its parent (default RootCmd). - -If you want your command to be public, pass in the command name -with an initial uppercase letter. - -Example: cobra add server -> resulting in a new cmd/server.go - `, - - Run: func(cmd *cobra.Command, args []string) { - if len(args) != 1 { - er("add needs a name for the command") - } - guessProjectPath() - createCmdFile(args[0]) - }, -} - -func init() { - addCmd.Flags().StringVarP(&pName, "parent", "p", "RootCmd", "name of parent command for this command") -} - -func parentName() string { - if !strings.HasSuffix(strings.ToLower(pName), "cmd") { - return pName + "Cmd" - } - - return pName -} - -func createCmdFile(cmdName string) { - lic := getLicense() - - template := `{{ comment .copyright }} -{{ comment .license }} - -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -// {{.cmdName}}Cmd represents the {{.cmdName}} command -var {{ .cmdName }}Cmd = &cobra.Command{ - Use: "{{ .cmdName }}", - Short: "A brief description of your command", - Long: ` + "`" + `A longer description that spans multiple lines and likely contains examples -and usage of using your command. For example: - -Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.` + "`" + `, - Run: func(cmd *cobra.Command, args []string) { - // TODO: Work your own magic here - fmt.Println("{{ .cmdName }} called") - }, -} - -func init() { - {{ .parentName }}.AddCommand({{ .cmdName }}Cmd) - - // Here you will define your flags and configuration settings. - - // Cobra supports Persistent Flags which will work for this command - // and all subcommands, e.g.: - // {{.cmdName}}Cmd.PersistentFlags().String("foo", "", "A help for foo") - - // Cobra supports local flags which will only run when this command - // is called directly, e.g.: - // {{.cmdName}}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") - -} -` - - var data map[string]interface{} - data = make(map[string]interface{}) - - data["copyright"] = copyrightLine() - data["license"] = lic.Header - data["appName"] = projectName() - data["viper"] = viper.GetBool("useViper") - data["parentName"] = parentName() - data["cmdName"] = cmdName - - err := writeTemplateToFile(filepath.Join(ProjectPath(), guessCmdDir()), cmdName+".go", template, data) - if err != nil { - er(err) - } - fmt.Println(cmdName, "created at", filepath.Join(ProjectPath(), guessCmdDir(), cmdName+".go")) -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers.go deleted file mode 100644 index 3f6357f0e..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers.go +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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 cmd - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "text/template" - "time" - - "github.com/spf13/viper" -) - -// var BaseDir = "" -// var AppName = "" -// var CommandDir = "" - -var funcMap template.FuncMap -var projectPath = "" -var inputPath = "" -var projectBase = "" - -// for testing only -var testWd = "" - -var cmdDirs = []string{"cmd", "cmds", "command", "commands"} - -func init() { - funcMap = template.FuncMap{ - "comment": commentifyString, - } -} - -func er(msg interface{}) { - fmt.Println("Error:", msg) - os.Exit(-1) -} - -// Check if a file or directory exists. -func exists(path string) (bool, error) { - _, err := os.Stat(path) - if err == nil { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -func ProjectPath() string { - if projectPath == "" { - guessProjectPath() - } - - return projectPath -} - -// wrapper of the os package so we can test better -func getWd() (string, error) { - if testWd == "" { - return os.Getwd() - } - return testWd, nil -} - -func guessCmdDir() string { - guessProjectPath() - if b, _ := isEmpty(projectPath); b { - return "cmd" - } - - files, _ := filepath.Glob(projectPath + string(os.PathSeparator) + "c*") - for _, f := range files { - for _, c := range cmdDirs { - if f == c { - return c - } - } - } - - return "cmd" -} - -func guessImportPath() string { - guessProjectPath() - - if !strings.HasPrefix(projectPath, getSrcPath()) { - er("Cobra only supports project within $GOPATH") - } - - return filepath.Clean(strings.TrimPrefix(projectPath, getSrcPath())) -} - -func getSrcPath() string { - return filepath.Join(os.Getenv("GOPATH"), "src") + string(os.PathSeparator) -} - -func projectName() string { - return filepath.Base(ProjectPath()) -} - -func guessProjectPath() { - // if no path is provided... assume CWD. - if inputPath == "" { - x, err := getWd() - if err != nil { - er(err) - } - - // inspect CWD - base := filepath.Base(x) - - // if we are in the cmd directory.. back up - for _, c := range cmdDirs { - if base == c { - projectPath = filepath.Dir(x) - return - } - } - - if projectPath == "" { - projectPath = filepath.Clean(x) - return - } - } - - srcPath := getSrcPath() - // if provided, inspect for logical locations - if strings.ContainsRune(inputPath, os.PathSeparator) { - if filepath.IsAbs(inputPath) { - // if Absolute, use it - projectPath = filepath.Clean(inputPath) - return - } - // If not absolute but contains slashes, - // assuming it means create it from $GOPATH - count := strings.Count(inputPath, string(os.PathSeparator)) - - switch count { - // If only one directory deep, assume "github.com" - case 1: - projectPath = filepath.Join(srcPath, "github.com", inputPath) - return - case 2: - projectPath = filepath.Join(srcPath, inputPath) - return - default: - er("Unknown directory") - } - } else { - // hardest case.. just a word. - if projectBase == "" { - x, err := getWd() - if err == nil { - projectPath = filepath.Join(x, inputPath) - return - } - er(err) - } else { - projectPath = filepath.Join(srcPath, projectBase, inputPath) - return - } - } -} - -// isEmpty checks if a given path is empty. -func isEmpty(path string) (bool, error) { - if b, _ := exists(path); !b { - return false, fmt.Errorf("%q path does not exist", path) - } - fi, err := os.Stat(path) - if err != nil { - return false, err - } - if fi.IsDir() { - f, err := os.Open(path) - // FIX: Resource leak - f.close() should be called here by defer or is missed - // if the err != nil branch is taken. - defer f.Close() - if err != nil { - return false, err - } - list, err := f.Readdir(-1) - // f.Close() - see bug fix above - return len(list) == 0, nil - } - return fi.Size() == 0, nil -} - -// isDir checks if a given path is a directory. -func isDir(path string) (bool, error) { - fi, err := os.Stat(path) - if err != nil { - return false, err - } - return fi.IsDir(), nil -} - -// dirExists checks if a path exists and is a directory. -func dirExists(path string) (bool, error) { - fi, err := os.Stat(path) - if err == nil && fi.IsDir() { - return true, nil - } - if os.IsNotExist(err) { - return false, nil - } - return false, err -} - -func writeTemplateToFile(path string, file string, template string, data interface{}) error { - filename := filepath.Join(path, file) - - r, err := templateToReader(template, data) - - if err != nil { - return err - } - - err = safeWriteToDisk(filename, r) - - if err != nil { - return err - } - return nil -} - -func writeStringToFile(path, file, text string) error { - filename := filepath.Join(path, file) - - r := strings.NewReader(text) - err := safeWriteToDisk(filename, r) - - if err != nil { - return err - } - return nil -} - -func templateToReader(tpl string, data interface{}) (io.Reader, error) { - tmpl := template.New("") - tmpl.Funcs(funcMap) - tmpl, err := tmpl.Parse(tpl) - - if err != nil { - return nil, err - } - buf := new(bytes.Buffer) - err = tmpl.Execute(buf, data) - - return buf, err -} - -// Same as WriteToDisk but checks to see if file/directory already exists. -func safeWriteToDisk(inpath string, r io.Reader) (err error) { - dir, _ := filepath.Split(inpath) - ospath := filepath.FromSlash(dir) - - if ospath != "" { - err = os.MkdirAll(ospath, 0777) // rwx, rw, r - if err != nil { - return - } - } - - ex, err := exists(inpath) - if err != nil { - return - } - if ex { - return fmt.Errorf("%v already exists", inpath) - } - - file, err := os.Create(inpath) - if err != nil { - return - } - defer file.Close() - - _, err = io.Copy(file, r) - return -} - -func getLicense() License { - l := whichLicense() - if l != "" { - if x, ok := Licenses[l]; ok { - return x - } - } - - return Licenses["apache"] -} - -func whichLicense() string { - // if explicitly flagged, use that - if userLicense != "" { - return matchLicense(userLicense) - } - - // if already present in the project, use that - // TODO: Inspect project for existing license - - // default to viper's setting - - return matchLicense(viper.GetString("license")) -} - -func copyrightLine() string { - author := viper.GetString("author") - year := time.Now().Format("2006") - - return "Copyright © " + year + " " + author -} - -func commentifyString(in string) string { - var newlines []string - lines := strings.Split(in, "\n") - for _, x := range lines { - if !strings.HasPrefix(x, "//") { - if x != "" { - newlines = append(newlines, "// "+x) - } else { - newlines = append(newlines, "//") - } - } else { - newlines = append(newlines, x) - } - } - return strings.Join(newlines, "\n") -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers_test.go deleted file mode 100644 index 564ddbe5f..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func checkGuess(t *testing.T, wd, input, expected string) { - testWd = wd - inputPath = input - guessProjectPath() - - if projectPath != expected { - t.Errorf("Unexpected Project Path. \n Got: %q\nExpected: %q\n", projectPath, expected) - } - - reset() -} - -func reset() { - testWd = "" - inputPath = "" - projectPath = "" -} - -func TestProjectPath(t *testing.T) { - checkGuess(t, "", "github.com/spf13/hugo", getSrcPath()+"github.com/spf13/hugo") - checkGuess(t, "", "spf13/hugo", getSrcPath()+"github.com/spf13/hugo") - checkGuess(t, "", "/bar/foo", "/bar/foo") - checkGuess(t, "/bar/foo", "baz", "/bar/foo/baz") - checkGuess(t, "/bar/foo/cmd", "", "/bar/foo") - checkGuess(t, "/bar/foo/command", "", "/bar/foo") - checkGuess(t, "/bar/foo/commands", "", "/bar/foo") - checkGuess(t, "github.com/spf13/hugo/../hugo", "", "github.com/spf13/hugo") -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/init.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/init.go deleted file mode 100644 index e3c0b45f0..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/init.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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 cmd - -import ( - "fmt" - "os" - "strings" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -func init() { - RootCmd.AddCommand(initCmd) -} - -// initialize Command -var initCmd = &cobra.Command{ - Use: "init [name]", - Aliases: []string{"initialize", "initalise", "create"}, - Short: "Initalize a Cobra Application", - Long: `Initialize (cobra init) will create a new application, with a license -and the appropriate structure for a Cobra-based CLI application. - - * If a name is provided, it will be created in the current directory; - * If no name is provided, the current directory will be assumed; - * If a relative path is provided, it will be created inside $GOPATH - (e.g. github.com/spf13/hugo); - * If an absolute path is provided, it will be created; - * If the directory already exists but is empty, it will be used. - -Init will not use an exiting directory with contents.`, - - Run: func(cmd *cobra.Command, args []string) { - switch len(args) { - case 0: - inputPath = "" - - case 1: - inputPath = args[0] - - default: - er("init doesn't support more than 1 parameter") - } - guessProjectPath() - initalizePath(projectPath) - }, -} - -func initalizePath(path string) { - b, err := exists(path) - if err != nil { - er(err) - } - - if !b { // If path doesn't yet exist, create it - err := os.MkdirAll(path, os.ModePerm) - if err != nil { - er(err) - } - } else { // If path exists and is not empty don't use it - empty, err := exists(path) - if err != nil { - er(err) - } - if !empty { - er("Cobra will not create a new project in a non empty directory") - } - } - // We have a directory and it's empty.. Time to initialize it. - - createLicenseFile() - createMainFile() - createRootCmdFile() -} - -func createLicenseFile() { - lic := getLicense() - - template := lic.Text - - var data map[string]interface{} - data = make(map[string]interface{}) - - // Try to remove the email address, if any - data["copyright"] = strings.Split(copyrightLine(), " <")[0] - - err := writeTemplateToFile(ProjectPath(), "LICENSE", template, data) - _ = err - // if err != nil { - // er(err) - // } -} - -func createMainFile() { - lic := getLicense() - - template := `{{ comment .copyright }} -{{ comment .license }} - -package main - -import "{{ .importpath }}" - -func main() { - cmd.Execute() -} -` - var data map[string]interface{} - data = make(map[string]interface{}) - - data["copyright"] = copyrightLine() - data["license"] = lic.Header - data["importpath"] = guessImportPath() + "/" + guessCmdDir() - - err := writeTemplateToFile(ProjectPath(), "main.go", template, data) - _ = err - // if err != nil { - // er(err) - // } -} - -func createRootCmdFile() { - lic := getLicense() - - template := `{{ comment .copyright }} -{{ comment .license }} - -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" -{{ if .viper }} "github.com/spf13/viper" -{{ end }}) -{{if .viper}} -var cfgFile string -{{ end }} -// This represents the base command when called without any subcommands -var RootCmd = &cobra.Command{ - Use: "{{ .appName }}", - Short: "A brief description of your application", - Long: ` + "`" + `A longer description that spans multiple lines and likely contains -examples and usage of using your application. For example: - -Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.` + "`" + `, -// Uncomment the following line if your bare application -// has an action associated with it: -// Run: func(cmd *cobra.Command, args []string) { }, -} - -// Execute adds all child commands to the root command sets flags appropriately. -// This is called by main.main(). It only needs to happen once to the rootCmd. -func Execute() { - if err := RootCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(-1) - } -} - -func init() { -{{ if .viper }} cobra.OnInitialize(initConfig) - -{{ end }} // Here you will define your flags and configuration settings. - // Cobra supports Persistent Flags, which, if defined here, - // will be global for your application. -{{ if .viper }} - RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)") -{{ else }} - // RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)") -{{ end }} // Cobra also supports local flags, which will only run - // when this action is called directly. - RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") -} -{{ if .viper }} -// initConfig reads in config file and ENV variables if set. -func initConfig() { - if cfgFile != "" { // enable ability to specify config file via flag - viper.SetConfigFile(cfgFile) - } - - viper.SetConfigName(".{{ .appName }}") // name of config file (without extension) - viper.AddConfigPath("$HOME") // adding home directory as first search path - viper.AutomaticEnv() // read in environment variables that match - - // If a config file is found, read it in. - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -{{ end }}` - - var data map[string]interface{} - data = make(map[string]interface{}) - - data["copyright"] = copyrightLine() - data["license"] = lic.Header - data["appName"] = projectName() - data["viper"] = viper.GetBool("useViper") - - err := writeTemplateToFile(ProjectPath()+string(os.PathSeparator)+guessCmdDir(), "root.go", template, data) - if err != nil { - er(err) - } - - fmt.Println("Your Cobra application is ready at") - fmt.Println(ProjectPath()) - fmt.Println("Give it a try by going there and running `go run main.go`") - fmt.Println("Add commands to it by running `cobra add [cmdname]`") -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/licenses.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/licenses.go deleted file mode 100644 index 5ad9c96ef..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/licenses.go +++ /dev/null @@ -1,1133 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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. - -// Parts inspired by https://github.com/ryanuber/go-license - -package cmd - -import "strings" - -//Licenses contains all possible licenses a user can chose from -var Licenses map[string]License - -//License represents a software license agreement, containing the Name of -// the license, its possible matches (on the command line as given to cobra) -// the header to be used with each file on the file's creating, and the text -// of the license -type License struct { - Name string // The type of license in use - PossibleMatches []string // Similar names to guess - Text string // License text data - Header string // License header for source files -} - -// given a license name (in), try to match the license indicated -func matchLicense(in string) string { - for key, lic := range Licenses { - for _, match := range lic.PossibleMatches { - if strings.EqualFold(in, match) { - return key - } - } - } - return "" -} - -func init() { - Licenses = make(map[string]License) - - Licenses["apache"] = License{ - Name: "Apache 2.0", - PossibleMatches: []string{"apache", "apache20", "apache 2.0", "apache2.0", "apache-2.0"}, - Header: ` -// 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.`, - Text: ` - 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. -`, - } - - Licenses["mit"] = License{ - Name: "Mit", - PossibleMatches: []string{"mit"}, - Header: ` -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.`, - Text: `The MIT License (MIT) - -{{ .copyright }} - -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. -`, - } - - Licenses["bsd"] = License{ - Name: "NewBSD", - PossibleMatches: []string{"bsd", "newbsd", "3 clause bsd"}, - Header: ` -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. 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. - -3. Neither the name of the copyright holder 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 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.`, - Text: `{{ .copyright }} -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. 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. - -3. Neither the name of the copyright holder 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 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. -`, - } - - Licenses["freebsd"] = License{ - Name: "Simplified BSD License", - PossibleMatches: []string{"freebsd", "simpbsd", "simple bsd", "2 clause bsd"}, - Header: ` -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. 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.`, - Text: `{{ .copyright }} -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -2. 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. -`, - } - - Licenses["gpl3"] = License{ - Name: "GNU General Public License 3.0", - PossibleMatches: []string{"gpl3", "gpl", "gnu gpl3", "gnu gpl"}, - Header: `{{ .copyright }} - - This file is part of {{ .appName }}. - - {{ .appName }} is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - {{ .appName }} is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with {{ .appName }}. If not, see . - `, - Text: ` GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands 'show w' and 'show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. -`, - } - - // Licenses["apache20"] = License{ - // Name: "Apache 2.0", - // PossibleMatches: []string{"apache", "apache20", ""}, - // Header: ` - // `, - // Text: ` - // `, - // } -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/root.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/root.go deleted file mode 100644 index 610386ad7..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/root.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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 cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var cfgFile string -var userLicense string - -// This represents the base command when called without any subcommands -var RootCmd = &cobra.Command{ - Use: "cobra", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, -} - -//Execute adds all child commands to the root command sets flags appropriately. -func Execute() { - if err := RootCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(-1) - } -} - -func init() { - cobra.OnInitialize(initConfig) - RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory, e.g. github.com/spf13/") - RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution") - RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)") - RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration") - viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase")) - viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - viper.SetDefault("licenseText", ` -// 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. -`) -} - -// Read in config file and ENV variables if set. -func initConfig() { - if cfgFile != "" { // enable ability to specify config file via flag - viper.SetConfigFile(cfgFile) - } - - viper.SetConfigName(".cobra") // name of config file (without extension) - viper.AddConfigPath("$HOME") // adding home directory as first search path - viper.AutomaticEnv() // read in environment variables that match - - // If a config file is found, read it in. - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/main.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra/main.go deleted file mode 100644 index c3a9d9cb0..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra/main.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright © 2015 Steve Francia . -// -// 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 main - -import "github.com/spf13/cobra/cobra/cmd" - -func main() { - cmd.Execute() -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go deleted file mode 100644 index e4138802e..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go +++ /dev/null @@ -1,1163 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "reflect" - "runtime" - "strings" - "testing" - "text/template" - - "github.com/spf13/pflag" -) - -var _ = fmt.Println -var _ = os.Stderr - -var tp, te, tt, t1, tr []string -var rootPersPre, echoPre, echoPersPre, timesPersPre []string -var flagb1, flagb2, flagb3, flagbr, flagbp bool -var flags1, flags2a, flags2b, flags3, outs string -var flagi1, flagi2, flagi3, flagir int -var globalFlag1 bool -var flagEcho, rootcalled bool -var versionUsed int - -const strtwoParentHelp = "help message for parent flag strtwo" -const strtwoChildHelp = "help message for child flag strtwo" - -var cmdHidden = &Command{ - Use: "hide [secret string to print]", - Short: "Print anything to screen (if command is known)", - Long: `an absolutely utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - outs = "hidden" - }, - Hidden: true, -} - -var cmdPrint = &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an absolutely utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, -} - -var cmdEcho = &Command{ - Use: "echo [string to echo]", - Aliases: []string{"say"}, - Short: "Echo anything to the screen", - Long: `an utterly useless command for testing.`, - Example: "Just run cobra-test echo", - PersistentPreRun: func(cmd *Command, args []string) { - echoPersPre = args - }, - PreRun: func(cmd *Command, args []string) { - echoPre = args - }, - Run: func(cmd *Command, args []string) { - te = args - }, -} - -var cmdEchoSub = &Command{ - Use: "echosub [string to print]", - Short: "second sub command for echo", - Long: `an absolutely utterly useless command for testing gendocs!.`, - Run: func(cmd *Command, args []string) { - }, -} - -var cmdDeprecated = &Command{ - Use: "deprecated [can't do anything here]", - Short: "A command which is deprecated", - Long: `an absolutely utterly useless command for testing deprecation!.`, - Deprecated: "Please use echo instead", - Run: func(cmd *Command, args []string) { - }, -} - -var cmdTimes = &Command{ - Use: "times [# times] [string to echo]", - SuggestFor: []string{"counts"}, - Short: "Echo anything to the screen more times", - Long: `a slightly useless command for testing.`, - PersistentPreRun: func(cmd *Command, args []string) { - timesPersPre = args - }, - Run: func(cmd *Command, args []string) { - tt = args - }, -} - -var cmdRootNoRun = &Command{ - Use: "cobra-test", - Short: "The root can run its own function", - Long: "The root description for help", - PersistentPreRun: func(cmd *Command, args []string) { - rootPersPre = args - }, -} - -var cmdRootSameName = &Command{ - Use: "print", - Short: "Root with the same name as a subcommand", - Long: "The root description for help", -} - -var cmdRootWithRun = &Command{ - Use: "cobra-test", - Short: "The root can run its own function", - Long: "The root description for help", - Run: func(cmd *Command, args []string) { - tr = args - rootcalled = true - }, -} - -var cmdSubNoRun = &Command{ - Use: "subnorun", - Short: "A subcommand without a Run function", - Long: "A long output about a subcommand without a Run function", -} - -var cmdVersion1 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `First version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 1 - }, -} - -var cmdVersion2 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `Second version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 2 - }, -} - -func flagInit() { - cmdEcho.ResetFlags() - cmdPrint.ResetFlags() - cmdTimes.ResetFlags() - cmdRootNoRun.ResetFlags() - cmdRootSameName.ResetFlags() - cmdRootWithRun.ResetFlags() - cmdSubNoRun.ResetFlags() - cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp) - cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone") - cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo") - cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree") - cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone") - cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool") - cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp) - cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree") - cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone") - cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo") - cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree") - cmdVersion1.ResetFlags() - cmdVersion2.ResetFlags() -} - -func commandInit() { - cmdEcho.ResetCommands() - cmdPrint.ResetCommands() - cmdTimes.ResetCommands() - cmdRootNoRun.ResetCommands() - cmdRootSameName.ResetCommands() - cmdRootWithRun.ResetCommands() - cmdSubNoRun.ResetCommands() -} - -func initialize() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - - var c = cmdRootNoRun - flagInit() - commandInit() - return c -} - -func initializeWithSameName() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - var c = cmdRootSameName - flagInit() - commandInit() - return c -} - -func initializeWithRootCmd() *Command { - cmdRootWithRun.ResetCommands() - tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false - flagInit() - cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot") - cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot") - commandInit() - return cmdRootWithRun -} - -type resulter struct { - Error error - Output string - Command *Command -} - -func fullSetupTest(input string) resulter { - c := initializeWithRootCmd() - - return fullTester(c, input) -} - -func noRRSetupTestSilenced(input string) resulter { - c := initialize() - c.SilenceErrors = true - c.SilenceUsage = true - return fullTester(c, input) -} - -func noRRSetupTest(input string) resulter { - c := initialize() - - return fullTester(c, input) -} - -func rootOnlySetupTest(input string) resulter { - c := initializeWithRootCmd() - - return simpleTester(c, input) -} - -func simpleTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func simpleTesterC(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - c.SetArgs(strings.Split(input, " ")) - - cmd, err := c.ExecuteC() - output := buf.String() - - return resulter{err, output, cmd} -} - -func fullTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func logErr(t *testing.T, found, expected string) { - out := new(bytes.Buffer) - - _, _, line, ok := runtime.Caller(2) - if ok { - fmt.Fprintf(out, "Line: %d ", line) - } - fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - t.Errorf(out.String()) -} - -func checkStringContains(t *testing.T, found, expected string) { - if !strings.Contains(found, expected) { - logErr(t, found, expected) - } -} - -func checkResultContains(t *testing.T, x resulter, check string) { - checkStringContains(t, x.Output, check) -} - -func checkStringOmits(t *testing.T, found, expected string) { - if strings.Contains(found, expected) { - logErr(t, found, expected) - } -} - -func checkResultOmits(t *testing.T, x resulter, check string) { - checkStringOmits(t, x.Output, check) -} - -func checkOutputContains(t *testing.T, c *Command, check string) { - buf := new(bytes.Buffer) - c.SetOutput(buf) - c.Execute() - - if !strings.Contains(buf.String(), check) { - logErr(t, buf.String(), check) - } -} - -func TestSingleCommand(t *testing.T) { - noRRSetupTest("print one two") - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestChildCommand(t *testing.T) { - noRRSetupTest("echo times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestCommandAlias(t *testing.T) { - noRRSetupTest("say times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("ech times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - - EnablePrefixMatching = false -} - -func TestNoPrefixMatching(t *testing.T) { - EnablePrefixMatching = false - - noRRSetupTest("ech times one two") - - if !(tt == nil && te == nil && tp == nil) { - t.Error("Wrong command called") - } -} - -func TestAliasPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("sa times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - EnablePrefixMatching = false -} - -func TestChildSameName(t *testing.T) { - c := initializeWithSameName() - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(strings.Split("print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestGrandChildSameName(t *testing.T) { - c := initializeWithSameName() - cmdTimes.AddCommand(cmdPrint) - c.AddCommand(cmdTimes) - c.SetArgs(strings.Split("times print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestFlagLong(t *testing.T) { - noRRSetupTest("echo --intone=13 something -- here") - - if cmdEcho.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash()) - } - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } -} - -func TestFlagShort(t *testing.T) { - noRRSetupTest("echo -i13 -- something here") - - if cmdEcho.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash()) - } - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("echo -i 13 something here") - - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("print -i99 one two") - - if strings.Join(tp, " ") != "one two" { - t.Errorf("flags didn't leave proper args remaining..%s given", tp) - } - if flagi3 != 99 { - t.Errorf("int flag didn't get correct value, had %d", flagi3) - } - if flagi1 != 123 { - t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2) - } -} - -func TestChildCommandFlags(t *testing.T) { - noRRSetupTest("echo times -j 99 one two") - - if strings.Join(tt, " ") != "one two" { - t.Errorf("flags didn't leave proper args remaining..%s given", tt) - } - - // Testing with flag that shouldn't be persistent - r := noRRSetupTest("echo times -j 99 -i77 one two") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - - if !strings.Contains(r.Error.Error(), "unknown shorthand") { - t.Errorf("Wrong error message displayed, \n %s", r.Error) - } - - if flagi2 != 99 { - t.Errorf("flag value should be 99, %d given", flagi2) - } - - if flagi1 != 123 { - t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1) - } - - // Testing with flag only existing on child - r = noRRSetupTest("echo -j 99 -i77 one two") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - if !strings.Contains(r.Error.Error(), "unknown shorthand flag") { - t.Errorf("Wrong error message displayed, \n %s", r.Error) - } - - // Testing with persistent flag overwritten by child - noRRSetupTest("echo times --strtwo=child one two") - - if flags2b != "child" { - t.Errorf("flag value should be child, %s given", flags2b) - } - - if flags2a != "two" { - t.Errorf("unset flag should have default value, expecting two, given %s", flags2a) - } - - // Testing flag with invalid input - r = noRRSetupTest("echo -i10E") - - if r.Error == nil { - t.Errorf("invalid input should generate error") - } - if !strings.Contains(r.Error.Error(), "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", r.Error) - } -} - -func TestTrailingCommandFlags(t *testing.T) { - x := fullSetupTest("echo two -x") - - if x.Error == nil { - t.Errorf("invalid flag should generate error") - } -} - -func TestInvalidSubcommandFlags(t *testing.T) { - cmd := initializeWithRootCmd() - cmd.AddCommand(cmdTimes) - - result := simpleTester(cmd, "times --inttwo=2 --badflag=bar") - // given that we are not checking here result.Error we check for - // stock usage message - checkResultContains(t, result, "cobra-test times [# times]") - if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") { - t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag") - } - -} - -func TestSubcommandExecuteC(t *testing.T) { - cmd := initializeWithRootCmd() - double := &Command{ - Use: "double message", - Run: func(c *Command, args []string) { - msg := strings.Join(args, " ") - c.Println(msg, msg) - }, - } - - echo := &Command{ - Use: "echo message", - Run: func(c *Command, args []string) { - msg := strings.Join(args, " ") - c.Println(msg, msg) - }, - } - - cmd.AddCommand(double, echo) - - result := simpleTesterC(cmd, "double hello world") - checkResultContains(t, result, "hello world hello world") - - if result.Command.Name() != "double" { - t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name()) - } - - result = simpleTesterC(cmd, "echo msg to be echoed") - checkResultContains(t, result, "msg to be echoed") - - if result.Command.Name() != "echo" { - t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name()) - } -} - -func TestSubcommandArgEvaluation(t *testing.T) { - cmd := initializeWithRootCmd() - - first := &Command{ - Use: "first", - Run: func(cmd *Command, args []string) { - }, - } - cmd.AddCommand(first) - - second := &Command{ - Use: "second", - Run: func(cmd *Command, args []string) { - fmt.Fprintf(cmd.Out(), "%v", args) - }, - } - first.AddCommand(second) - - result := simpleTester(cmd, "first second first third") - - expectedOutput := fmt.Sprintf("%v", []string{"first third"}) - if result.Output != expectedOutput { - t.Errorf("exptected %v, got %v", expectedOutput, result.Output) - } -} - -func TestPersistentFlags(t *testing.T) { - fullSetupTest("echo -s something -p more here") - - // persistentFlag should act like normal flag on its own command - if strings.Join(te, " ") != "more here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flags1 != "something" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } - - // persistentFlag should act like normal flag on its own command - fullSetupTest("echo times -s again -c -p test here") - - if strings.Join(tt, " ") != "test here" { - t.Errorf("flags didn't leave proper args remaining..%s given", tt) - } - - if flags1 != "again" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - - if !flagb2 { - t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } -} - -func TestHelpCommand(t *testing.T) { - x := fullSetupTest("help") - checkResultContains(t, x, cmdRootWithRun.Long) - - x = fullSetupTest("help echo") - checkResultContains(t, x, cmdEcho.Long) - - x = fullSetupTest("help echo times") - checkResultContains(t, x, cmdTimes.Long) -} - -func TestChildCommandHelp(t *testing.T) { - c := noRRSetupTest("print --help") - checkResultContains(t, c, strtwoParentHelp) - r := noRRSetupTest("echo times --help") - checkResultContains(t, r, strtwoChildHelp) -} - -func TestNonRunChildHelp(t *testing.T) { - x := noRRSetupTest("subnorun") - checkResultContains(t, x, cmdSubNoRun.Long) -} - -func TestRunnableRootCommand(t *testing.T) { - x := fullSetupTest("") - - if rootcalled != true { - t.Errorf("Root Function was not called\n out:%v", x.Error) - } -} - -func TestVisitParents(t *testing.T) { - c := &Command{Use: "app"} - sub := &Command{Use: "sub"} - dsub := &Command{Use: "dsub"} - sub.AddCommand(dsub) - c.AddCommand(sub) - total := 0 - add := func(x *Command) { - total++ - } - sub.VisitParents(add) - if total != 1 { - t.Errorf("Should have visited 1 parent but visited %d", total) - } - - total = 0 - dsub.VisitParents(add) - if total != 2 { - t.Errorf("Should have visited 2 parent but visited %d", total) - } - - total = 0 - c.VisitParents(add) - if total != 0 { - t.Errorf("Should have not visited any parent but visited %d", total) - } -} - -func TestRunnableRootCommandNilInput(t *testing.T) { - empty_arg := make([]string, 0) - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(empty_arg) - - err := c.Execute() - if err != nil { - t.Errorf("Execute() failed with %v", err) - } - - if rootcalled != true { - t.Errorf("Root Function was not called") - } -} - -func TestRunnableRootCommandEmptyInput(t *testing.T) { - args := make([]string, 3) - args[0] = "" - args[1] = "--introot=12" - args[2] = "" - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if rootcalled != true { - t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf) - } -} - -func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) { - fullSetupTest("echo invalid-sub") - - if te[0] != "invalid-sub" { - t.Errorf("Subcommand didn't work...") - } -} - -func TestRootFlags(t *testing.T) { - fullSetupTest("-i 17 -b") - - if flagbr != true { - t.Errorf("flag value should be true, %v given", flagbr) - } - - if flagir != 17 { - t.Errorf("flag value should be 17, %d given", flagir) - } -} - -func TestRootHelp(t *testing.T) { - x := fullSetupTest("--help") - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - if strings.Contains(x.Output, cmdEcho.Use) { - t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output) - } - - x = fullSetupTest("echo --help") - - if strings.Contains(x.Output, cmdTimes.Use) { - t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output) - } - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - -} - -func TestFlagAccess(t *testing.T) { - initialize() - - local := cmdTimes.LocalFlags() - inherited := cmdTimes.InheritedFlags() - - for _, f := range []string{"inttwo", "strtwo", "booltwo"} { - if local.Lookup(f) == nil { - t.Errorf("LocalFlags expected to contain %s, Got: nil", f) - } - } - if inherited.Lookup("strone") == nil { - t.Errorf("InheritedFlags expected to contain strone, Got: nil") - } - if inherited.Lookup("strtwo") != nil { - t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo") - - } -} - -func TestNoNRunnableRootCommandNilInput(t *testing.T) { - args := make([]string, 0) - c := initialize() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if !strings.Contains(buf.String(), cmdRootNoRun.Long) { - t.Errorf("Expected to get help output, Got: \n %s", buf) - } -} - -func TestRootNoCommandHelp(t *testing.T) { - x := rootOnlySetupTest("--help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - x = rootOnlySetupTest("echo --help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } -} - -func TestRootUnknownCommand(t *testing.T) { - r := noRRSetupTest("bogus") - s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" - - if r.Output != s { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) - } - - r = noRRSetupTest("--strtwo=a bogus") - if r.Output != s { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) - } -} - -func TestRootUnknownCommandSilenced(t *testing.T) { - r := noRRSetupTestSilenced("bogus") - s := "Run 'cobra-test --help' for usage.\n" - - if r.Output != "" { - t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", s, r.Output) - } - - r = noRRSetupTestSilenced("--strtwo=a bogus") - if r.Output != "" { - t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", s, r.Output) - } -} - -func TestRootSuggestions(t *testing.T) { - outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n" - outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" - - cmd := initializeWithRootCmd() - cmd.AddCommand(cmdTimes) - - tests := map[string]string{ - "time": "times", - "tiems": "times", - "tims": "times", - "timeS": "times", - "rimes": "times", - "ti": "times", - "t": "times", - "timely": "times", - "ri": "", - "timezone": "", - "foo": "", - "counts": "times", - } - - for typo, suggestion := range tests { - for _, suggestionsDisabled := range []bool{false, true} { - cmd.DisableSuggestions = suggestionsDisabled - result := simpleTester(cmd, typo) - expected := "" - if len(suggestion) == 0 || suggestionsDisabled { - expected = fmt.Sprintf(outputWithoutSuggestions, typo) - } else { - expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion) - } - if result.Output != expected { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output) - } - } - } -} - -func TestFlagsBeforeCommand(t *testing.T) { - // short without space - x := fullSetupTest("-i10 echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - // short (int) with equals - // It appears that pflags doesn't support this... - // Commenting out until support can be added - - //x = noRRSetupTest("echo -i=10") - //if x.Error != nil { - //t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error) - //} - - // long with equals - x = noRRSetupTest("--intone=123 echo one two") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error) - } - - // With parsing error properly reported - x = fullSetupTest("-i10E echo") - if !strings.Contains(x.Error.Error(), "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", x.Error) - } - - //With quotes - x = fullSetupTest("-s=\"walking\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With quotes and space - x = fullSetupTest("-s=\"walking fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With inner quote - x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With quotes and space - x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - -} - -func TestRemoveCommand(t *testing.T) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - x := fullTester(c, "version") - if x.Error == nil { - t.Errorf("Removed command should not have been called\n") - return - } -} - -func TestCommandWithoutSubcommands(t *testing.T) { - c := initializeWithRootCmd() - - x := simpleTester(c, "") - if x.Error != nil { - t.Errorf("Calling command without subcommands should not have error: %v", x.Error) - return - } -} - -func TestCommandWithoutSubcommandsWithArg(t *testing.T) { - c := initializeWithRootCmd() - expectedArgs := []string{"arg"} - - x := simpleTester(c, "arg") - if x.Error != nil { - t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error) - return - } - if !reflect.DeepEqual(expectedArgs, tr) { - t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr) - return - } -} - -func TestReplaceCommandWithRemove(t *testing.T) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - c.AddCommand(cmdVersion2) - x := fullTester(c, "version") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - return - } - if versionUsed == 1 { - t.Errorf("Removed command shouldn't be called\n") - } - if versionUsed != 2 { - t.Errorf("Replacing command should have been called but didn't\n") - } -} - -func TestDeprecatedSub(t *testing.T) { - c := fullSetupTest("deprecated") - - checkResultContains(t, c, cmdDeprecated.Deprecated) -} - -func TestPreRun(t *testing.T) { - noRRSetupTest("echo one two") - if echoPre == nil || echoPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if rootPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("echo times one two") - if timesPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if echoPre != nil || echoPersPre != nil || rootPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("print one two") - if rootPersPre == nil { - t.Error("Parent PersistentPreRun not called but should not have been") - } - if echoPre != nil || echoPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } -} - -// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last -func TestPeristentPreRunPropagation(t *testing.T) { - rootCmd := initialize() - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - - rootCmd.SetArgs(strings.Split("print echosub lala", " ")) - rootCmd.Execute() - - if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" { - t.Error("RootCmd PersistentPreRun not called but should have been") - } -} - -func TestGlobalNormFuncPropagation(t *testing.T) { - normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(name) - } - - rootCmd := initialize() - rootCmd.SetGlobalNormalizationFunc(normFunc) - if reflect.ValueOf(normFunc) != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()) { - t.Error("rootCmd seems to have a wrong normalization function") - } - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil { - t.Error("cmdPrint and cmdEchoSub should had no normalization functions") - } - - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() || - reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() { - t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd") - } -} - -func TestFlagOnPflagCommandLine(t *testing.T) { - flagName := "flagOnCommandLine" - pflag.CommandLine.String(flagName, "", "about my flag") - r := fullSetupTest("--help") - - checkResultContains(t, r, flagName) -} - -func TestAddTemplateFunctions(t *testing.T) { - AddTemplateFunc("t", func() bool { return true }) - AddTemplateFuncs(template.FuncMap{ - "f": func() bool { return false }, - "h": func() string { return "Hello," }, - "w": func() string { return "world." }}) - - const usage = "Hello, world." - - c := &Command{} - c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`) - - if us := c.UsageString(); us != usage { - t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us) - } -} - -func TestUsageIsNotPrintedTwice(t *testing.T) { - var cmd = &Command{Use: "root"} - var sub = &Command{Use: "sub"} - cmd.AddCommand(sub) - - r := simpleTester(cmd, "") - if strings.Count(r.Output, "Usage:") != 1 { - t.Error("Usage output is not printed exactly once") - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/command_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/command_test.go deleted file mode 100644 index 43ed7a34f..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/command_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package cobra - -import ( - "reflect" - "testing" -) - -// test to ensure hidden commands run as intended -func TestHiddenCommandExecutes(t *testing.T) { - - // ensure that outs does not already equal what the command will be setting it - // to, if it did this test would not actually be testing anything... - if outs == "hidden" { - t.Errorf("outs should NOT EQUAL hidden") - } - - cmdHidden.Execute() - - // upon running the command, the value of outs should now be 'hidden' - if outs != "hidden" { - t.Errorf("Hidden command failed to run!") - } -} - -// test to ensure hidden commands do not show up in usage/help text -func TestHiddenCommandIsHidden(t *testing.T) { - if cmdHidden.IsAvailableCommand() { - t.Errorf("Hidden command found!") - } -} - -func TestStripFlags(t *testing.T) { - tests := []struct { - input []string - output []string - }{ - { - []string{"foo", "bar"}, - []string{"foo", "bar"}, - }, - { - []string{"foo", "--bar", "-b"}, - []string{"foo"}, - }, - { - []string{"-b", "foo", "--bar", "bar"}, - []string{}, - }, - { - []string{"-i10", "echo"}, - []string{"echo"}, - }, - { - []string{"-i=10", "echo"}, - []string{"echo"}, - }, - { - []string{"--int=100", "echo"}, - []string{"echo"}, - }, - { - []string{"-ib", "echo", "-bfoo", "baz"}, - []string{"echo", "baz"}, - }, - { - []string{"-i=baz", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"--int=baz", "-bbar", "-i", "foo", "blah"}, - []string{"blah"}, - }, - { - []string{"--cat", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"-c", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"--persist", "bar"}, - []string{"bar"}, - }, - { - []string{"-p", "bar"}, - []string{"bar"}, - }, - } - - cmdPrint := &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, - } - - var flagi int - var flagstr string - var flagbool bool - cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one") - cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int") - cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string") - cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool") - - for _, test := range tests { - output := stripFlags(test.input, cmdPrint) - if !reflect.DeepEqual(test.output, output) { - t.Errorf("expected: %v, got: %v", test.output, output) - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go deleted file mode 100644 index 10da9850e..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package cobra_test - -import ( - "bytes" - "fmt" - - "github.com/spf13/cobra" -) - -func ExampleCommand_GenManTree() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - header := &cobra.GenManHeader{ - Title: "MINE", - Section: "3", - } - cmd.GenManTree(header, "/tmp") -} - -func ExampleCommand_GenMan() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - header := &cobra.GenManHeader{ - Title: "MINE", - Section: "3", - } - out := new(bytes.Buffer) - cmd.GenMan(header, out) - fmt.Print(out.String()) -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go deleted file mode 100644 index ab4030c33..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func translate(in string) string { - return strings.Replace(in, "-", "\\-", -1) -} - -func TestGenManDoc(t *testing.T) { - c := initializeWithRootCmd() - // Need two commands to run the command alphabetical sort - cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) - c.AddCommand(cmdPrint, cmdEcho) - cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) - - out := new(bytes.Buffer) - - header := &GenManHeader{ - Title: "Project", - Section: "2", - } - // We generate on a subcommand so we have both subcommands and parents - cmdEcho.GenMan(header, out) - found := out.String() - - // Make sure parent has - in CommandPath() in SEE ALSO: - parentPath := cmdEcho.Parent().CommandPath() - dashParentPath := strings.Replace(parentPath, " ", "-", -1) - expected := translate(dashParentPath) - expected = expected + "(" + header.Section + ")" - checkStringContains(t, found, expected) - - // Our description - expected = translate(cmdEcho.Name()) - checkStringContains(t, found, expected) - - // Better have our example - expected = translate(cmdEcho.Name()) - checkStringContains(t, found, expected) - - // A local flag - expected = "boolone" - checkStringContains(t, found, expected) - - // persistent flag on parent - expected = "rootflag" - checkStringContains(t, found, expected) - - // We better output info about our parent - expected = translate(cmdRootWithRun.Name()) - checkStringContains(t, found, expected) - - // And about subcommands - expected = translate(cmdEchoSub.Name()) - checkStringContains(t, found, expected) - - unexpected := translate(cmdDeprecated.Name()) - checkStringOmits(t, found, unexpected) - - // auto generated - expected = translate("Auto generated") - checkStringContains(t, found, expected) -} - -func TestGenManNoGenTag(t *testing.T) { - - c := initializeWithRootCmd() - // Need two commands to run the command alphabetical sort - cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) - c.AddCommand(cmdPrint, cmdEcho) - cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) - cmdEcho.DisableAutoGenTag = true - out := new(bytes.Buffer) - - header := &GenManHeader{ - Title: "Project", - Section: "2", - } - // We generate on a subcommand so we have both subcommands and parents - cmdEcho.GenMan(header, out) - found := out.String() - - unexpected := translate("#HISTORY") - checkStringOmits(t, found, unexpected) -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go deleted file mode 100644 index 82f5452ce..000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func TestGenMdDoc(t *testing.T) { - c := initializeWithRootCmd() - // Need two commands to run the command alphabetical sort - cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) - c.AddCommand(cmdPrint, cmdEcho) - cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) - - out := new(bytes.Buffer) - - // We generate on s subcommand so we have both subcommands and parents - GenMarkdown(cmdEcho, out) - found := out.String() - - // Our description - expected := cmdEcho.Long - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // Better have our example - expected = cmdEcho.Example - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // A local flag - expected = "boolone" - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // persistent flag on parent - expected = "rootflag" - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // We better output info about our parent - expected = cmdRootWithRun.Short - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // And about subcommands - expected = cmdEchoSub.Short - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - unexpected := cmdDeprecated.Short - if strings.Contains(found, unexpected) { - t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected) - } -} - -func TestGenMdNoTag(t *testing.T) { - c := initializeWithRootCmd() - // Need two commands to run the command alphabetical sort - cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) - c.AddCommand(cmdPrint, cmdEcho) - c.DisableAutoGenTag = true - cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) - out := new(bytes.Buffer) - - GenMarkdown(c, out) - found := out.String() - - unexpected := "Auto generated" - checkStringOmits(t, found, unexpected) - -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go deleted file mode 100644 index afd25ae2f..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go +++ /dev/null @@ -1,180 +0,0 @@ -// 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 pflag - -import ( - "bytes" - "fmt" - "strconv" - "testing" -) - -// This value can be a boolean ("true", "false") or "maybe" -type triStateValue int - -const ( - triStateFalse triStateValue = 0 - triStateTrue triStateValue = 1 - triStateMaybe triStateValue = 2 -) - -const strTriStateMaybe = "maybe" - -func (v *triStateValue) IsBoolFlag() bool { - return true -} - -func (v *triStateValue) Get() interface{} { - return triStateValue(*v) -} - -func (v *triStateValue) Set(s string) error { - if s == strTriStateMaybe { - *v = triStateMaybe - return nil - } - boolVal, err := strconv.ParseBool(s) - if boolVal { - *v = triStateTrue - } else { - *v = triStateFalse - } - return err -} - -func (v *triStateValue) String() string { - if *v == triStateMaybe { - return strTriStateMaybe - } - return fmt.Sprintf("%v", bool(*v == triStateTrue)) -} - -// The type of the flag as required by the pflag.Value interface -func (v *triStateValue) Type() string { - return "version" -} - -func setUpFlagSet(tristate *triStateValue) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - *tristate = triStateFalse - flag := f.VarPF(tristate, "tristate", "t", "tristate value (true, maybe or false)") - flag.NoOptDefVal = "true" - return f -} - -func TestExplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=true"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestImplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlag(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"-t"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlagExtraArgument(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - // The"maybe"turns into an arg, since short boolean options will only do true/false - err := f.Parse([]string{"-t", "maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } - args := f.Args() - if len(args) != 1 || args[0] != "maybe" { - t.Fatal("expected an extra 'maybe' argument to stick around") - } -} - -func TestExplicitMaybe(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateMaybe { - t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead") - } -} - -func TestExplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=false"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestImplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestInvalidValue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - var buf bytes.Buffer - f.SetOutput(&buf) - err := f.Parse([]string{"--tristate=invalid"}) - if err == nil { - t.Fatal("expected an error but did not get any, tristate has value", tristate) - } -} - -func TestBoolP(t *testing.T) { - b := BoolP("bool", "b", false, "bool value in CommandLine") - c := BoolP("c", "c", false, "other bool value") - args := []string{"--bool"} - if err := CommandLine.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if *b != true { - t.Errorf("expected b=true got b=%s", b) - } - if *c != false { - t.Errorf("expect c=false got c=%s", c) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/count_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/count_test.go deleted file mode 100644 index 716765cba..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/count_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package pflag - -import ( - "fmt" - "os" - "testing" -) - -var _ = fmt.Printf - -func setUpCount(c *int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.CountVarP(c, "verbose", "v", "a counter") - return f -} - -func TestCount(t *testing.T) { - testCases := []struct { - input []string - success bool - expected int - }{ - {[]string{"-vvv"}, true, 3}, - {[]string{"-v", "-v", "-v"}, true, 3}, - {[]string{"-v", "--verbose", "-v"}, true, 3}, - {[]string{"-v=3", "-v"}, true, 4}, - {[]string{"-v=a"}, false, 0}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var count int - f := setUpCount(&count) - - tc := &testCases[i] - - err := f.Parse(tc.input) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure, got success") - continue - } else if tc.success { - c, err := f.GetCount("verbose") - if err != nil { - t.Errorf("Got error trying to fetch the counter flag") - } - if c != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, c) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go deleted file mode 100644 index 9be7a49f2..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go +++ /dev/null @@ -1,77 +0,0 @@ -// 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. - -// These examples demonstrate more intricate uses of the flag package. -package pflag_test - -import ( - "errors" - "fmt" - "strings" - "time" - - flag "github.com/spf13/pflag" -) - -// Example 1: A single string flag called "species" with default value "gopher". -var species = flag.String("species", "gopher", "the species we are studying") - -// Example 2: A flag with a shorthand letter. -var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher") - -// Example 3: A user-defined flag type, a slice of durations. -type interval []time.Duration - -// String is the method to format the flag's value, part of the flag.Value interface. -// The String method's output will be used in diagnostics. -func (i *interval) String() string { - return fmt.Sprint(*i) -} - -func (i *interval) Type() string { - return "interval" -} - -// Set is the method to set the flag value, part of the flag.Value interface. -// Set's argument is a string to be parsed to set the flag. -// It's a comma-separated list, so we split it. -func (i *interval) Set(value string) error { - // If we wanted to allow the flag to be set multiple times, - // accumulating values, we would delete this if statement. - // That would permit usages such as - // -deltaT 10s -deltaT 15s - // and other combinations. - if len(*i) > 0 { - return errors.New("interval flag already set") - } - for _, dt := range strings.Split(value, ",") { - duration, err := time.ParseDuration(dt) - if err != nil { - return err - } - *i = append(*i, duration) - } - return nil -} - -// Define a flag to accumulate durations. Because it has a special type, -// we need to use the Var function and therefore create the flag during -// init. - -var intervalFlag interval - -func init() { - // Tie the command-line flag to the intervalFlag variable and - // set a usage message. - flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") -} - -func Example() { - // All the interesting pieces are with the variables declared above, but - // to enable the flag package to see the flags defined there, one must - // execute, typically at the start of main (not init!): - // flag.Parse() - // We don't run it here because this is not a main function and - // the testing suite has already parsed the flags. -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/export_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/export_test.go deleted file mode 100644 index 9318fee00..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/export_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 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 pflag - -import ( - "io/ioutil" - "os" -) - -// Additional routines compiled into the package only during testing. - -// ResetForTesting clears all flag state and sets the usage function as directed. -// After calling ResetForTesting, parse errors in flag handling will not -// exit the program. -func ResetForTesting(usage func()) { - CommandLine = &FlagSet{ - name: os.Args[0], - errorHandling: ContinueOnError, - output: ioutil.Discard, - } - Usage = usage -} - -// GetCommandLine returns the default FlagSet. -func GetCommandLine() *FlagSet { - return CommandLine -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go deleted file mode 100644 index e17b2aad8..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go +++ /dev/null @@ -1,874 +0,0 @@ -// 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 pflag - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "reflect" - "sort" - "strings" - "testing" - "time" -) - -var ( - testBool = Bool("test_bool", false, "bool value") - testInt = Int("test_int", 0, "int value") - testInt64 = Int64("test_int64", 0, "int64 value") - testUint = Uint("test_uint", 0, "uint value") - testUint64 = Uint64("test_uint64", 0, "uint64 value") - testString = String("test_string", "0", "string value") - testFloat = Float64("test_float64", 0, "float64 value") - testDuration = Duration("test_duration", 0, "time.Duration value") - testOptionalInt = Int("test_optional_int", 0, "optional int value") - normalizeFlagNameInvocations = 0 -) - -func boolString(s string) string { - if s == "0" { - return "false" - } - return "true" -} - -func TestEverything(t *testing.T) { - m := make(map[string]*Flag) - desired := "0" - visitor := func(f *Flag) { - if len(f.Name) > 5 && f.Name[0:5] == "test_" { - m[f.Name] = f - ok := false - switch { - case f.Value.String() == desired: - ok = true - case f.Name == "test_bool" && f.Value.String() == boolString(desired): - ok = true - case f.Name == "test_duration" && f.Value.String() == desired+"s": - ok = true - } - if !ok { - t.Error("Visit: bad value", f.Value.String(), "for", f.Name) - } - } - } - VisitAll(visitor) - if len(m) != 9 { - t.Error("VisitAll misses some flags") - for k, v := range m { - t.Log(k, *v) - } - } - m = make(map[string]*Flag) - Visit(visitor) - if len(m) != 0 { - t.Errorf("Visit sees unset flags") - for k, v := range m { - t.Log(k, *v) - } - } - // Now set all flags - Set("test_bool", "true") - Set("test_int", "1") - Set("test_int64", "1") - Set("test_uint", "1") - Set("test_uint64", "1") - Set("test_string", "1") - Set("test_float64", "1") - Set("test_duration", "1s") - Set("test_optional_int", "1") - desired = "1" - Visit(visitor) - if len(m) != 9 { - t.Error("Visit fails after set") - for k, v := range m { - t.Log(k, *v) - } - } - // Now test they're visited in sort order. - var flagNames []string - Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) }) - if !sort.StringsAreSorted(flagNames) { - t.Errorf("flag names not sorted: %v", flagNames) - } -} - -func TestUsage(t *testing.T) { - called := false - ResetForTesting(func() { called = true }) - if GetCommandLine().Parse([]string{"--x"}) == nil { - t.Error("parse did not fail for unknown flag") - } - if !called { - t.Error("did not call Usage for unknown flag") - } -} - -func TestAddFlagSet(t *testing.T) { - oldSet := NewFlagSet("old", ContinueOnError) - newSet := NewFlagSet("new", ContinueOnError) - - oldSet.String("flag1", "flag1", "flag1") - oldSet.String("flag2", "flag2", "flag2") - - newSet.String("flag2", "flag2", "flag2") - newSet.String("flag3", "flag3", "flag3") - - oldSet.AddFlagSet(newSet) - - if len(oldSet.formal) != 3 { - t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet) - } -} - -func TestAnnotation(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - - if err := f.SetAnnotation("missing-flag", "key", nil); err == nil { - t.Errorf("Expected error setting annotation on non-existent flag") - } - - f.StringP("stringa", "a", "", "string value") - if err := f.SetAnnotation("stringa", "key", nil); err != nil { - t.Errorf("Unexpected error setting new nil annotation: %v", err) - } - if annotation := f.Lookup("stringa").Annotations["key"]; annotation != nil { - t.Errorf("Unexpected annotation: %v", annotation) - } - - f.StringP("stringb", "b", "", "string2 value") - if err := f.SetAnnotation("stringb", "key", []string{"value1"}); err != nil { - t.Errorf("Unexpected error setting new annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value1"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } - - if err := f.SetAnnotation("stringb", "key", []string{"value2"}); err != nil { - t.Errorf("Unexpected error updating annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value2"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } -} - -func testParse(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolFlag := f.Bool("bool", false, "bool value") - bool2Flag := f.Bool("bool2", false, "bool2 value") - bool3Flag := f.Bool("bool3", false, "bool3 value") - intFlag := f.Int("int", 0, "int value") - int8Flag := f.Int8("int8", 0, "int value") - int32Flag := f.Int32("int32", 0, "int value") - int64Flag := f.Int64("int64", 0, "int64 value") - uintFlag := f.Uint("uint", 0, "uint value") - uint8Flag := f.Uint8("uint8", 0, "uint value") - uint16Flag := f.Uint16("uint16", 0, "uint value") - uint32Flag := f.Uint32("uint32", 0, "uint value") - uint64Flag := f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - float32Flag := f.Float32("float32", 0, "float32 value") - float64Flag := f.Float64("float64", 0, "float64 value") - ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value") - maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value") - durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") - optionalIntNoValueFlag := f.Int("optional-int-no-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - optionalIntWithValueFlag := f.Int("optional-int-with-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - extra := "one-extra-argument" - args := []string{ - "--bool", - "--bool2=true", - "--bool3=false", - "--int=22", - "--int8=-8", - "--int32=-32", - "--int64=0x23", - "--uint", "24", - "--uint8=8", - "--uint16=16", - "--uint32=32", - "--uint64=25", - "--string=hello", - "--float32=-172e12", - "--float64=2718e28", - "--ip=10.11.12.13", - "--mask=255.255.255.0", - "--duration=2m", - "--optional-int-no-value", - "--optional-int-with-value=42", - extra, - } - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if v, err := f.GetBool("bool"); err != nil || v != *boolFlag { - t.Error("GetBool does not work.") - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if *bool3Flag != false { - t.Error("bool3 flag should be false, is ", *bool2Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if v, err := f.GetInt("int"); err != nil || v != *intFlag { - t.Error("GetInt does not work.") - } - if *int8Flag != -8 { - t.Error("int8 flag should be 0x23, is ", *int8Flag) - } - if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag { - t.Error("GetInt8 does not work.") - } - if *int32Flag != -32 { - t.Error("int32 flag should be 0x23, is ", *int32Flag) - } - if v, err := f.GetInt32("int32"); err != nil || v != *int32Flag { - t.Error("GetInt32 does not work.") - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if v, err := f.GetInt64("int64"); err != nil || v != *int64Flag { - t.Error("GetInt64 does not work.") - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if v, err := f.GetUint("uint"); err != nil || v != *uintFlag { - t.Error("GetUint does not work.") - } - if *uint8Flag != 8 { - t.Error("uint8 flag should be 8, is ", *uint8Flag) - } - if v, err := f.GetUint8("uint8"); err != nil || v != *uint8Flag { - t.Error("GetUint8 does not work.") - } - if *uint16Flag != 16 { - t.Error("uint16 flag should be 16, is ", *uint16Flag) - } - if v, err := f.GetUint16("uint16"); err != nil || v != *uint16Flag { - t.Error("GetUint16 does not work.") - } - if *uint32Flag != 32 { - t.Error("uint32 flag should be 32, is ", *uint32Flag) - } - if v, err := f.GetUint32("uint32"); err != nil || v != *uint32Flag { - t.Error("GetUint32 does not work.") - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if v, err := f.GetUint64("uint64"); err != nil || v != *uint64Flag { - t.Error("GetUint64 does not work.") - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if v, err := f.GetString("string"); err != nil || v != *stringFlag { - t.Error("GetString does not work.") - } - if *float32Flag != -172e12 { - t.Error("float32 flag should be -172e12, is ", *float32Flag) - } - if v, err := f.GetFloat32("float32"); err != nil || v != *float32Flag { - t.Errorf("GetFloat32 returned %v but float32Flag was %v", v, *float32Flag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if v, err := f.GetFloat64("float64"); err != nil || v != *float64Flag { - t.Errorf("GetFloat64 returned %v but float64Flag was %v", v, *float64Flag) - } - if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) { - t.Error("ip flag should be 10.11.12.13, is ", *ipFlag) - } - if v, err := f.GetIP("ip"); err != nil || !v.Equal(*ipFlag) { - t.Errorf("GetIP returned %v but ipFlag was %v", v, *ipFlag) - } - if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() { - t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String()) - } - if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() { - t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } - if v, err := f.GetDuration("duration"); err != nil || v != *durationFlag { - t.Error("GetDuration does not work.") - } - if _, err := f.GetInt("duration"); err == nil { - t.Error("GetInt parsed a time.Duration?!?!") - } - if *optionalIntNoValueFlag != 9 { - t.Error("optional int flag should be the default value, is ", *optionalIntNoValueFlag) - } - if *optionalIntWithValueFlag != 42 { - t.Error("optional int flag should be 42, is ", *optionalIntWithValueFlag) - } - if len(f.Args()) != 1 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } -} - -func TestShorthand(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolaFlag := f.BoolP("boola", "a", false, "bool value") - boolbFlag := f.BoolP("boolb", "b", false, "bool2 value") - boolcFlag := f.BoolP("boolc", "c", false, "bool3 value") - booldFlag := f.BoolP("boold", "d", false, "bool4 value") - stringaFlag := f.StringP("stringa", "s", "0", "string value") - stringzFlag := f.StringP("stringz", "z", "0", "string value") - extra := "interspersed-argument" - notaflag := "--i-look-like-a-flag" - args := []string{ - "-ab", - extra, - "-cs", - "hello", - "-z=something", - "-d=true", - "--", - notaflag, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolaFlag != true { - t.Error("boola flag should be true, is ", *boolaFlag) - } - if *boolbFlag != true { - t.Error("boolb flag should be true, is ", *boolbFlag) - } - if *boolcFlag != true { - t.Error("boolc flag should be true, is ", *boolcFlag) - } - if *booldFlag != true { - t.Error("boold flag should be true, is ", *booldFlag) - } - if *stringaFlag != "hello" { - t.Error("stringa flag should be `hello`, is ", *stringaFlag) - } - if *stringzFlag != "something" { - t.Error("stringz flag should be `something`, is ", *stringzFlag) - } - if len(f.Args()) != 2 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } else if f.Args()[1] != notaflag { - t.Errorf("expected argument %q got %q", notaflag, f.Args()[1]) - } - if f.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1) - } -} - -func TestParse(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParse(GetCommandLine(), t) -} - -func TestFlagSetParse(t *testing.T) { - testParse(NewFlagSet("test", ContinueOnError), t) -} - -func TestChangedHelper(t *testing.T) { - f := NewFlagSet("changedtest", ContinueOnError) - _ = f.Bool("changed", false, "changed bool") - _ = f.Bool("settrue", true, "true to true") - _ = f.Bool("setfalse", false, "false to false") - _ = f.Bool("unchanged", false, "unchanged bool") - - args := []string{"--changed", "--settrue", "--setfalse=false"} - if err := f.Parse(args); err != nil { - t.Error("f.Parse() = false after Parse") - } - if !f.Changed("changed") { - t.Errorf("--changed wasn't changed!") - } - if !f.Changed("settrue") { - t.Errorf("--settrue wasn't changed!") - } - if !f.Changed("setfalse") { - t.Errorf("--setfalse wasn't changed!") - } - if f.Changed("unchanged") { - t.Errorf("--unchanged was changed!") - } - if f.Changed("invalid") { - t.Errorf("--invalid was changed!") - } - if f.ArgsLenAtDash() != -1 { - t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash()) - } -} - -func replaceSeparators(name string, from []string, to string) string { - result := name - for _, sep := range from { - result = strings.Replace(result, sep, to, -1) - } - // Type convert to indicate normalization has been done. - return result -} - -func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - name = replaceSeparators(name, seps, ".") - normalizeFlagNameInvocations++ - - return NormalizedName(name) -} - -func testWordSepNormalizedNames(args []string, t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - withDashFlag := f.Bool("with-dash-flag", false, "bool value") - // Set this after some flags have been added and before others. - f.SetNormalizeFunc(wordSepNormalizeFunc) - withUnderFlag := f.Bool("with_under_flag", false, "bool value") - withBothFlag := f.Bool("with-both_flag", false, "bool value") - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *withDashFlag != true { - t.Error("withDashFlag flag should be true, is ", *withDashFlag) - } - if *withUnderFlag != true { - t.Error("withUnderFlag flag should be true, is ", *withUnderFlag) - } - if *withBothFlag != true { - t.Error("withBothFlag flag should be true, is ", *withBothFlag) - } -} - -func TestWordSepNormalizedNames(t *testing.T) { - args := []string{ - "--with-dash-flag", - "--with-under-flag", - "--with-both-flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with_dash_flag", - "--with_under_flag", - "--with_both_flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with-dash_flag", - "--with-under_flag", - "--with-both_flag", - } - testWordSepNormalizedNames(args, t) -} - -func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - - oldName := replaceSeparators("old-valid_flag", seps, ".") - newName := replaceSeparators("valid-flag", seps, ".") - - name = replaceSeparators(name, seps, ".") - switch name { - case oldName: - name = newName - break - } - - return NormalizedName(name) -} - -func TestCustomNormalizedNames(t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - - validFlag := f.Bool("valid-flag", false, "bool value") - f.SetNormalizeFunc(aliasAndWordSepFlagNames) - someOtherFlag := f.Bool("some-other-flag", false, "bool value") - - args := []string{"--old_valid_flag", "--some-other_flag"} - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - - if *validFlag != true { - t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag) - } - if *someOtherFlag != true { - t.Error("someOtherFlag should be true, is ", *someOtherFlag) - } -} - -// Every flag we add, the name (displayed also in usage) should normalized -func TestNormalizationFuncShouldChangeFlagName(t *testing.T) { - // Test normalization after addition - f := NewFlagSet("normalized", ContinueOnError) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid_flag" { - t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name) - } - - f.SetNormalizeFunc(wordSepNormalizeFunc) - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } - - // Test normalization before addition - f = NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } -} - -// Declare a user-defined flag type. -type flagVar []string - -func (f *flagVar) String() string { - return fmt.Sprint([]string(*f)) -} - -func (f *flagVar) Set(value string) error { - *f = append(*f, value) - return nil -} - -func (f *flagVar) Type() string { - return "flagVar" -} - -func TestUserDefined(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var v flagVar - flags.VarP(&v, "v", "v", "usage") - if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil { - t.Error(err) - } - if len(v) != 3 { - t.Fatal("expected 3 args; got ", len(v)) - } - expect := "[1 2 3]" - if v.String() != expect { - t.Errorf("expected value %q got %q", expect, v.String()) - } -} - -func TestSetOutput(t *testing.T) { - var flags FlagSet - var buf bytes.Buffer - flags.SetOutput(&buf) - flags.Init("test", ContinueOnError) - flags.Parse([]string{"--unknown"}) - if out := buf.String(); !strings.Contains(out, "--unknown") { - t.Logf("expected output mentioning unknown; got %q", out) - } -} - -// This tests that one can reset the flags. This still works but not well, and is -// superseded by FlagSet. -func TestChangingArgs(t *testing.T) { - ResetForTesting(func() { t.Fatal("bad parse") }) - oldArgs := os.Args - defer func() { os.Args = oldArgs }() - os.Args = []string{"cmd", "--before", "subcmd"} - before := Bool("before", false, "") - if err := GetCommandLine().Parse(os.Args[1:]); err != nil { - t.Fatal(err) - } - cmd := Arg(0) - os.Args = []string{"subcmd", "--after", "args"} - after := Bool("after", false, "") - Parse() - args := Args() - - if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { - t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) - } -} - -// Test that -help invokes the usage message and returns ErrHelp. -func TestHelp(t *testing.T) { - var helpCalled = false - fs := NewFlagSet("help test", ContinueOnError) - fs.Usage = func() { helpCalled = true } - var flag bool - fs.BoolVar(&flag, "flag", false, "regular flag") - // Regular flag invocation should work - err := fs.Parse([]string{"--flag=true"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - if !flag { - t.Error("flag was not set by --flag") - } - if helpCalled { - t.Error("help called for regular flag") - helpCalled = false // reset for next test - } - // Help flag should work as expected. - err = fs.Parse([]string{"--help"}) - if err == nil { - t.Fatal("error expected") - } - if err != ErrHelp { - t.Fatal("expected ErrHelp; got ", err) - } - if !helpCalled { - t.Fatal("help was not called") - } - // If we define a help flag, that should override. - var help bool - fs.BoolVar(&help, "help", false, "help flag") - helpCalled = false - err = fs.Parse([]string{"--help"}) - if err != nil { - t.Fatal("expected no error for defined --help; got ", err) - } - if helpCalled { - t.Fatal("help was called; should not have been for defined help flag") - } -} - -func TestNoInterspersed(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - f.SetInterspersed(false) - f.Bool("true", true, "always true") - f.Bool("false", false, "always false") - err := f.Parse([]string{"--true", "break", "--false"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - args := f.Args() - if len(args) != 2 || args[0] != "break" || args[1] != "--false" { - t.Fatal("expected interspersed options/non-options to fail") - } -} - -func TestTermination(t *testing.T) { - f := NewFlagSet("termination", ContinueOnError) - boolFlag := f.BoolP("bool", "l", false, "bool value") - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - arg1 := "ls" - arg2 := "-l" - args := []string{ - "--", - arg1, - arg2, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Fatal("expected no error; got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag { - t.Error("expected boolFlag=false, got true") - } - if len(f.Args()) != 2 { - t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args()) - } - if f.Args()[0] != arg1 { - t.Errorf("expected argument %q got %q", arg1, f.Args()[0]) - } - if f.Args()[1] != arg2 { - t.Errorf("expected argument %q got %q", arg2, f.Args()[1]) - } - if f.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash()) - } -} - -func TestDeprecatedFlagInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - f.MarkDeprecated("badflag", "use --good-flag instead") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "badflag") { - t.Errorf("found deprecated flag in usage!") - } -} - -func TestDeprecatedFlagShorthandInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name)) - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "-n,") { - t.Errorf("found deprecated flag shorthand in usage!") - } -} - -func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) { - oldStderr := os.Stderr - r, w, _ := os.Pipe() - os.Stderr = w - - err := f.Parse(args) - - outC := make(chan string) - // copy the output in a separate goroutine so printing can't block indefinitely - go func() { - var buf bytes.Buffer - io.Copy(&buf, r) - outC <- buf.String() - }() - - w.Close() - os.Stderr = oldStderr - out := <-outC - - return out, err -} - -func TestDeprecatedFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - usageMsg := "use --good-flag instead" - f.MarkDeprecated("badflag", usageMsg) - - args := []string{"--badflag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagShorthandUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - usageMsg := fmt.Sprintf("use --%s instead", name) - f.MarkShorthandDeprecated(name, usageMsg) - - args := []string{"-n"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagUsageNormalized(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("bad-double_flag", true, "always true") - f.SetNormalizeFunc(wordSepNormalizeFunc) - usageMsg := "use --good-flag instead" - f.MarkDeprecated("bad_double-flag", usageMsg) - - args := []string{"--bad_double_flag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -// Name normalization function should be called only once on flag addition -func TestMultipleNormalizeFlagNameInvocations(t *testing.T) { - normalizeFlagNameInvocations = 0 - - f := NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - f.Bool("with_under_flag", false, "bool value") - - if normalizeFlagNameInvocations != 1 { - t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations) - } -} - -// -func TestHiddenFlagInUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "secretFlag") { - t.Errorf("found hidden flag in usage!") - } -} - -// -func TestHiddenFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - args := []string{"--secretFlag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if strings.Contains(out, "shhh") { - t.Errorf("usage message printed when using a hidden flag!") - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/golangflag_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/golangflag_test.go deleted file mode 100644 index 77e2d7d80..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/golangflag_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// 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 pflag - -import ( - goflag "flag" - "testing" -) - -func TestGoflags(t *testing.T) { - goflag.String("stringFlag", "stringFlag", "stringFlag") - goflag.Bool("boolFlag", false, "boolFlag") - - f := NewFlagSet("test", ContinueOnError) - - f.AddGoFlagSet(goflag.CommandLine) - err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"}) - if err != nil { - t.Fatal("expected no error; get", err) - } - - getString, err := f.GetString("stringFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getString != "bob" { - t.Fatalf("expected getString=bob but got getString=%s", getString) - } - - getBool, err := f.GetBool("boolFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getBool != true { - t.Fatalf("expected getBool=true but got getBool=%v", getBool) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/int_slice_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/int_slice_test.go deleted file mode 100644 index 5f2eee66a..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/int_slice_test.go +++ /dev/null @@ -1,162 +0,0 @@ -// 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 pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpISFlagSet(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{}, "Command separated list!") - return f -} - -func setUpISFlagSetWithDefault(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{0, 1}, "Command separated list!") - return f -} - -func TestEmptyIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if len(getIS) != 0 { - t.Fatalf("got is %v with len=%d but expected length=0", getIS, len(getIS)) - } -} - -func TestIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - vals := []string{"1", "2", "4", "3"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d", i, vals[i], v) - } - } - getIS, err := f.GetIntSlice("is") - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d from GetIntSlice", i, vals[i], v) - } - } -} - -func TestISDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"0", "1"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISWithDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"1", "2"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISCalledTwice(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - in := []string{"1,2", "3"} - expected := []int{1, 2, 3} - argfmt := "--is=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - if expected[i] != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/ip_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/ip_test.go deleted file mode 100644 index 1fec50e42..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/ip_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIP(ip *net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address") - return f -} - -func TestIP(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0", true, "0.0.0.0"}, - {" 0.0.0.0 ", true, "0.0.0.0"}, - {"1.2.3.4", true, "1.2.3.4"}, - {"127.0.0.1", true, "127.0.0.1"}, - {"255.255.255.255", true, "255.255.255.255"}, - {"", false, ""}, - {"0", false, ""}, - {"localhost", false, ""}, - {"0.0.0", false, ""}, - {"0.0.0.", false, ""}, - {"0.0.0.0.", false, ""}, - {"0.0.0.256", false, ""}, - {"0 . 0 . 0 . 0", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IP - f := setUpIP(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIP("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/ipnet_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/ipnet_test.go deleted file mode 100644 index 335b6fa15..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/ipnet_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIPNet(ip *net.IPNet) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - _, def, _ := net.ParseCIDR("0.0.0.0/0") - f.IPNetVar(ip, "address", *def, "IP Address") - return f -} - -func TestIPNet(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0/0", true, "0.0.0.0/0"}, - {" 0.0.0.0/0 ", true, "0.0.0.0/0"}, - {"1.2.3.4/8", true, "1.0.0.0/8"}, - {"127.0.0.1/16", true, "127.0.0.0/16"}, - {"255.255.255.255/19", true, "255.255.224.0/19"}, - {"255.255.255.255/32", true, "255.255.255.255/32"}, - {"", false, ""}, - {"/0", false, ""}, - {"0", false, ""}, - {"0/0", false, ""}, - {"localhost/0", false, ""}, - {"0.0.0/4", false, ""}, - {"0.0.0./8", false, ""}, - {"0.0.0.0./12", false, ""}, - {"0.0.0.256/16", false, ""}, - {"0.0.0.0 /20", false, ""}, - {"0.0.0.0/ 24", false, ""}, - {"0 . 0 . 0 . 0 / 28", false, ""}, - {"0.0.0.0/33", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IPNet - f := setUpIPNet(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIPNet("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/string_slice_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/string_slice_test.go deleted file mode 100644 index c7fdc70b4..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/string_slice_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// 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 pflag - -import ( - "fmt" - "strings" - "testing" -) - -func setUpSSFlagSet(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{}, "Command separated list!") - return f -} - -func setUpSSFlagSetWithDefault(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{"default", "values"}, "Command separated list!") - return f -} - -func TestEmptySS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - if len(getSS) != 0 { - t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) - } -} - -func TestSS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"default", "values"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSWithDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSCalledTwice(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{"one,two", "three"} - expected := []string{"one", "two", "three"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSSWithComma(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{`"one,two"`, `"three"`} - expected := []string{"one,two", "three"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/verify/all.sh b/Godeps/_workspace/src/github.com/spf13/pflag/verify/all.sh deleted file mode 100644 index 739f89c0b..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/verify/all.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/bash - -set -o errexit -set -o nounset -set -o pipefail - -ROOT=$(dirname "${BASH_SOURCE}")/.. - -# Some useful colors. -if [[ -z "${color_start-}" ]]; then - declare -r color_start="\033[" - declare -r color_red="${color_start}0;31m" - declare -r color_yellow="${color_start}0;33m" - declare -r color_green="${color_start}0;32m" - declare -r color_norm="${color_start}0m" -fi - -SILENT=true - -function is-excluded { - for e in $EXCLUDE; do - if [[ $1 -ef ${BASH_SOURCE} ]]; then - return - fi - if [[ $1 -ef "$ROOT/hack/$e" ]]; then - return - fi - done - return 1 -} - -while getopts ":v" opt; do - case $opt in - v) - SILENT=false - ;; - \?) - echo "Invalid flag: -$OPTARG" >&2 - exit 1 - ;; - esac -done - -if $SILENT ; then - echo "Running in the silent mode, run with -v if you want to see script logs." -fi - -EXCLUDE="all.sh" - -ret=0 -for t in `ls $ROOT/verify/*.sh` -do - if is-excluded $t ; then - echo "Skipping $t" - continue - fi - if $SILENT ; then - echo -e "Verifying $t" - if bash "$t" &> /dev/null; then - echo -e "${color_green}SUCCESS${color_norm}" - else - echo -e "${color_red}FAILED${color_norm}" - ret=1 - fi - else - bash "$t" || ret=1 - fi -done -exit $ret diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/verify/gofmt.sh b/Godeps/_workspace/src/github.com/spf13/pflag/verify/gofmt.sh deleted file mode 100644 index f66acf803..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/verify/gofmt.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash - -set -o errexit -set -o nounset -set -o pipefail - -ROOT=$(dirname "${BASH_SOURCE}")/.. - -pushd "${ROOT}" > /dev/null - -GOFMT=${GOFMT:-"gofmt"} -bad_files=$(find . -name '*.go' | xargs $GOFMT -s -l) -if [[ -n "${bad_files}" ]]; then - echo "!!! '$GOFMT' needs to be run on the following files: " - echo "${bad_files}" - exit 1 -fi - -# ex: ts=2 sw=2 et filetype=sh diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/verify/golint.sh b/Godeps/_workspace/src/github.com/spf13/pflag/verify/golint.sh deleted file mode 100644 index 685c1778e..000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/verify/golint.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -ROOT=$(dirname "${BASH_SOURCE}")/.. -GOLINT=${GOLINT:-"golint"} - -pushd "${ROOT}" > /dev/null - bad_files=$($GOLINT -min_confidence=0.9 ./...) - if [[ -n "${bad_files}" ]]; then - echo "!!! '$GOLINT' problems: " - echo "${bad_files}" - exit 1 - fi -popd > /dev/null - -# ex: ts=2 sw=2 et filetype=sh diff --git a/Godeps/_workspace/src/github.com/ugorji/go/LICENSE b/Godeps/_workspace/src/github.com/ugorji/go/LICENSE new file mode 100644 index 000000000..95a0f0541 --- /dev/null +++ b/Godeps/_workspace/src/github.com/ugorji/go/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2012-2015 Ugorji Nwoke. +All rights reserved. + +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/Godeps/_workspace/src/github.com/ugorji/go/codec/0doc.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/0doc.go index caa7e0a3b..bd7361c87 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/0doc.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/0doc.go @@ -64,6 +64,7 @@ Rich Feature Set includes: - Never silently skip data when decoding. User decides whether to return an error or silently skip data when keys or indexes in the data stream do not map to fields in the struct. + - Detect and error when encoding a cyclic reference (instead of stack overflow shutdown) - Encode/Decode from/to chan types (for iterative streaming support) - Drop-in replacement for encoding/json. `json:` key in struct tag supported. - Provides a RPC Server and Client Codec for net/rpc communication protocol. @@ -171,6 +172,8 @@ package codec // TODO: // +// - optimization for codecgen: +// if len of entity is <= 3 words, then support a value receiver for encode. // - (En|De)coder should store an error when it occurs. // Until reset, subsequent calls return that error that was stored. // This means that free panics must go away. @@ -183,11 +186,14 @@ package codec // Name string // Ys []Y // Ys chan <- Y -// Ys func(interface{}) -> call this interface for each entry in there. +// Ys func(Y) -> call this function for each entry // } // - Consider adding a isZeroer interface { isZero() bool } // It is used within isEmpty, for omitEmpty support. // - Consider making Handle used AS-IS within the encoding/decoding session. // This means that we don't cache Handle information within the (En|De)coder, // except we really need it at Reset(...) -// - Handle recursive types during encoding/decoding? +// - Consider adding math/big support +// - Consider reducing the size of the generated functions: +// Maybe use one loop, and put the conditionals in the loop. +// for ... { if cLen > 0 { if j == cLen { break } } else if dd.CheckBreak() { break } } diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go index c884d14dc..766d26cf6 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/binc.go @@ -908,10 +908,14 @@ func (h *BincHandle) newDecDriver(d *Decoder) decDriver { func (e *bincEncDriver) reset() { e.w = e.e.w + e.s = 0 + e.m = nil } func (d *bincDecDriver) reset() { d.r = d.d.r + d.s = nil + d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0 } var _ decDriver = (*bincDecDriver)(nil) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor.go index 0e5d32b2e..a224cd3a7 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor.go @@ -508,7 +508,7 @@ func (d *cborDecDriver) DecodeNaked() { n.v = valueTypeExt n.u = d.decUint() n.l = nil - d.bdRead = false + // d.bdRead = false // d.d.decode(&re.Value) // handled by decode itself. // decodeFurther = true default: @@ -578,6 +578,7 @@ func (e *cborEncDriver) reset() { func (d *cborDecDriver) reset() { d.r = d.d.r + d.bd, d.bdRead = 0, false } var _ decDriver = (*cborDecDriver)(nil) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor_test.go deleted file mode 100644 index 205dffa7d..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/cbor_test.go +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -import ( - "bufio" - "bytes" - "encoding/hex" - "math" - "os" - "regexp" - "strings" - "testing" -) - -func TestCborIndefiniteLength(t *testing.T) { - oldMapType := testCborH.MapType - defer func() { - testCborH.MapType = oldMapType - }() - testCborH.MapType = testMapStrIntfTyp - // var ( - // M1 map[string][]byte - // M2 map[uint64]bool - // L1 []interface{} - // S1 []string - // B1 []byte - // ) - var v, vv interface{} - // define it (v), encode it using indefinite lengths, decode it (vv), compare v to vv - v = map[string]interface{}{ - "one-byte-key": []byte{1, 2, 3, 4, 5, 6}, - "two-string-key": "two-value", - "three-list-key": []interface{}{true, false, uint64(1), int64(-1)}, - } - var buf bytes.Buffer - // buf.Reset() - e := NewEncoder(&buf, testCborH) - buf.WriteByte(cborBdIndefiniteMap) - //---- - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode("one-") - e.MustEncode("byte-") - e.MustEncode("key") - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdIndefiniteBytes) - e.MustEncode([]byte{1, 2, 3}) - e.MustEncode([]byte{4, 5, 6}) - buf.WriteByte(cborBdBreak) - - //---- - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode("two-") - e.MustEncode("string-") - e.MustEncode("key") - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode([]byte("two-")) // encode as bytes, to check robustness of code - e.MustEncode([]byte("value")) - buf.WriteByte(cborBdBreak) - - //---- - buf.WriteByte(cborBdIndefiniteString) - e.MustEncode("three-") - e.MustEncode("list-") - e.MustEncode("key") - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdIndefiniteArray) - e.MustEncode(true) - e.MustEncode(false) - e.MustEncode(uint64(1)) - e.MustEncode(int64(-1)) - buf.WriteByte(cborBdBreak) - - buf.WriteByte(cborBdBreak) // close map - - NewDecoderBytes(buf.Bytes(), testCborH).MustDecode(&vv) - if err := deepEqual(v, vv); err != nil { - logT(t, "-------- Before and After marshal do not match: Error: %v", err) - logT(t, " ....... GOLDEN: (%T) %#v", v, v) - logT(t, " ....... DECODED: (%T) %#v", vv, vv) - failT(t) - } -} - -type testCborGolden struct { - Base64 string `codec:"cbor"` - Hex string `codec:"hex"` - Roundtrip bool `codec:"roundtrip"` - Decoded interface{} `codec:"decoded"` - Diagnostic string `codec:"diagnostic"` - Skip bool `codec:"skip"` -} - -// Some tests are skipped because they include numbers outside the range of int64/uint64 -func doTestCborGoldens(t *testing.T) { - oldMapType := testCborH.MapType - defer func() { - testCborH.MapType = oldMapType - }() - testCborH.MapType = testMapStrIntfTyp - // decode test-cbor-goldens.json into a list of []*testCborGolden - // for each one, - // - decode hex into []byte bs - // - decode bs into interface{} v - // - compare both using deepequal - // - for any miss, record it - var gs []*testCborGolden - f, err := os.Open("test-cbor-goldens.json") - if err != nil { - logT(t, "error opening test-cbor-goldens.json: %v", err) - failT(t) - } - defer f.Close() - jh := new(JsonHandle) - jh.MapType = testMapStrIntfTyp - // d := NewDecoder(f, jh) - d := NewDecoder(bufio.NewReader(f), jh) - // err = d.Decode(&gs) - d.MustDecode(&gs) - if err != nil { - logT(t, "error json decoding test-cbor-goldens.json: %v", err) - failT(t) - } - - tagregex := regexp.MustCompile(`[\d]+\(.+?\)`) - hexregex := regexp.MustCompile(`h'([0-9a-fA-F]*)'`) - for i, g := range gs { - // fmt.Printf("%v, skip: %v, isTag: %v, %s\n", i, g.Skip, tagregex.MatchString(g.Diagnostic), g.Diagnostic) - // skip tags or simple or those with prefix, as we can't verify them. - if g.Skip || strings.HasPrefix(g.Diagnostic, "simple(") || tagregex.MatchString(g.Diagnostic) { - // fmt.Printf("%v: skipped\n", i) - logT(t, "[%v] skipping because skip=true OR unsupported simple value or Tag Value", i) - continue - } - // println("++++++++++++", i, "g.Diagnostic", g.Diagnostic) - if hexregex.MatchString(g.Diagnostic) { - // println(i, "g.Diagnostic matched hex") - if s2 := g.Diagnostic[2 : len(g.Diagnostic)-1]; s2 == "" { - g.Decoded = zeroByteSlice - } else if bs2, err2 := hex.DecodeString(s2); err2 == nil { - g.Decoded = bs2 - } - // fmt.Printf("%v: hex: %v\n", i, g.Decoded) - } - bs, err := hex.DecodeString(g.Hex) - if err != nil { - logT(t, "[%v] error hex decoding %s [%v]: %v", i, g.Hex, err) - failT(t) - } - var v interface{} - NewDecoderBytes(bs, testCborH).MustDecode(&v) - if _, ok := v.(RawExt); ok { - continue - } - // check the diagnostics to compare - switch g.Diagnostic { - case "Infinity": - b := math.IsInf(v.(float64), 1) - testCborError(t, i, math.Inf(1), v, nil, &b) - case "-Infinity": - b := math.IsInf(v.(float64), -1) - testCborError(t, i, math.Inf(-1), v, nil, &b) - case "NaN": - // println(i, "checking NaN") - b := math.IsNaN(v.(float64)) - testCborError(t, i, math.NaN(), v, nil, &b) - case "undefined": - b := v == nil - testCborError(t, i, nil, v, nil, &b) - default: - v0 := g.Decoded - // testCborCoerceJsonNumber(reflect.ValueOf(&v0)) - testCborError(t, i, v0, v, deepEqual(v0, v), nil) - } - } -} - -func testCborError(t *testing.T, i int, v0, v1 interface{}, err error, equal *bool) { - if err == nil && equal == nil { - // fmt.Printf("%v testCborError passed (err and equal nil)\n", i) - return - } - if err != nil { - logT(t, "[%v] deepEqual error: %v", i, err) - logT(t, " ....... GOLDEN: (%T) %#v", v0, v0) - logT(t, " ....... DECODED: (%T) %#v", v1, v1) - failT(t) - } - if equal != nil && !*equal { - logT(t, "[%v] values not equal", i) - logT(t, " ....... GOLDEN: (%T) %#v", v0, v0) - logT(t, " ....... DECODED: (%T) %#v", v1, v1) - failT(t) - } - // fmt.Printf("%v testCborError passed (checks passed)\n", i) -} - -func TestCborGoldens(t *testing.T) { - doTestCborGoldens(t) -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go deleted file mode 100644 index ab14e2d01..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go +++ /dev/null @@ -1,1185 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// Test works by using a slice of interfaces. -// It can test for encoding/decoding into/from a nil interface{} -// or passing the object to encode/decode into. -// -// There are basically 2 main tests here. -// First test internally encodes and decodes things and verifies that -// the artifact was as expected. -// Second test will use python msgpack to create a bunch of golden files, -// read those files, and compare them to what it should be. It then -// writes those files back out and compares the byte streams. -// -// Taken together, the tests are pretty extensive. -// -// The following manual tests must be done: -// - TestCodecUnderlyingType -// - Set fastpathEnabled to false and run tests (to ensure that regular reflection works). -// We don't want to use a variable there so that code is ellided. - -import ( - "bytes" - "encoding/gob" - "flag" - "fmt" - "io/ioutil" - "math" - "math/rand" - "net" - "net/rpc" - "os" - "os/exec" - "path/filepath" - "reflect" - "runtime" - "strconv" - "sync/atomic" - "testing" - "time" -) - -func init() { - testInitFlags() - testPreInitFns = append(testPreInitFns, testInit) -} - -type testVerifyArg int - -const ( - testVerifyMapTypeSame testVerifyArg = iota - testVerifyMapTypeStrIntf - testVerifyMapTypeIntfIntf - // testVerifySliceIntf - testVerifyForPython -) - -const testSkipRPCTests = false - -var ( - testVerbose bool - testInitDebug bool - testUseIoEncDec bool - testStructToArray bool - testCanonical bool - testUseReset bool - testWriteNoSymbols bool - testSkipIntf bool - testInternStr bool - testUseMust bool - - skipVerifyVal interface{} = &(struct{}{}) - - testMapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil)) - - // For Go Time, do not use a descriptive timezone. - // It's unnecessary, and makes it harder to do a reflect.DeepEqual. - // The Offset already tells what the offset should be, if not on UTC and unknown zone name. - timeLoc = time.FixedZone("", -8*60*60) // UTC-08:00 //time.UTC-8 - timeToCompare1 = time.Date(2012, 2, 2, 2, 2, 2, 2000, timeLoc).UTC() - timeToCompare2 = time.Date(1900, 2, 2, 2, 2, 2, 2000, timeLoc).UTC() - timeToCompare3 = time.Unix(0, 270).UTC() // use value that must be encoded as uint64 for nanoseconds (for cbor/msgpack comparison) - //timeToCompare4 = time.Time{}.UTC() // does not work well with simple cbor time encoding (overflow) - timeToCompare4 = time.Unix(-2013855848, 4223).UTC() - - table []interface{} // main items we encode - tableVerify []interface{} // we verify encoded things against this after decode - tableTestNilVerify []interface{} // for nil interface, use this to verify (rules are different) - tablePythonVerify []interface{} // for verifying for python, since Python sometimes - // will encode a float32 as float64, or large int as uint - testRpcInt = new(TestRpcInt) -) - -func testInitFlags() { - // delete(testDecOpts.ExtFuncs, timeTyp) - flag.BoolVar(&testVerbose, "tv", false, "Test Verbose") - flag.BoolVar(&testInitDebug, "tg", false, "Test Init Debug") - flag.BoolVar(&testUseIoEncDec, "ti", false, "Use IO Reader/Writer for Marshal/Unmarshal") - flag.BoolVar(&testStructToArray, "ts", false, "Set StructToArray option") - flag.BoolVar(&testWriteNoSymbols, "tn", false, "Set NoSymbols option") - flag.BoolVar(&testCanonical, "tc", false, "Set Canonical option") - flag.BoolVar(&testInternStr, "te", false, "Set InternStr option") - flag.BoolVar(&testSkipIntf, "tf", false, "Skip Interfaces") - flag.BoolVar(&testUseReset, "tr", false, "Use Reset") - flag.BoolVar(&testUseMust, "tm", true, "Use Must(En|De)code") -} - -func testByteBuf(in []byte) *bytes.Buffer { - return bytes.NewBuffer(in) -} - -type TestABC struct { - A, B, C string -} - -type TestRpcInt struct { - i int -} - -func (r *TestRpcInt) Update(n int, res *int) error { r.i = n; *res = r.i; return nil } -func (r *TestRpcInt) Square(ignore int, res *int) error { *res = r.i * r.i; return nil } -func (r *TestRpcInt) Mult(n int, res *int) error { *res = r.i * n; return nil } -func (r *TestRpcInt) EchoStruct(arg TestABC, res *string) error { - *res = fmt.Sprintf("%#v", arg) - return nil -} -func (r *TestRpcInt) Echo123(args []string, res *string) error { - *res = fmt.Sprintf("%#v", args) - return nil -} - -type testUnixNanoTimeExt struct { - // keep timestamp here, so that do not incur interface-conversion costs - ts int64 -} - -// func (x *testUnixNanoTimeExt) WriteExt(interface{}) []byte { panic("unsupported") } -// func (x *testUnixNanoTimeExt) ReadExt(interface{}, []byte) { panic("unsupported") } -func (x *testUnixNanoTimeExt) ConvertExt(v interface{}) interface{} { - switch v2 := v.(type) { - case time.Time: - x.ts = v2.UTC().UnixNano() - case *time.Time: - x.ts = v2.UTC().UnixNano() - default: - panic(fmt.Sprintf("unsupported format for time conversion: expecting time.Time; got %T", v)) - } - return &x.ts -} -func (x *testUnixNanoTimeExt) UpdateExt(dest interface{}, v interface{}) { - // fmt.Printf("testUnixNanoTimeExt.UpdateExt: v: %v\n", v) - tt := dest.(*time.Time) - switch v2 := v.(type) { - case int64: - *tt = time.Unix(0, v2).UTC() - case *int64: - *tt = time.Unix(0, *v2).UTC() - case uint64: - *tt = time.Unix(0, int64(v2)).UTC() - case *uint64: - *tt = time.Unix(0, int64(*v2)).UTC() - //case float64: - //case string: - default: - panic(fmt.Sprintf("unsupported format for time conversion: expecting int64/uint64; got %T", v)) - } - // fmt.Printf("testUnixNanoTimeExt.UpdateExt: v: %v, tt: %#v\n", v, tt) -} - -func testVerifyVal(v interface{}, arg testVerifyArg) (v2 interface{}) { - //for python msgpack, - // - all positive integers are unsigned 64-bit ints - // - all floats are float64 - switch iv := v.(type) { - case int8: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case int16: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case int32: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case int64: - if iv >= 0 { - v2 = uint64(iv) - } else { - v2 = int64(iv) - } - case uint8: - v2 = uint64(iv) - case uint16: - v2 = uint64(iv) - case uint32: - v2 = uint64(iv) - case uint64: - v2 = uint64(iv) - case float32: - v2 = float64(iv) - case float64: - v2 = float64(iv) - case []interface{}: - m2 := make([]interface{}, len(iv)) - for j, vj := range iv { - m2[j] = testVerifyVal(vj, arg) - } - v2 = m2 - case map[string]bool: - switch arg { - case testVerifyMapTypeSame: - m2 := make(map[string]bool) - for kj, kv := range iv { - m2[kj] = kv - } - v2 = m2 - case testVerifyMapTypeStrIntf, testVerifyForPython: - m2 := make(map[string]interface{}) - for kj, kv := range iv { - m2[kj] = kv - } - v2 = m2 - case testVerifyMapTypeIntfIntf: - m2 := make(map[interface{}]interface{}) - for kj, kv := range iv { - m2[kj] = kv - } - v2 = m2 - } - case map[string]interface{}: - switch arg { - case testVerifyMapTypeSame: - m2 := make(map[string]interface{}) - for kj, kv := range iv { - m2[kj] = testVerifyVal(kv, arg) - } - v2 = m2 - case testVerifyMapTypeStrIntf, testVerifyForPython: - m2 := make(map[string]interface{}) - for kj, kv := range iv { - m2[kj] = testVerifyVal(kv, arg) - } - v2 = m2 - case testVerifyMapTypeIntfIntf: - m2 := make(map[interface{}]interface{}) - for kj, kv := range iv { - m2[kj] = testVerifyVal(kv, arg) - } - v2 = m2 - } - case map[interface{}]interface{}: - m2 := make(map[interface{}]interface{}) - for kj, kv := range iv { - m2[testVerifyVal(kj, arg)] = testVerifyVal(kv, arg) - } - v2 = m2 - case time.Time: - switch arg { - case testVerifyForPython: - if iv2 := iv.UnixNano(); iv2 >= 0 { - v2 = uint64(iv2) - } else { - v2 = int64(iv2) - } - default: - v2 = v - } - default: - v2 = v - } - return -} - -func testInit() { - gob.Register(new(TestStruc)) - if testInitDebug { - ts0 := newTestStruc(2, false, !testSkipIntf, false) - fmt.Printf("====> depth: %v, ts: %#v\n", 2, ts0) - } - - for _, v := range testHandles { - bh := v.getBasicHandle() - bh.InternString = testInternStr - bh.Canonical = testCanonical - bh.StructToArray = testStructToArray - // mostly doing this for binc - if testWriteNoSymbols { - bh.AsSymbols = AsSymbolNone - } else { - bh.AsSymbols = AsSymbolAll - } - } - - testMsgpackH.RawToString = true - - // testMsgpackH.AddExt(byteSliceTyp, 0, testMsgpackH.BinaryEncodeExt, testMsgpackH.BinaryDecodeExt) - // testMsgpackH.AddExt(timeTyp, 1, testMsgpackH.TimeEncodeExt, testMsgpackH.TimeDecodeExt) - timeEncExt := func(rv reflect.Value) (bs []byte, err error) { - defer panicToErr(&err) - bs = timeExt{}.WriteExt(rv.Interface()) - return - } - timeDecExt := func(rv reflect.Value, bs []byte) (err error) { - defer panicToErr(&err) - timeExt{}.ReadExt(rv.Interface(), bs) - return - } - - // add extensions for msgpack, simple for time.Time, so we can encode/decode same way. - // use different flavors of XXXExt calls, including deprecated ones. - testSimpleH.AddExt(timeTyp, 1, timeEncExt, timeDecExt) - testMsgpackH.SetBytesExt(timeTyp, 1, timeExt{}) - testCborH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{}) - testJsonH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{}) - - primitives := []interface{}{ - int8(-8), - int16(-1616), - int32(-32323232), - int64(-6464646464646464), - uint8(192), - uint16(1616), - uint32(32323232), - uint64(6464646464646464), - byte(192), - float32(-3232.0), - float64(-6464646464.0), - float32(3232.0), - float64(6464646464.0), - false, - true, - nil, - "someday", - "", - "bytestring", - timeToCompare1, - timeToCompare2, - timeToCompare3, - timeToCompare4, - } - mapsAndStrucs := []interface{}{ - map[string]bool{ - "true": true, - "false": false, - }, - map[string]interface{}{ - "true": "True", - "false": false, - "uint16(1616)": uint16(1616), - }, - //add a complex combo map in here. (map has list which has map) - //note that after the first thing, everything else should be generic. - map[string]interface{}{ - "list": []interface{}{ - int16(1616), - int32(32323232), - true, - float32(-3232.0), - map[string]interface{}{ - "TRUE": true, - "FALSE": false, - }, - []interface{}{true, false}, - }, - "int32": int32(32323232), - "bool": true, - "LONG STRING": "123456789012345678901234567890123456789012345678901234567890", - "SHORT STRING": "1234567890", - }, - map[interface{}]interface{}{ - true: "true", - uint8(138): false, - "false": uint8(200), - }, - newTestStruc(0, false, !testSkipIntf, false), - } - - table = []interface{}{} - table = append(table, primitives...) //0-19 are primitives - table = append(table, primitives) //20 is a list of primitives - table = append(table, mapsAndStrucs...) //21-24 are maps. 25 is a *struct - - tableVerify = make([]interface{}, len(table)) - tableTestNilVerify = make([]interface{}, len(table)) - tablePythonVerify = make([]interface{}, len(table)) - - lp := len(primitives) - av := tableVerify - for i, v := range table { - if i == lp+3 { - av[i] = skipVerifyVal - continue - } - //av[i] = testVerifyVal(v, testVerifyMapTypeSame) - switch v.(type) { - case []interface{}: - av[i] = testVerifyVal(v, testVerifyMapTypeSame) - case map[string]interface{}: - av[i] = testVerifyVal(v, testVerifyMapTypeSame) - case map[interface{}]interface{}: - av[i] = testVerifyVal(v, testVerifyMapTypeSame) - default: - av[i] = v - } - } - - av = tableTestNilVerify - for i, v := range table { - if i > lp+3 { - av[i] = skipVerifyVal - continue - } - av[i] = testVerifyVal(v, testVerifyMapTypeStrIntf) - } - - av = tablePythonVerify - for i, v := range table { - if i > lp+3 { - av[i] = skipVerifyVal - continue - } - av[i] = testVerifyVal(v, testVerifyForPython) - } - - tablePythonVerify = tablePythonVerify[:24] -} - -func testUnmarshal(v interface{}, data []byte, h Handle) (err error) { - return testCodecDecode(data, v, h) -} - -func testMarshal(v interface{}, h Handle) (bs []byte, err error) { - return testCodecEncode(v, nil, testByteBuf, h) -} - -func testMarshalErr(v interface{}, h Handle, t *testing.T, name string) (bs []byte, err error) { - if bs, err = testMarshal(v, h); err != nil { - logT(t, "Error encoding %s: %v, Err: %v", name, v, err) - t.FailNow() - } - return -} - -func testUnmarshalErr(v interface{}, data []byte, h Handle, t *testing.T, name string) (err error) { - if err = testUnmarshal(v, data, h); err != nil { - logT(t, "Error Decoding into %s: %v, Err: %v", name, v, err) - t.FailNow() - } - return -} - -// doTestCodecTableOne allows us test for different variations based on arguments passed. -func doTestCodecTableOne(t *testing.T, testNil bool, h Handle, - vs []interface{}, vsVerify []interface{}) { - //if testNil, then just test for when a pointer to a nil interface{} is passed. It should work. - //Current setup allows us test (at least manually) the nil interface or typed interface. - logT(t, "================ TestNil: %v ================\n", testNil) - for i, v0 := range vs { - logT(t, "..............................................") - logT(t, " Testing: #%d:, %T, %#v\n", i, v0, v0) - b0, err := testMarshalErr(v0, h, t, "v0") - if err != nil { - continue - } - if h.isBinary() { - logT(t, " Encoded bytes: len: %v, %v\n", len(b0), b0) - } else { - logT(t, " Encoded string: len: %v, %v\n", len(string(b0)), string(b0)) - // println("########### encoded string: " + string(b0)) - } - var v1 interface{} - - if testNil { - err = testUnmarshal(&v1, b0, h) - } else { - if v0 != nil { - v0rt := reflect.TypeOf(v0) // ptr - rv1 := reflect.New(v0rt) - err = testUnmarshal(rv1.Interface(), b0, h) - v1 = rv1.Elem().Interface() - // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() - } - } - - logT(t, " v1 returned: %T, %#v", v1, v1) - // if v1 != nil { - // logT(t, " v1 returned: %T, %#v", v1, v1) - // //we always indirect, because ptr to typed value may be passed (if not testNil) - // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() - // } - if err != nil { - logT(t, "-------- Error: %v. Partial return: %v", err, v1) - failT(t) - continue - } - v0check := vsVerify[i] - if v0check == skipVerifyVal { - logT(t, " Nil Check skipped: Decoded: %T, %#v\n", v1, v1) - continue - } - - if err = deepEqual(v0check, v1); err == nil { - logT(t, "++++++++ Before and After marshal matched\n") - } else { - // logT(t, "-------- Before and After marshal do not match: Error: %v"+ - // " ====> GOLDEN: (%T) %#v, DECODED: (%T) %#v\n", err, v0check, v0check, v1, v1) - logT(t, "-------- Before and After marshal do not match: Error: %v", err) - logT(t, " ....... GOLDEN: (%T) %#v", v0check, v0check) - logT(t, " ....... DECODED: (%T) %#v", v1, v1) - failT(t) - } - } -} - -func testCodecTableOne(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - // func TestMsgpackAllExperimental(t *testing.T) { - // dopts := testDecOpts(nil, nil, false, true, true), - - idxTime, numPrim, numMap := 19, 23, 4 - //println("#################") - switch v := h.(type) { - case *MsgpackHandle: - var oldWriteExt, oldRawToString bool - oldWriteExt, v.WriteExt = v.WriteExt, true - oldRawToString, v.RawToString = v.RawToString, true - doTestCodecTableOne(t, false, h, table, tableVerify) - v.WriteExt, v.RawToString = oldWriteExt, oldRawToString - case *JsonHandle: - //skip []interface{} containing time.Time, as it encodes as a number, but cannot decode back to time.Time. - //As there is no real support for extension tags in json, this must be skipped. - doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim]) - doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:]) - default: - doTestCodecTableOne(t, false, h, table, tableVerify) - } - // func TestMsgpackAll(t *testing.T) { - - // //skip []interface{} containing time.Time - // doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim]) - // doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:]) - // func TestMsgpackNilStringMap(t *testing.T) { - var oldMapType reflect.Type - v := h.getBasicHandle() - - oldMapType, v.MapType = v.MapType, testMapStrIntfTyp - - //skip time.Time, []interface{} containing time.Time, last map, and newStruc - doTestCodecTableOne(t, true, h, table[:idxTime], tableTestNilVerify[:idxTime]) - doTestCodecTableOne(t, true, h, table[numPrim+1:numPrim+numMap], tableTestNilVerify[numPrim+1:numPrim+numMap]) - - v.MapType = oldMapType - - // func TestMsgpackNilIntf(t *testing.T) { - - //do newTestStruc and last element of map - doTestCodecTableOne(t, true, h, table[numPrim+numMap:], tableTestNilVerify[numPrim+numMap:]) - //TODO? What is this one? - //doTestCodecTableOne(t, true, h, table[17:18], tableTestNilVerify[17:18]) -} - -func testCodecMiscOne(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - b, err := testMarshalErr(32, h, t, "32") - // Cannot do this nil one, because faster type assertion decoding will panic - // var i *int32 - // if err = testUnmarshal(b, i, nil); err == nil { - // logT(t, "------- Expecting error because we cannot unmarshal to int32 nil ptr") - // t.FailNow() - // } - var i2 int32 = 0 - err = testUnmarshalErr(&i2, b, h, t, "int32-ptr") - if i2 != int32(32) { - logT(t, "------- didn't unmarshal to 32: Received: %d", i2) - t.FailNow() - } - - // func TestMsgpackDecodePtr(t *testing.T) { - ts := newTestStruc(0, false, !testSkipIntf, false) - b, err = testMarshalErr(ts, h, t, "pointer-to-struct") - if len(b) < 40 { - logT(t, "------- Size must be > 40. Size: %d", len(b)) - t.FailNow() - } - if h.isBinary() { - logT(t, "------- b: %v", b) - } else { - logT(t, "------- b: %s", b) - } - ts2 := new(TestStruc) - err = testUnmarshalErr(ts2, b, h, t, "pointer-to-struct") - if ts2.I64 != math.MaxInt64*2/3 { - logT(t, "------- Unmarshal wrong. Expect I64 = 64. Got: %v", ts2.I64) - t.FailNow() - } - - // func TestMsgpackIntfDecode(t *testing.T) { - m := map[string]int{"A": 2, "B": 3} - p := []interface{}{m} - bs, err := testMarshalErr(p, h, t, "p") - - m2 := map[string]int{} - p2 := []interface{}{m2} - err = testUnmarshalErr(&p2, bs, h, t, "&p2") - - if m2["A"] != 2 || m2["B"] != 3 { - logT(t, "m2 not as expected: expecting: %v, got: %v", m, m2) - t.FailNow() - } - // log("m: %v, m2: %v, p: %v, p2: %v", m, m2, p, p2) - checkEqualT(t, p, p2, "p=p2") - checkEqualT(t, m, m2, "m=m2") - if err = deepEqual(p, p2); err == nil { - logT(t, "p and p2 match") - } else { - logT(t, "Not Equal: %v. p: %v, p2: %v", err, p, p2) - t.FailNow() - } - if err = deepEqual(m, m2); err == nil { - logT(t, "m and m2 match") - } else { - logT(t, "Not Equal: %v. m: %v, m2: %v", err, m, m2) - t.FailNow() - } - - // func TestMsgpackDecodeStructSubset(t *testing.T) { - // test that we can decode a subset of the stream - mm := map[string]interface{}{"A": 5, "B": 99, "C": 333} - bs, err = testMarshalErr(mm, h, t, "mm") - type ttt struct { - A uint8 - C int32 - } - var t2 ttt - testUnmarshalErr(&t2, bs, h, t, "t2") - t3 := ttt{5, 333} - checkEqualT(t, t2, t3, "t2=t3") - - // println(">>>>>") - // test simple arrays, non-addressable arrays, slices - type tarr struct { - A int64 - B [3]int64 - C []byte - D [3]byte - } - var tarr0 = tarr{1, [3]int64{2, 3, 4}, []byte{4, 5, 6}, [3]byte{7, 8, 9}} - // test both pointer and non-pointer (value) - for _, tarr1 := range []interface{}{tarr0, &tarr0} { - bs, err = testMarshalErr(tarr1, h, t, "tarr1") - if err != nil { - logT(t, "Error marshalling: %v", err) - t.FailNow() - } - if _, ok := h.(*JsonHandle); ok { - logT(t, "Marshal as: %s", bs) - } - var tarr2 tarr - testUnmarshalErr(&tarr2, bs, h, t, "tarr2") - checkEqualT(t, tarr0, tarr2, "tarr0=tarr2") - // fmt.Printf(">>>> err: %v. tarr1: %v, tarr2: %v\n", err, tarr0, tarr2) - } - - // test byte array, even if empty (msgpack only) - if h == testMsgpackH { - type ystruct struct { - Anarray []byte - } - var ya = ystruct{} - testUnmarshalErr(&ya, []byte{0x91, 0x90}, h, t, "ya") - } -} - -func testCodecEmbeddedPointer(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - type Z int - type A struct { - AnInt int - } - type B struct { - *Z - *A - MoreInt int - } - var z Z = 4 - x1 := &B{&z, &A{5}, 6} - bs, err := testMarshalErr(x1, h, t, "x1") - // fmt.Printf("buf: len(%v): %x\n", buf.Len(), buf.Bytes()) - var x2 = new(B) - err = testUnmarshalErr(x2, bs, h, t, "x2") - err = checkEqualT(t, x1, x2, "x1=x2") - _ = err -} - -func testCodecUnderlyingType(t *testing.T, h Handle) { - testOnce.Do(testInitAll) - // Manual Test. - // Run by hand, with accompanying print statements in fast-path.go - // to ensure that the fast functions are called. - type T1 map[string]string - v := T1{"1": "1s", "2": "2s"} - var bs []byte - var err error - NewEncoderBytes(&bs, h).MustEncode(v) - if err != nil { - logT(t, "Error during encode: %v", err) - failT(t) - } - var v2 T1 - NewDecoderBytes(bs, h).MustDecode(&v2) - if err != nil { - logT(t, "Error during decode: %v", err) - failT(t) - } -} - -func testCodecChan(t *testing.T, h Handle) { - // - send a slice []*int64 (sl1) into an chan (ch1) with cap > len(s1) - // - encode ch1 as a stream array - // - decode a chan (ch2), with cap > len(s1) from the stream array - // - receive from ch2 into slice sl2 - // - compare sl1 and sl2 - // - do this for codecs: json, cbor (covers all types) - sl1 := make([]*int64, 4) - for i := range sl1 { - var j int64 = int64(i) - sl1[i] = &j - } - ch1 := make(chan *int64, 4) - for _, j := range sl1 { - ch1 <- j - } - var bs []byte - NewEncoderBytes(&bs, h).MustEncode(ch1) - // if !h.isBinary() { - // fmt.Printf("before: len(ch1): %v, bs: %s\n", len(ch1), bs) - // } - // var ch2 chan *int64 // this will block if json, etc. - ch2 := make(chan *int64, 8) - NewDecoderBytes(bs, h).MustDecode(&ch2) - // logT(t, "Len(ch2): %v", len(ch2)) - // fmt.Printf("after: len(ch2): %v, ch2: %v\n", len(ch2), ch2) - close(ch2) - var sl2 []*int64 - for j := range ch2 { - sl2 = append(sl2, j) - } - if err := deepEqual(sl1, sl2); err != nil { - logT(t, "Not Match: %v; len: %v, %v", err, len(sl1), len(sl2)) - failT(t) - } -} - -func testCodecRpcOne(t *testing.T, rr Rpc, h Handle, doRequest bool, exitSleepMs time.Duration, -) (port int) { - testOnce.Do(testInitAll) - if testSkipRPCTests { - return - } - // rpc needs EOF, which is sent via a panic, and so must be recovered. - if !recoverPanicToErr { - logT(t, "EXPECTED. set recoverPanicToErr=true, since rpc needs EOF") - t.FailNow() - } - srv := rpc.NewServer() - srv.Register(testRpcInt) - ln, err := net.Listen("tcp", "127.0.0.1:0") - // log("listener: %v", ln.Addr()) - checkErrT(t, err) - port = (ln.Addr().(*net.TCPAddr)).Port - // var opts *DecoderOptions - // opts := testDecOpts - // opts.MapType = mapStrIntfTyp - // opts.RawToString = false - serverExitChan := make(chan bool, 1) - var serverExitFlag uint64 = 0 - serverFn := func() { - for { - conn1, err1 := ln.Accept() - // if err1 != nil { - // //fmt.Printf("accept err1: %v\n", err1) - // continue - // } - if atomic.LoadUint64(&serverExitFlag) == 1 { - serverExitChan <- true - conn1.Close() - return // exit serverFn goroutine - } - if err1 == nil { - var sc rpc.ServerCodec = rr.ServerCodec(conn1, h) - srv.ServeCodec(sc) - } - } - } - - clientFn := func(cc rpc.ClientCodec) { - cl := rpc.NewClientWithCodec(cc) - defer cl.Close() - // defer func() { println("##### client closing"); cl.Close() }() - var up, sq, mult int - var rstr string - // log("Calling client") - checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up)) - // log("Called TestRpcInt.Update") - checkEqualT(t, testRpcInt.i, 5, "testRpcInt.i=5") - checkEqualT(t, up, 5, "up=5") - checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq)) - checkEqualT(t, sq, 25, "sq=25") - checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult)) - checkEqualT(t, mult, 100, "mult=100") - checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr)) - checkEqualT(t, rstr, fmt.Sprintf("%#v", TestABC{"Aa", "Bb", "Cc"}), "rstr=") - checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr)) - checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}), "rstr=") - } - - connFn := func() (bs net.Conn) { - // log("calling f1") - bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String()) - //fmt.Printf("f1. bs: %v, err2: %v\n", bs, err2) - checkErrT(t, err2) - return - } - - exitFn := func() { - atomic.StoreUint64(&serverExitFlag, 1) - bs := connFn() - <-serverExitChan - bs.Close() - // serverExitChan <- true - } - - go serverFn() - runtime.Gosched() - //time.Sleep(100 * time.Millisecond) - if exitSleepMs == 0 { - defer ln.Close() - defer exitFn() - } - if doRequest { - bs := connFn() - cc := rr.ClientCodec(bs, h) - clientFn(cc) - } - if exitSleepMs != 0 { - go func() { - defer ln.Close() - time.Sleep(exitSleepMs) - exitFn() - }() - } - return -} - -func doTestMapEncodeForCanonical(t *testing.T, name string, h Handle) { - v1 := map[string]interface{}{ - "a": 1, - "b": "hello", - "c": map[string]interface{}{ - "c/a": 1, - "c/b": "world", - "c/c": []int{1, 2, 3, 4}, - "c/d": map[string]interface{}{ - "c/d/a": "fdisajfoidsajfopdjsaopfjdsapofda", - "c/d/b": "fdsafjdposakfodpsakfopdsakfpodsakfpodksaopfkdsopafkdopsa", - "c/d/c": "poir02 ir30qif4p03qir0pogjfpoaerfgjp ofke[padfk[ewapf kdp[afep[aw", - "c/d/d": "fdsopafkd[sa f-32qor-=4qeof -afo-erfo r-eafo 4e- o r4-qwo ag", - "c/d/e": "kfep[a sfkr0[paf[a foe-[wq ewpfao-q ro3-q ro-4qof4-qor 3-e orfkropzjbvoisdb", - "c/d/f": "", - }, - "c/e": map[int]string{ - 1: "1", - 22: "22", - 333: "333", - 4444: "4444", - 55555: "55555", - }, - "c/f": map[string]int{ - "1": 1, - "22": 22, - "333": 333, - "4444": 4444, - "55555": 55555, - }, - }, - } - var v2 map[string]interface{} - var b1, b2 []byte - - // encode v1 into b1, decode b1 into v2, encode v2 into b2, compare b1 and b2 - - bh := h.getBasicHandle() - if !bh.Canonical { - bh.Canonical = true - defer func() { bh.Canonical = false }() - } - - e1 := NewEncoderBytes(&b1, h) - e1.MustEncode(v1) - d1 := NewDecoderBytes(b1, h) - d1.MustDecode(&v2) - e2 := NewEncoderBytes(&b2, h) - e2.MustEncode(v2) - if !bytes.Equal(b1, b2) { - logT(t, "Unequal bytes: %v VS %v", b1, b2) - t.FailNow() - } -} - -// Comprehensive testing that generates data encoded from python handle (cbor, msgpack), -// and validates that our code can read and write it out accordingly. -// We keep this unexported here, and put actual test in ext_dep_test.go. -// This way, it can be excluded by excluding file completely. -func doTestPythonGenStreams(t *testing.T, name string, h Handle) { - logT(t, "TestPythonGenStreams-%v", name) - tmpdir, err := ioutil.TempDir("", "golang-"+name+"-test") - if err != nil { - logT(t, "-------- Unable to create temp directory\n") - t.FailNow() - } - defer os.RemoveAll(tmpdir) - logT(t, "tmpdir: %v", tmpdir) - cmd := exec.Command("python", "test.py", "testdata", tmpdir) - //cmd.Stdin = strings.NewReader("some input") - //cmd.Stdout = &out - var cmdout []byte - if cmdout, err = cmd.CombinedOutput(); err != nil { - logT(t, "-------- Error running test.py testdata. Err: %v", err) - logT(t, " %v", string(cmdout)) - t.FailNow() - } - - bh := h.getBasicHandle() - - oldMapType := bh.MapType - for i, v := range tablePythonVerify { - // if v == uint64(0) && h == testMsgpackH { - // v = int64(0) - // } - bh.MapType = oldMapType - //load up the golden file based on number - //decode it - //compare to in-mem object - //encode it again - //compare to output stream - logT(t, "..............................................") - logT(t, " Testing: #%d: %T, %#v\n", i, v, v) - var bss []byte - bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+"."+name+".golden")) - if err != nil { - logT(t, "-------- Error reading golden file: %d. Err: %v", i, err) - failT(t) - continue - } - bh.MapType = testMapStrIntfTyp - - var v1 interface{} - if err = testUnmarshal(&v1, bss, h); err != nil { - logT(t, "-------- Error decoding stream: %d: Err: %v", i, err) - failT(t) - continue - } - if v == skipVerifyVal { - continue - } - //no need to indirect, because we pass a nil ptr, so we already have the value - //if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() } - if err = deepEqual(v, v1); err == nil { - logT(t, "++++++++ Objects match: %T, %v", v, v) - } else { - logT(t, "-------- Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1) - logT(t, "-------- GOLDEN: %#v", v) - // logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface()) - logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface()) - failT(t) - } - bsb, err := testMarshal(v1, h) - if err != nil { - logT(t, "Error encoding to stream: %d: Err: %v", i, err) - failT(t) - continue - } - if err = deepEqual(bsb, bss); err == nil { - logT(t, "++++++++ Bytes match") - } else { - logT(t, "???????? Bytes do not match. %v.", err) - xs := "--------" - if reflect.ValueOf(v).Kind() == reflect.Map { - xs = " " - logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs) - } else { - logT(t, "%s It's not a map. They should match.", xs) - failT(t) - } - logT(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss) - logT(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb) - } - } - bh.MapType = oldMapType -} - -// To test MsgpackSpecRpc, we test 3 scenarios: -// - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec) -// - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc) -// - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc) -// -// This allows us test the different calling conventions -// - Go Service requires only one argument -// - Python Service allows multiple arguments - -func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) { - if testSkipRPCTests { - return - } - // openPorts are between 6700 and 6800 - r := rand.New(rand.NewSource(time.Now().UnixNano())) - openPort := strconv.FormatInt(6700+r.Int63n(99), 10) - // openPort := "6792" - cmd := exec.Command("python", "test.py", "rpc-server", openPort, "4") - checkErrT(t, cmd.Start()) - bs, err2 := net.Dial("tcp", ":"+openPort) - for i := 0; i < 10 && err2 != nil; i++ { - time.Sleep(50 * time.Millisecond) // time for python rpc server to start - bs, err2 = net.Dial("tcp", ":"+openPort) - } - checkErrT(t, err2) - cc := MsgpackSpecRpc.ClientCodec(bs, testMsgpackH) - cl := rpc.NewClientWithCodec(cc) - defer cl.Close() - var rstr string - checkErrT(t, cl.Call("EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr)) - //checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}") - var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"} - checkErrT(t, cl.Call("Echo123", mArgs, &rstr)) - checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=") - cmd.Process.Kill() -} - -func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) { - if testSkipRPCTests { - return - } - port := testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second) - //time.Sleep(1000 * time.Millisecond) - cmd := exec.Command("python", "test.py", "rpc-client-go-service", strconv.Itoa(port)) - var cmdout []byte - var err error - if cmdout, err = cmd.CombinedOutput(); err != nil { - logT(t, "-------- Error running test.py rpc-client-go-service. Err: %v", err) - logT(t, " %v", string(cmdout)) - t.FailNow() - } - checkEqualT(t, string(cmdout), - fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestABC{"Aa", "Bb", "Cc"}), "cmdout=") -} - -func TestBincCodecsTable(t *testing.T) { - testCodecTableOne(t, testBincH) -} - -func TestBincCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testBincH) -} - -func TestBincCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testBincH) -} - -func TestSimpleCodecsTable(t *testing.T) { - testCodecTableOne(t, testSimpleH) -} - -func TestSimpleCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testSimpleH) -} - -func TestSimpleCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testSimpleH) -} - -func TestMsgpackCodecsTable(t *testing.T) { - testCodecTableOne(t, testMsgpackH) -} - -func TestMsgpackCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testMsgpackH) -} - -func TestMsgpackCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testMsgpackH) -} - -func TestCborCodecsTable(t *testing.T) { - testCodecTableOne(t, testCborH) -} - -func TestCborCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testCborH) -} - -func TestCborCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testCborH) -} - -func TestCborMapEncodeForCanonical(t *testing.T) { - doTestMapEncodeForCanonical(t, "cbor", testCborH) -} - -func TestJsonCodecsTable(t *testing.T) { - testCodecTableOne(t, testJsonH) -} - -func TestJsonCodecsMisc(t *testing.T) { - testCodecMiscOne(t, testJsonH) -} - -func TestJsonCodecsEmbeddedPointer(t *testing.T) { - testCodecEmbeddedPointer(t, testJsonH) -} - -func TestJsonCodecChan(t *testing.T) { - testCodecChan(t, testJsonH) -} - -func TestCborCodecChan(t *testing.T) { - testCodecChan(t, testCborH) -} - -// ----- RPC ----- - -func TestBincRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testBincH, true, 0) -} - -func TestSimpleRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testSimpleH, true, 0) -} - -func TestMsgpackRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testMsgpackH, true, 0) -} - -func TestCborRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testCborH, true, 0) -} - -func TestJsonRpcGo(t *testing.T) { - testCodecRpcOne(t, GoRpc, testJsonH, true, 0) -} - -func TestMsgpackRpcSpec(t *testing.T) { - testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0) -} - -func TestBincUnderlyingType(t *testing.T) { - testCodecUnderlyingType(t, testBincH) -} - -// TODO: -// Add Tests for: -// - decoding empty list/map in stream into a nil slice/map -// - binary(M|Unm)arsher support for time.Time (e.g. cbor encoding) -// - text(M|Unm)arshaler support for time.Time (e.g. json encoding) -// - non fast-path scenarios e.g. map[string]uint16, []customStruct. -// Expand cbor to include indefinite length stuff for this non-fast-path types. -// This may not be necessary, since we have the manual tests (fastpathEnabled=false) to test/validate with. -// - CodecSelfer -// Ensure it is called when (en|de)coding interface{} or reflect.Value (2 different codepaths). -// - interfaces: textMarshaler, binaryMarshaler, codecSelfer -// - struct tags: -// on anonymous fields, _struct (all fields), etc -// - codecgen of struct containing channels. -// -// Cleanup tests: -// - The are brittle in their handling of validation and skipping diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/README.md b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/README.md deleted file mode 100644 index 3ae8a056f..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# codecgen tool - -Generate is given a list of *.go files to parse, and an output file (fout), -codecgen will create an output file __file.go__ which -contains `codec.Selfer` implementations for the named types found -in the files parsed. - -Using codecgen is very straightforward. - -**Download and install the tool** - -`go get -u github.com/ugorji/go/codec/codecgen` - -**Run the tool on your files** - -The command line format is: - -`codecgen [options] (-o outfile) (infile ...)` - -```sh -% codecgen -? -Usage of codecgen: - -c="github.com/ugorji/go/codec": codec path - -o="": out file - -r=".*": regex for type name to match - -rt="": tags for go run - -t="": build tag to put in file - -u=false: Use unsafe, e.g. to avoid unnecessary allocation on []byte->string - -x=false: keep temp file - -% codecgen -o values_codecgen.go values.go values2.go moretypedefs.go -``` - -Please see the [blog article](http://ugorji.net/blog/go-codecgen) -for more information on how to use the tool. - diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/gen.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/gen.go deleted file mode 100644 index f370b4c79..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/gen.go +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -// codecgen generates codec.Selfer implementations for a set of types. -package main - -import ( - "bufio" - "bytes" - "errors" - "flag" - "fmt" - "go/ast" - "go/build" - "go/parser" - "go/token" - "math/rand" - "os" - "os/exec" - "path/filepath" - "regexp" - "strconv" - "text/template" - "time" -) - -const genCodecPkg = "codec1978" // keep this in sync with codec.genCodecPkg - -const genFrunMainTmpl = `//+build ignore - -package main -{{ if .Types }}import "{{ .ImportPath }}"{{ end }} -func main() { - {{ $.PackageName }}.CodecGenTempWrite{{ .RandString }}() -} -` - -// const genFrunPkgTmpl = `//+build codecgen -const genFrunPkgTmpl = ` -package {{ $.PackageName }} - -import ( - {{ if not .CodecPkgFiles }}{{ .CodecPkgName }} "{{ .CodecImportPath }}"{{ end }} - "os" - "reflect" - "bytes" - "strings" - "go/format" -) - -func CodecGenTempWrite{{ .RandString }}() { - fout, err := os.Create("{{ .OutFile }}") - if err != nil { - panic(err) - } - defer fout.Close() - var out bytes.Buffer - - var typs []reflect.Type -{{ range $index, $element := .Types }} - var t{{ $index }} {{ . }} - typs = append(typs, reflect.TypeOf(t{{ $index }})) -{{ end }} - {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}Gen(&out, "{{ .BuildTag }}", "{{ .PackageName }}", "{{ .RandString }}", {{ .UseUnsafe }}, {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}NewTypeInfos(strings.Split("{{ .StructTags }}", ",")), typs...) - bout, err := format.Source(out.Bytes()) - if err != nil { - fout.Write(out.Bytes()) - panic(err) - } - fout.Write(bout) -} - -` - -// Generate is given a list of *.go files to parse, and an output file (fout). -// -// It finds all types T in the files, and it creates 2 tmp files (frun). -// - main package file passed to 'go run' -// - package level file which calls *genRunner.Selfer to write Selfer impls for each T. -// We use a package level file so that it can reference unexported types in the package being worked on. -// Tool then executes: "go run __frun__" which creates fout. -// fout contains Codec(En|De)codeSelf implementations for every type T. -// -func Generate(outfile, buildTag, codecPkgPath string, uid int64, useUnsafe bool, goRunTag string, - st string, regexName *regexp.Regexp, deleteTempFile bool, infiles ...string) (err error) { - // For each file, grab AST, find each type, and write a call to it. - if len(infiles) == 0 { - return - } - if outfile == "" || codecPkgPath == "" { - err = errors.New("outfile and codec package path cannot be blank") - return - } - if uid < 0 { - uid = -uid - } - if uid == 0 { - rr := rand.New(rand.NewSource(time.Now().UnixNano())) - uid = 101 + rr.Int63n(9777) - } - // We have to parse dir for package, before opening the temp file for writing (else ImportDir fails). - // Also, ImportDir(...) must take an absolute path. - lastdir := filepath.Dir(outfile) - absdir, err := filepath.Abs(lastdir) - if err != nil { - return - } - pkg, err := build.Default.ImportDir(absdir, build.AllowBinary) - if err != nil { - return - } - type tmplT struct { - CodecPkgName string - CodecImportPath string - ImportPath string - OutFile string - PackageName string - RandString string - BuildTag string - StructTags string - Types []string - CodecPkgFiles bool - UseUnsafe bool - } - tv := tmplT{ - CodecPkgName: genCodecPkg, - OutFile: outfile, - CodecImportPath: codecPkgPath, - BuildTag: buildTag, - UseUnsafe: useUnsafe, - RandString: strconv.FormatInt(uid, 10), - StructTags: st, - } - tv.ImportPath = pkg.ImportPath - if tv.ImportPath == tv.CodecImportPath { - tv.CodecPkgFiles = true - tv.CodecPkgName = "codec" - } - astfiles := make([]*ast.File, len(infiles)) - for i, infile := range infiles { - if filepath.Dir(infile) != lastdir { - err = errors.New("in files must all be in same directory as outfile") - return - } - fset := token.NewFileSet() - astfiles[i], err = parser.ParseFile(fset, infile, nil, 0) - if err != nil { - return - } - if i == 0 { - tv.PackageName = astfiles[i].Name.Name - if tv.PackageName == "main" { - // codecgen cannot be run on types in the 'main' package. - // A temporary 'main' package must be created, and should reference the fully built - // package containing the types. - // Also, the temporary main package will conflict with the main package which already has a main method. - err = errors.New("codecgen cannot be run on types in the 'main' package") - return - } - } - } - - for _, f := range astfiles { - for _, d := range f.Decls { - if gd, ok := d.(*ast.GenDecl); ok { - for _, dd := range gd.Specs { - if td, ok := dd.(*ast.TypeSpec); ok { - // if len(td.Name.Name) == 0 || td.Name.Name[0] > 'Z' || td.Name.Name[0] < 'A' { - if len(td.Name.Name) == 0 { - continue - } - - // only generate for: - // struct: StructType - // primitives (numbers, bool, string): Ident - // map: MapType - // slice, array: ArrayType - // chan: ChanType - // do not generate: - // FuncType, InterfaceType, StarExpr (ptr), etc - switch td.Type.(type) { - case *ast.StructType, *ast.Ident, *ast.MapType, *ast.ArrayType, *ast.ChanType: - if regexName.FindStringIndex(td.Name.Name) != nil { - tv.Types = append(tv.Types, td.Name.Name) - } - } - } - } - } - } - } - - if len(tv.Types) == 0 { - return - } - - // we cannot use ioutil.TempFile, because we cannot guarantee the file suffix (.go). - // Also, we cannot create file in temp directory, - // because go run will not work (as it needs to see the types here). - // Consequently, create the temp file in the current directory, and remove when done. - - // frun, err = ioutil.TempFile("", "codecgen-") - // frunName := filepath.Join(os.TempDir(), "codecgen-"+strconv.FormatInt(time.Now().UnixNano(), 10)+".go") - - frunMainName := "codecgen-main-" + tv.RandString + ".generated.go" - frunPkgName := "codecgen-pkg-" + tv.RandString + ".generated.go" - if deleteTempFile { - defer os.Remove(frunMainName) - defer os.Remove(frunPkgName) - } - // var frunMain, frunPkg *os.File - if _, err = gen1(frunMainName, genFrunMainTmpl, &tv); err != nil { - return - } - if _, err = gen1(frunPkgName, genFrunPkgTmpl, &tv); err != nil { - return - } - - // remove outfile, so "go run ..." will not think that types in outfile already exist. - os.Remove(outfile) - - // execute go run frun - cmd := exec.Command("go", "run", "-tags="+goRunTag, frunMainName) //, frunPkg.Name()) - var buf bytes.Buffer - cmd.Stdout = &buf - cmd.Stderr = &buf - if err = cmd.Run(); err != nil { - err = fmt.Errorf("error running 'go run %s': %v, console: %s", - frunMainName, err, buf.Bytes()) - return - } - os.Stdout.Write(buf.Bytes()) - return -} - -func gen1(frunName, tmplStr string, tv interface{}) (frun *os.File, err error) { - os.Remove(frunName) - if frun, err = os.Create(frunName); err != nil { - return - } - defer frun.Close() - - t := template.New("") - if t, err = t.Parse(tmplStr); err != nil { - return - } - bw := bufio.NewWriter(frun) - if err = t.Execute(bw, tv); err != nil { - return - } - if err = bw.Flush(); err != nil { - return - } - return -} - -func main() { - o := flag.String("o", "", "out file") - c := flag.String("c", genCodecPath, "codec path") - t := flag.String("t", "", "build tag to put in file") - r := flag.String("r", ".*", "regex for type name to match") - rt := flag.String("rt", "", "tags for go run") - st := flag.String("st", "codec,json", "struct tag keys to introspect") - x := flag.Bool("x", false, "keep temp file") - u := flag.Bool("u", false, "Use unsafe, e.g. to avoid unnecessary allocation on []byte->string") - d := flag.Int64("d", 0, "random identifier for use in generated code") - flag.Parse() - if err := Generate(*o, *t, *c, *d, *u, *rt, *st, - regexp.MustCompile(*r), !*x, flag.Args()...); err != nil { - fmt.Fprintf(os.Stderr, "codecgen error: %v\n", err) - os.Exit(1) - } -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/z.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/z.go deleted file mode 100644 index e120a4eb9..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen/z.go +++ /dev/null @@ -1,3 +0,0 @@ -package main - -const genCodecPath = "github.com/ugorji/go/codec" diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go deleted file mode 100644 index a73497e91..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go +++ /dev/null @@ -1,24 +0,0 @@ -//+build x,codecgen - -package codec - -import ( - "fmt" - "testing" -) - -func _TestCodecgenJson1(t *testing.T) { - // This is just a simplistic test for codecgen. - // It is typically disabled. We only enable it for debugging purposes. - const callCodecgenDirect bool = true - v := newTestStruc(2, false, !testSkipIntf, false) - var bs []byte - e := NewEncoderBytes(&bs, testJsonH) - if callCodecgenDirect { - v.CodecEncodeSelf(e) - e.w.atEndOfEncode() - } else { - e.MustEncode(v) - } - fmt.Printf("%s\n", bs) -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go index b3b99f036..7e56f1eca 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/decode.go @@ -583,14 +583,16 @@ func (f *decFnInfo) kInterfaceNaked() (rvn reflect.Value) { if d.mtid == 0 || d.mtid == mapIntfIntfTypId { l := len(n.ms) n.ms = append(n.ms, nil) - d.decode(&n.ms[l]) - rvn = reflect.ValueOf(&n.ms[l]).Elem() + var v2 interface{} = &n.ms[l] + d.decode(v2) + rvn = reflect.ValueOf(v2).Elem() n.ms = n.ms[:l] } else if d.mtid == mapStrIntfTypId { // for json performance l := len(n.ns) n.ns = append(n.ns, nil) - d.decode(&n.ns[l]) - rvn = reflect.ValueOf(&n.ns[l]).Elem() + var v2 interface{} = &n.ns[l] + d.decode(v2) + rvn = reflect.ValueOf(v2).Elem() n.ns = n.ns[:l] } else { rvn = reflect.New(d.h.MapType).Elem() @@ -601,8 +603,9 @@ func (f *decFnInfo) kInterfaceNaked() (rvn reflect.Value) { if d.stid == 0 || d.stid == intfSliceTypId { l := len(n.ss) n.ss = append(n.ss, nil) - d.decode(&n.ss[l]) - rvn = reflect.ValueOf(&n.ss[l]).Elem() + var v2 interface{} = &n.ss[l] + d.decode(v2) + rvn = reflect.ValueOf(v2).Elem() n.ss = n.ss[:l] } else { rvn = reflect.New(d.h.SliceType).Elem() @@ -615,9 +618,9 @@ func (f *decFnInfo) kInterfaceNaked() (rvn reflect.Value) { l := len(n.is) n.is = append(n.is, nil) v2 := &n.is[l] - n.is = n.is[:l] d.decode(v2) v = *v2 + n.is = n.is[:l] } bfn := d.h.getExtForTag(tag) if bfn == nil { @@ -1453,8 +1456,8 @@ func (d *Decoder) swallow() { l := len(n.is) n.is = append(n.is, nil) v2 := &n.is[l] - n.is = n.is[:l] d.decode(v2) + n.is = n.is[:l] } } } @@ -1862,6 +1865,7 @@ func (d *Decoder) intern(s string) { } } +// nextValueBytes returns the next value in the stream as a set of bytes. func (d *Decoder) nextValueBytes() []byte { d.d.uncacheRead() d.r.track() diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go index 99af6fa55..a874c744b 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/encode.go @@ -110,6 +110,15 @@ type EncodeOptions struct { // Canonical bool + // CheckCircularRef controls whether we check for circular references + // and error fast during an encode. + // + // If enabled, an error is received if a pointer to a struct + // references itself either directly or through one of its fields (iteratively). + // + // This is opt-in, as there may be a performance hit to checking circular references. + CheckCircularRef bool + // AsSymbols defines what should be encoded as symbols. // // Encoding as symbols can reduce the encoded size significantly. @@ -464,7 +473,7 @@ func (f *encFnInfo) kSlice(rv reflect.Value) { for j := 0; j < l; j++ { if cr != nil { if ti.mbs { - if l%2 == 0 { + if j%2 == 0 { cr.sendContainerState(containerMapKey) } else { cr.sendContainerState(containerMapValue) @@ -503,7 +512,7 @@ func (f *encFnInfo) kStruct(rv reflect.Value) { newlen := len(fti.sfi) // Use sync.Pool to reduce allocating slices unnecessarily. - // The cost of the occasional locking is less than the cost of new allocation. + // The cost of sync.Pool is less than the cost of new allocation. pool, poolv, fkvs := encStructPoolGet(newlen) // if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct) @@ -514,11 +523,6 @@ func (f *encFnInfo) kStruct(rv reflect.Value) { var kv stringRv for _, si := range tisfi { kv.r = si.field(rv, false) - // if si.i != -1 { - // rvals[newlen] = rv.Field(int(si.i)) - // } else { - // rvals[newlen] = rv.FieldByIndex(si.is) - // } if toMap { if si.omitEmpty && isEmptyValue(kv.r) { continue @@ -596,13 +600,15 @@ func (f *encFnInfo) kStruct(rv reflect.Value) { // f.e.encodeValue(rv.Elem()) // } -func (f *encFnInfo) kInterface(rv reflect.Value) { - if rv.IsNil() { - f.e.e.EncodeNil() - return - } - f.e.encodeValue(rv.Elem(), nil) -} +// func (f *encFnInfo) kInterface(rv reflect.Value) { +// println("kInterface called") +// debug.PrintStack() +// if rv.IsNil() { +// f.e.e.EncodeNil() +// return +// } +// f.e.encodeValue(rv.Elem(), nil) +// } func (f *encFnInfo) kMap(rv reflect.Value) { ee := f.e.e @@ -877,6 +883,7 @@ type Encoder struct { // as the handler MAY need to do some coordination. w encWriter s []encRtidFn + ci set be bool // is binary encoding js bool // is json handle @@ -1133,20 +1140,23 @@ func (e *Encoder) encode(iv interface{}) { } } -func (e *Encoder) encodeI(iv interface{}, checkFastpath, checkCodecSelfer bool) { - if rv, proceed := e.preEncodeValue(reflect.ValueOf(iv)); proceed { - rt := rv.Type() - rtid := reflect.ValueOf(rt).Pointer() - fn := e.getEncFn(rtid, rt, checkFastpath, checkCodecSelfer) - fn.f(&fn.i, rv) - } -} - -func (e *Encoder) preEncodeValue(rv reflect.Value) (rv2 reflect.Value, proceed bool) { +func (e *Encoder) preEncodeValue(rv reflect.Value) (rv2 reflect.Value, sptr uintptr, proceed bool) { // use a goto statement instead of a recursive function for ptr/interface. TOP: switch rv.Kind() { - case reflect.Ptr, reflect.Interface: + case reflect.Ptr: + if rv.IsNil() { + e.e.EncodeNil() + return + } + rv = rv.Elem() + if e.h.CheckCircularRef && rv.Kind() == reflect.Struct { + // TODO: Movable pointers will be an issue here. Future problem. + sptr = rv.UnsafeAddr() + break TOP + } + goto TOP + case reflect.Interface: if rv.IsNil() { e.e.EncodeNil() return @@ -1163,18 +1173,40 @@ TOP: return } - return rv, true + proceed = true + rv2 = rv + return +} + +func (e *Encoder) doEncodeValue(rv reflect.Value, fn *encFn, sptr uintptr, + checkFastpath, checkCodecSelfer bool) { + if sptr != 0 { + if (&e.ci).add(sptr) { + e.errorf("circular reference found: # %d", sptr) + } + } + if fn == nil { + rt := rv.Type() + rtid := reflect.ValueOf(rt).Pointer() + // fn = e.getEncFn(rtid, rt, true, true) + fn = e.getEncFn(rtid, rt, checkFastpath, checkCodecSelfer) + } + fn.f(&fn.i, rv) + if sptr != 0 { + (&e.ci).remove(sptr) + } +} + +func (e *Encoder) encodeI(iv interface{}, checkFastpath, checkCodecSelfer bool) { + if rv, sptr, proceed := e.preEncodeValue(reflect.ValueOf(iv)); proceed { + e.doEncodeValue(rv, nil, sptr, checkFastpath, checkCodecSelfer) + } } func (e *Encoder) encodeValue(rv reflect.Value, fn *encFn) { // if a valid fn is passed, it MUST BE for the dereferenced type of rv - if rv, proceed := e.preEncodeValue(rv); proceed { - if fn == nil { - rt := rv.Type() - rtid := reflect.ValueOf(rt).Pointer() - fn = e.getEncFn(rtid, rt, true, true) - } - fn.f(&fn.i, rv) + if rv, sptr, proceed := e.preEncodeValue(rv); proceed { + e.doEncodeValue(rv, fn, sptr, true, true) } } @@ -1234,7 +1266,7 @@ func (e *Encoder) getEncFn(rtid uintptr, rt reflect.Type, checkFastpath, checkCo } else { rk := rt.Kind() if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) { - if rt.PkgPath() == "" { + if rt.PkgPath() == "" { // un-named slice or map if idx := fastpathAV.index(rtid); idx != -1 { fn.f = fastpathAV[idx].encfn } @@ -1284,10 +1316,11 @@ func (e *Encoder) getEncFn(rtid uintptr, rt reflect.Type, checkFastpath, checkCo fn.f = (*encFnInfo).kSlice case reflect.Struct: fn.f = (*encFnInfo).kStruct + // reflect.Ptr and reflect.Interface are handled already by preEncodeValue // case reflect.Ptr: // fn.f = (*encFnInfo).kPtr - case reflect.Interface: - fn.f = (*encFnInfo).kInterface + // case reflect.Interface: + // fn.f = (*encFnInfo).kInterface case reflect.Map: fn.f = (*encFnInfo).kMap default: @@ -1353,25 +1386,6 @@ func encStructPoolGet(newlen int) (p *sync.Pool, v interface{}, s []stringRv) { // panic(errors.New("encStructPoolLen must be equal to 4")) // defensive, in case it is changed // } // idxpool := newlen / 8 - - // if pool == nil { - // fkvs = make([]stringRv, newlen) - // } else { - // poolv = pool.Get() - // switch vv := poolv.(type) { - // case *[8]stringRv: - // fkvs = vv[:newlen] - // case *[16]stringRv: - // fkvs = vv[:newlen] - // case *[32]stringRv: - // fkvs = vv[:newlen] - // case *[64]stringRv: - // fkvs = vv[:newlen] - // case *[128]stringRv: - // fkvs = vv[:newlen] - // } - // } - if newlen <= 8 { p = &encStructPool[0] v = p.Get() diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go index d968a500f..cf6e00df2 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.generated.go @@ -3124,7 +3124,11 @@ func fastpathEncodeTypeSwitchMap(iv interface{}, e *Encoder) bool { // -- -- fast path functions func (f *encFnInfo) fastpathEncSliceIntfR(rv reflect.Value) { - fastpathTV.EncSliceIntfV(rv.Interface().([]interface{}), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceIntfV(rv.Interface().([]interface{}), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceIntfV(rv.Interface().([]interface{}), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceIntfV(v []interface{}, checkNil bool, e *Encoder) { ee := e.e @@ -3145,8 +3149,39 @@ func (_ fastpathT) EncSliceIntfV(v []interface{}, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceIntfV(v []interface{}, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + e.encode(v2) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceStringR(rv reflect.Value) { - fastpathTV.EncSliceStringV(rv.Interface().([]string), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceStringV(rv.Interface().([]string), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceStringV(rv.Interface().([]string), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceStringV(v []string, checkNil bool, e *Encoder) { ee := e.e @@ -3167,8 +3202,39 @@ func (_ fastpathT) EncSliceStringV(v []string, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceStringV(v []string, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeString(c_UTF8, v2) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceFloat32R(rv reflect.Value) { - fastpathTV.EncSliceFloat32V(rv.Interface().([]float32), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceFloat32V(rv.Interface().([]float32), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceFloat32V(rv.Interface().([]float32), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceFloat32V(v []float32, checkNil bool, e *Encoder) { ee := e.e @@ -3189,8 +3255,39 @@ func (_ fastpathT) EncSliceFloat32V(v []float32, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceFloat32V(v []float32, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeFloat32(v2) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceFloat64R(rv reflect.Value) { - fastpathTV.EncSliceFloat64V(rv.Interface().([]float64), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceFloat64V(rv.Interface().([]float64), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceFloat64V(rv.Interface().([]float64), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceFloat64V(v []float64, checkNil bool, e *Encoder) { ee := e.e @@ -3211,8 +3308,39 @@ func (_ fastpathT) EncSliceFloat64V(v []float64, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceFloat64V(v []float64, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeFloat64(v2) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceUintR(rv reflect.Value) { - fastpathTV.EncSliceUintV(rv.Interface().([]uint), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceUintV(rv.Interface().([]uint), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceUintV(rv.Interface().([]uint), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceUintV(v []uint, checkNil bool, e *Encoder) { ee := e.e @@ -3233,8 +3361,39 @@ func (_ fastpathT) EncSliceUintV(v []uint, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceUintV(v []uint, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeUint(uint64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceUint16R(rv reflect.Value) { - fastpathTV.EncSliceUint16V(rv.Interface().([]uint16), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceUint16V(rv.Interface().([]uint16), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceUint16V(rv.Interface().([]uint16), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceUint16V(v []uint16, checkNil bool, e *Encoder) { ee := e.e @@ -3255,8 +3414,39 @@ func (_ fastpathT) EncSliceUint16V(v []uint16, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceUint16V(v []uint16, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeUint(uint64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceUint32R(rv reflect.Value) { - fastpathTV.EncSliceUint32V(rv.Interface().([]uint32), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceUint32V(rv.Interface().([]uint32), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceUint32V(rv.Interface().([]uint32), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceUint32V(v []uint32, checkNil bool, e *Encoder) { ee := e.e @@ -3277,8 +3467,39 @@ func (_ fastpathT) EncSliceUint32V(v []uint32, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceUint32V(v []uint32, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeUint(uint64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceUint64R(rv reflect.Value) { - fastpathTV.EncSliceUint64V(rv.Interface().([]uint64), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceUint64V(rv.Interface().([]uint64), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceUint64V(rv.Interface().([]uint64), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceUint64V(v []uint64, checkNil bool, e *Encoder) { ee := e.e @@ -3299,8 +3520,39 @@ func (_ fastpathT) EncSliceUint64V(v []uint64, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceUint64V(v []uint64, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeUint(uint64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceUintptrR(rv reflect.Value) { - fastpathTV.EncSliceUintptrV(rv.Interface().([]uintptr), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceUintptrV(rv.Interface().([]uintptr), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceUintptrV(rv.Interface().([]uintptr), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceUintptrV(v []uintptr, checkNil bool, e *Encoder) { ee := e.e @@ -3321,8 +3573,39 @@ func (_ fastpathT) EncSliceUintptrV(v []uintptr, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceUintptrV(v []uintptr, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + e.encode(v2) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceIntR(rv reflect.Value) { - fastpathTV.EncSliceIntV(rv.Interface().([]int), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceIntV(rv.Interface().([]int), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceIntV(rv.Interface().([]int), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceIntV(v []int, checkNil bool, e *Encoder) { ee := e.e @@ -3343,8 +3626,39 @@ func (_ fastpathT) EncSliceIntV(v []int, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceIntV(v []int, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeInt(int64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceInt8R(rv reflect.Value) { - fastpathTV.EncSliceInt8V(rv.Interface().([]int8), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceInt8V(rv.Interface().([]int8), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceInt8V(rv.Interface().([]int8), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceInt8V(v []int8, checkNil bool, e *Encoder) { ee := e.e @@ -3365,8 +3679,39 @@ func (_ fastpathT) EncSliceInt8V(v []int8, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceInt8V(v []int8, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeInt(int64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceInt16R(rv reflect.Value) { - fastpathTV.EncSliceInt16V(rv.Interface().([]int16), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceInt16V(rv.Interface().([]int16), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceInt16V(rv.Interface().([]int16), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceInt16V(v []int16, checkNil bool, e *Encoder) { ee := e.e @@ -3387,8 +3732,39 @@ func (_ fastpathT) EncSliceInt16V(v []int16, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceInt16V(v []int16, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeInt(int64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceInt32R(rv reflect.Value) { - fastpathTV.EncSliceInt32V(rv.Interface().([]int32), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceInt32V(rv.Interface().([]int32), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceInt32V(rv.Interface().([]int32), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceInt32V(v []int32, checkNil bool, e *Encoder) { ee := e.e @@ -3409,8 +3785,39 @@ func (_ fastpathT) EncSliceInt32V(v []int32, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceInt32V(v []int32, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeInt(int64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceInt64R(rv reflect.Value) { - fastpathTV.EncSliceInt64V(rv.Interface().([]int64), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceInt64V(rv.Interface().([]int64), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceInt64V(rv.Interface().([]int64), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceInt64V(v []int64, checkNil bool, e *Encoder) { ee := e.e @@ -3431,8 +3838,39 @@ func (_ fastpathT) EncSliceInt64V(v []int64, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceInt64V(v []int64, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeInt(int64(v2)) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncSliceBoolR(rv reflect.Value) { - fastpathTV.EncSliceBoolV(rv.Interface().([]bool), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.EncAsMapSliceBoolV(rv.Interface().([]bool), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.EncSliceBoolV(rv.Interface().([]bool), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) EncSliceBoolV(v []bool, checkNil bool, e *Encoder) { ee := e.e @@ -3453,6 +3891,33 @@ func (_ fastpathT) EncSliceBoolV(v []bool, checkNil bool, e *Encoder) { } } +func (_ fastpathT) EncAsMapSliceBoolV(v []bool, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + ee.EncodeBool(v2) + } + if cr != nil { + cr.sendContainerState(containerMapEnd) + } +} + func (f *encFnInfo) fastpathEncMapIntfIntfR(rv reflect.Value) { fastpathTV.EncMapIntfIntfV(rv.Interface().(map[interface{}]interface{}), fastpathCheckNilFalse, f.e) } @@ -17712,7 +18177,7 @@ func (_ fastpathT) DecSliceIntfV(v []interface{}, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -17771,7 +18236,7 @@ func (_ fastpathT) DecSliceIntfV(v []interface{}, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]interface{}, 1, 4) @@ -17846,7 +18311,7 @@ func (_ fastpathT) DecSliceStringV(v []string, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -17905,7 +18370,7 @@ func (_ fastpathT) DecSliceStringV(v []string, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]string, 1, 4) @@ -17979,7 +18444,7 @@ func (_ fastpathT) DecSliceFloat32V(v []float32, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18038,7 +18503,7 @@ func (_ fastpathT) DecSliceFloat32V(v []float32, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]float32, 1, 4) @@ -18112,7 +18577,7 @@ func (_ fastpathT) DecSliceFloat64V(v []float64, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18171,7 +18636,7 @@ func (_ fastpathT) DecSliceFloat64V(v []float64, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]float64, 1, 4) @@ -18245,7 +18710,7 @@ func (_ fastpathT) DecSliceUintV(v []uint, checkNil bool, canChange bool, d *Dec changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18304,7 +18769,7 @@ func (_ fastpathT) DecSliceUintV(v []uint, checkNil bool, canChange bool, d *Dec changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]uint, 1, 4) @@ -18378,7 +18843,7 @@ func (_ fastpathT) DecSliceUint16V(v []uint16, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18437,7 +18902,7 @@ func (_ fastpathT) DecSliceUint16V(v []uint16, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]uint16, 1, 4) @@ -18511,7 +18976,7 @@ func (_ fastpathT) DecSliceUint32V(v []uint32, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18570,7 +19035,7 @@ func (_ fastpathT) DecSliceUint32V(v []uint32, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]uint32, 1, 4) @@ -18644,7 +19109,7 @@ func (_ fastpathT) DecSliceUint64V(v []uint64, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18703,7 +19168,7 @@ func (_ fastpathT) DecSliceUint64V(v []uint64, checkNil bool, canChange bool, d changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]uint64, 1, 4) @@ -18777,7 +19242,7 @@ func (_ fastpathT) DecSliceUintptrV(v []uintptr, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18836,7 +19301,7 @@ func (_ fastpathT) DecSliceUintptrV(v []uintptr, checkNil bool, canChange bool, changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]uintptr, 1, 4) @@ -18910,7 +19375,7 @@ func (_ fastpathT) DecSliceIntV(v []int, checkNil bool, canChange bool, d *Decod changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -18969,7 +19434,7 @@ func (_ fastpathT) DecSliceIntV(v []int, checkNil bool, canChange bool, d *Decod changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]int, 1, 4) @@ -19043,7 +19508,7 @@ func (_ fastpathT) DecSliceInt8V(v []int8, checkNil bool, canChange bool, d *Dec changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -19102,7 +19567,7 @@ func (_ fastpathT) DecSliceInt8V(v []int8, checkNil bool, canChange bool, d *Dec changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]int8, 1, 4) @@ -19176,7 +19641,7 @@ func (_ fastpathT) DecSliceInt16V(v []int16, checkNil bool, canChange bool, d *D changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -19235,7 +19700,7 @@ func (_ fastpathT) DecSliceInt16V(v []int16, checkNil bool, canChange bool, d *D changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]int16, 1, 4) @@ -19309,7 +19774,7 @@ func (_ fastpathT) DecSliceInt32V(v []int32, checkNil bool, canChange bool, d *D changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -19368,7 +19833,7 @@ func (_ fastpathT) DecSliceInt32V(v []int32, checkNil bool, canChange bool, d *D changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]int32, 1, 4) @@ -19442,7 +19907,7 @@ func (_ fastpathT) DecSliceInt64V(v []int64, checkNil bool, canChange bool, d *D changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -19501,7 +19966,7 @@ func (_ fastpathT) DecSliceInt64V(v []int64, checkNil bool, canChange bool, d *D changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]int64, 1, 4) @@ -19575,7 +20040,7 @@ func (_ fastpathT) DecSliceBoolV(v []bool, checkNil bool, canChange bool, d *Dec changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -19634,7 +20099,7 @@ func (_ fastpathT) DecSliceBoolV(v []bool, checkNil bool, canChange bool, d *Dec changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]bool, 1, 4) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl index 58cc6df4c..04c173fba 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/fast-path.go.tmpl @@ -165,7 +165,11 @@ func fastpathEncodeTypeSwitchMap(iv interface{}, e *Encoder) bool { {{range .Values}}{{if not .Primitive}}{{if not .MapKey }} func (f *encFnInfo) {{ .MethodNamePfx "fastpathEnc" false }}R(rv reflect.Value) { - fastpathTV.{{ .MethodNamePfx "Enc" false }}V(rv.Interface().([]{{ .Elem }}), fastpathCheckNilFalse, f.e) + if f.ti.mbs { + fastpathTV.{{ .MethodNamePfx "EncAsMap" false }}V(rv.Interface().([]{{ .Elem }}), fastpathCheckNilFalse, f.e) + } else { + fastpathTV.{{ .MethodNamePfx "Enc" false }}V(rv.Interface().([]{{ .Elem }}), fastpathCheckNilFalse, f.e) + } } func (_ fastpathT) {{ .MethodNamePfx "Enc" false }}V(v []{{ .Elem }}, checkNil bool, e *Encoder) { ee := e.e @@ -182,6 +186,31 @@ func (_ fastpathT) {{ .MethodNamePfx "Enc" false }}V(v []{{ .Elem }}, checkNil b if cr != nil { cr.sendContainerState(containerArrayEnd) }{{/* ee.EncodeEnd() */}} } +func (_ fastpathT) {{ .MethodNamePfx "EncAsMap" false }}V(v []{{ .Elem }}, checkNil bool, e *Encoder) { + ee := e.e + cr := e.cr + if checkNil && v == nil { + ee.EncodeNil() + return + } + if len(v)%2 == 1 { + e.errorf("mapBySlice requires even slice length, but got %v", len(v)) + return + } + ee.EncodeMapStart(len(v) / 2) + for j, v2 := range v { + if cr != nil { + if j%2 == 0 { + cr.sendContainerState(containerMapKey) + } else { + cr.sendContainerState(containerMapValue) + } + } + {{ encmd .Elem "v2"}} + } + if cr != nil { cr.sendContainerState(containerMapEnd) } +} + {{end}}{{end}}{{end}} {{range .Values}}{{if not .Primitive}}{{if .MapKey }} @@ -328,7 +357,7 @@ func (_ fastpathT) {{ .MethodNamePfx "Dec" false }}V(v []{{ .Elem }}, checkNil b changed = true } slh.End() - return + return v, changed } if containerLenS > 0 { @@ -391,7 +420,7 @@ func (_ fastpathT) {{ .MethodNamePfx "Dec" false }}V(v []{{ .Elem }}, checkNil b changed = true } slh.End() - return + return v, changed } if cap(v) == 0 { v = make([]{{ .Elem }}, 1, 4) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl index 2caae5bfd..32df54144 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen-dec-array.go.tmpl @@ -1,6 +1,7 @@ {{var "v"}} := {{if not isArray}}*{{end}}{{ .Varname }} -{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}} +{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}}{{if not isArray}} var {{var "c"}} bool {{/* // changed */}} +_ = {{var "c"}}{{end}} if {{var "l"}} == 0 { {{if isSlice }}if {{var "v"}} == nil { {{var "v"}} = []{{ .Typ }}{} @@ -26,6 +27,8 @@ if {{var "l"}} == 0 { } {{ else }} var {{var "rr"}}, {{var "rl"}} int {{/* // num2read, length of slice/array/chan */}} var {{var "rt"}} bool {{/* truncated */}} + _, _ = {{var "rl"}}, {{var "rt"}} + {{var "rr"}} = {{var "l"}} // len({{var "v"}}) if {{var "l"}} > cap({{var "v"}}) { {{if isArray }}z.DecArrayCannotExpand(len({{var "v"}}), {{var "l"}}) {{ else }}{{if not .Immutable }} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go index fb6f4b809..2ace97b78 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.generated.go @@ -68,8 +68,9 @@ z.DecSendContainerState(codecSelfer_containerMapEnd{{ .Sfx }}) const genDecListTmpl = ` {{var "v"}} := {{if not isArray}}*{{end}}{{ .Varname }} -{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}} +{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}}{{if not isArray}} var {{var "c"}} bool {{/* // changed */}} +_ = {{var "c"}}{{end}} if {{var "l"}} == 0 { {{if isSlice }}if {{var "v"}} == nil { {{var "v"}} = []{{ .Typ }}{} @@ -95,6 +96,8 @@ if {{var "l"}} == 0 { } {{ else }} var {{var "rr"}}, {{var "rl"}} int {{/* // num2read, length of slice/array/chan */}} var {{var "rt"}} bool {{/* truncated */}} + _, _ = {{var "rl"}}, {{var "rt"}} + {{var "rr"}} = {{var "l"}} // len({{var "v"}}) if {{var "l"}} > cap({{var "v"}}) { {{if isArray }}z.DecArrayCannotExpand(len({{var "v"}}), {{var "l"}}) {{ else }}{{if not .Immutable }} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go index a075e7c0d..ffc5aecf6 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/gen.go @@ -21,6 +21,8 @@ import ( "sync" "text/template" "time" + "unicode" + "unicode/utf8" ) // --------------------------------------------------- @@ -266,6 +268,7 @@ func Gen(w io.Writer, buildTags, pkgName, uid string, useUnsafe bool, ti *TypeIn x.line("type " + x.hn + " struct{}") x.line("") + x.varsfxreset() x.line("func init() {") x.linef("if %sGenVersion != %v {", x.cpfx, GenVersion) x.line("_, file, _, _ := runtime.Caller(0)") @@ -309,6 +312,7 @@ func Gen(w io.Writer, buildTags, pkgName, uid string, useUnsafe bool, ti *TypeIn for _, t := range x.ts { rtid := reflect.ValueOf(t).Pointer() // generate enc functions for all these slice/map types. + x.varsfxreset() x.linef("func (x %s) enc%s(v %s%s, e *%sEncoder) {", x.hn, x.genMethodNameT(t), x.arr2str(t, "*"), x.genTypeName(t), x.cpfx) x.genRequiredMethodVars(true) switch t.Kind() { @@ -323,6 +327,7 @@ func Gen(w io.Writer, buildTags, pkgName, uid string, useUnsafe bool, ti *TypeIn x.line("") // generate dec functions for all these slice/map types. + x.varsfxreset() x.linef("func (x %s) dec%s(v *%s, d *%sDecoder) {", x.hn, x.genMethodNameT(t), x.genTypeName(t), x.cpfx) x.genRequiredMethodVars(false) switch t.Kind() { @@ -377,7 +382,7 @@ func (x *genRunner) genRefPkgs(t reflect.Type) { x.imn[tpkg] = tpkg } else { x.imc++ - x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + tpkg[idx+1:] + x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + genGoIdentifier(tpkg[idx+1:], false) } } } @@ -408,6 +413,10 @@ func (x *genRunner) varsfx() string { return strconv.FormatUint(x.c, 10) } +func (x *genRunner) varsfxreset() { + x.c = 0 +} + func (x *genRunner) out(s string) { if _, err := io.WriteString(x.w, s); err != nil { panic(err) @@ -494,6 +503,7 @@ func (x *genRunner) selfer(encode bool) { // always make decode use a pointer receiver, // and structs always use a ptr receiver (encode|decode) isptr := !encode || t.Kind() == reflect.Struct + x.varsfxreset() fnSigPfx := "func (x " if isptr { fnSigPfx += "*" @@ -566,9 +576,28 @@ func (x *genRunner) xtraSM(varname string, encode bool, t reflect.Type) { } else { x.linef("h.dec%s((*%s)(%s), d)", x.genMethodNameT(t), x.genTypeName(t), varname) } - if _, ok := x.tm[t]; !ok { - x.tm[t] = struct{}{} - x.ts = append(x.ts, t) + x.registerXtraT(t) +} + +func (x *genRunner) registerXtraT(t reflect.Type) { + // recursively register the types + if _, ok := x.tm[t]; ok { + return + } + var tkey reflect.Type + switch t.Kind() { + case reflect.Chan, reflect.Slice, reflect.Array: + case reflect.Map: + tkey = t.Key() + default: + return + } + x.tm[t] = struct{}{} + x.ts = append(x.ts, t) + // check if this refers to any xtra types eg. a slice of array: add the array + x.registerXtraT(t.Elem()) + if tkey != nil { + x.registerXtraT(tkey) } } @@ -608,22 +637,33 @@ func (x *genRunner) encVar(varname string, t reflect.Type) { } -// enc will encode a variable (varname) of type T, -// except t is of kind reflect.Struct or reflect.Array, wherein varname is of type *T (to prevent copying) +// enc will encode a variable (varname) of type t, +// except t is of kind reflect.Struct or reflect.Array, wherein varname is of type ptrTo(T) (to prevent copying) func (x *genRunner) enc(varname string, t reflect.Type) { - // varName here must be to a pointer to a struct/array, or to a value directly. rtid := reflect.ValueOf(t).Pointer() // We call CodecEncodeSelf if one of the following are honored: // - the type already implements Selfer, call that // - the type has a Selfer implementation just created, use that // - the type is in the list of the ones we will generate for, but it is not currently being generated + mi := x.varsfx() tptr := reflect.PtrTo(t) tk := t.Kind() if x.checkForSelfer(t, varname) { - if t.Implements(selferTyp) || (tptr.Implements(selferTyp) && (tk == reflect.Array || tk == reflect.Struct)) { - x.line(varname + ".CodecEncodeSelf(e)") - return + if tk == reflect.Array || tk == reflect.Struct { // varname is of type *T + if tptr.Implements(selferTyp) || t.Implements(selferTyp) { + x.line(varname + ".CodecEncodeSelf(e)") + return + } + } else { // varname is of type T + if t.Implements(selferTyp) { + x.line(varname + ".CodecEncodeSelf(e)") + return + } else if tptr.Implements(selferTyp) { + x.linef("%ssf%s := &%s", genTempVarPfx, mi, varname) + x.linef("%ssf%s.CodecEncodeSelf(e)", genTempVarPfx, mi) + return + } } if _, ok := x.te[rtid]; ok { @@ -653,7 +693,6 @@ func (x *genRunner) enc(varname string, t reflect.Type) { // check if // - type is RawExt // - the type implements (Text|JSON|Binary)(Unm|M)arshal - mi := x.varsfx() x.linef("%sm%s := z.EncBinary()", genTempVarPfx, mi) x.linef("_ = %sm%s", genTempVarPfx, mi) x.line("if false {") //start if block @@ -676,15 +715,31 @@ func (x *genRunner) enc(varname string, t reflect.Type) { // first check if extensions are configued, before doing the interface conversion x.linef("} else if z.HasExtensions() && z.EncExt(%s) {", varname) } - if t.Implements(binaryMarshalerTyp) || tptr.Implements(binaryMarshalerTyp) { - x.linef("} else if %sm%s { z.EncBinaryMarshal(%v) ", genTempVarPfx, mi, varname) + if tk == reflect.Array || tk == reflect.Struct { // varname is of type *T + if t.Implements(binaryMarshalerTyp) || tptr.Implements(binaryMarshalerTyp) { + x.linef("} else if %sm%s { z.EncBinaryMarshal(%v) ", genTempVarPfx, mi, varname) + } + if t.Implements(jsonMarshalerTyp) || tptr.Implements(jsonMarshalerTyp) { + x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", genTempVarPfx, mi, varname) + } else if t.Implements(textMarshalerTyp) || tptr.Implements(textMarshalerTyp) { + x.linef("} else if !%sm%s { z.EncTextMarshal(%v) ", genTempVarPfx, mi, varname) + } + } else { // varname is of type T + if t.Implements(binaryMarshalerTyp) { + x.linef("} else if %sm%s { z.EncBinaryMarshal(%v) ", genTempVarPfx, mi, varname) + } else if tptr.Implements(binaryMarshalerTyp) { + x.linef("} else if %sm%s { z.EncBinaryMarshal(&%v) ", genTempVarPfx, mi, varname) + } + if t.Implements(jsonMarshalerTyp) { + x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", genTempVarPfx, mi, varname) + } else if tptr.Implements(jsonMarshalerTyp) { + x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(&%v) ", genTempVarPfx, mi, varname) + } else if t.Implements(textMarshalerTyp) { + x.linef("} else if !%sm%s { z.EncTextMarshal(%v) ", genTempVarPfx, mi, varname) + } else if tptr.Implements(textMarshalerTyp) { + x.linef("} else if !%sm%s { z.EncTextMarshal(&%v) ", genTempVarPfx, mi, varname) + } } - if t.Implements(jsonMarshalerTyp) || tptr.Implements(jsonMarshalerTyp) { - x.linef("} else if !%sm%s && z.IsJSONHandle() { z.EncJSONMarshal(%v) ", genTempVarPfx, mi, varname) - } else if t.Implements(textMarshalerTyp) || tptr.Implements(textMarshalerTyp) { - x.linef("} else if !%sm%s { z.EncTextMarshal(%v) ", genTempVarPfx, mi, varname) - } - x.line("} else {") switch t.Kind() { @@ -1020,6 +1075,8 @@ func (x *genRunner) decVar(varname string, t reflect.Type, canBeNil bool) { } } +// dec will decode a variable (varname) of type ptrTo(t). +// t is always a basetype (i.e. not of kind reflect.Ptr). func (x *genRunner) dec(varname string, t reflect.Type) { // assumptions: // - the varname is to a pointer already. No need to take address of it @@ -1592,6 +1649,26 @@ func genImportPath(t reflect.Type) (s string) { return } +// A go identifier is (letter|_)[letter|number|_]* +func genGoIdentifier(s string, checkFirstChar bool) string { + b := make([]byte, 0, len(s)) + t := make([]byte, 4) + var n int + for i, r := range s { + if checkFirstChar && i == 0 && !unicode.IsLetter(r) { + b = append(b, '_') + } + // r must be unicode_letter, unicode_digit or _ + if unicode.IsLetter(r) || unicode.IsDigit(r) { + n = utf8.EncodeRune(t, r) + b = append(b, t[:n]...) + } else { + b = append(b, '_') + } + } + return string(b) +} + func genNonPtr(t reflect.Type) reflect.Type { for t.Kind() == reflect.Ptr { t = t.Elem() diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go index 560014ae3..40065a01c 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/helper.go @@ -155,8 +155,10 @@ const ( resetSliceElemToZeroValue bool = false ) -var oneByteArr = [1]byte{0} -var zeroByteSlice = oneByteArr[:0:0] +var ( + oneByteArr = [1]byte{0} + zeroByteSlice = oneByteArr[:0:0] +) type charEncoding uint8 @@ -215,6 +217,24 @@ const ( containerArrayEnd ) +type rgetPoolT struct { + encNames [8]string + fNames [8]string + etypes [8]uintptr + sfis [8]*structFieldInfo +} + +var rgetPool = sync.Pool{ + New: func() interface{} { return new(rgetPoolT) }, +} + +type rgetT struct { + fNames []string + encNames []string + etypes []uintptr + sfis []*structFieldInfo +} + type containerStateRecv interface { sendContainerState(containerState) } @@ -833,14 +853,17 @@ func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) { siInfo = parseStructFieldInfo(structInfoFieldName, x.structTag(f.Tag)) ti.toArray = siInfo.toArray } - sfip := make([]*structFieldInfo, 0, rt.NumField()) - x.rget(rt, nil, make(map[string]bool, 16), &sfip, siInfo) - - ti.sfip = make([]*structFieldInfo, len(sfip)) - ti.sfi = make([]*structFieldInfo, len(sfip)) - copy(ti.sfip, sfip) - sort.Sort(sfiSortedByEncName(sfip)) - copy(ti.sfi, sfip) + pi := rgetPool.Get() + pv := pi.(*rgetPoolT) + pv.etypes[0] = ti.baseId + vv := rgetT{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]} + x.rget(rt, rtid, nil, &vv, siInfo) + ti.sfip = make([]*structFieldInfo, len(vv.sfis)) + ti.sfi = make([]*structFieldInfo, len(vv.sfis)) + copy(ti.sfip, vv.sfis) + sort.Sort(sfiSortedByEncName(vv.sfis)) + copy(ti.sfi, vv.sfis) + rgetPool.Put(pi) } // sfi = sfip @@ -853,16 +876,37 @@ func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) { return } -func (x *TypeInfos) rget(rt reflect.Type, indexstack []int, fnameToHastag map[string]bool, - sfi *[]*structFieldInfo, siInfo *structFieldInfo, +func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, + indexstack []int, pv *rgetT, siInfo *structFieldInfo, ) { - for j := 0; j < rt.NumField(); j++ { + // This will read up the fields and store how to access the value. + // It uses the go language's rules for embedding, as below: + // - if a field has been seen while traversing, skip it + // - if an encName has been seen while traversing, skip it + // - if an embedded type has been seen, skip it + // + // Also, per Go's rules, embedded fields must be analyzed AFTER all top-level fields. + // + // Note: we consciously use slices, not a map, to simulate a set. + // Typically, types have < 16 fields, and iteration using equals is faster than maps there + + type anonField struct { + ft reflect.Type + idx int + } + + var anonFields []anonField + +LOOP: + for j, jlen := 0, rt.NumField(); j < jlen; j++ { f := rt.Field(j) fkind := f.Type.Kind() // skip if a func type, or is unexported, or structTag value == "-" - if fkind == reflect.Func { - continue + switch fkind { + case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer: + continue LOOP } + // if r1, _ := utf8.DecodeRuneInString(f.Name); r1 == utf8.RuneError || !unicode.IsUpper(r1) { if f.PkgPath != "" && !f.Anonymous { // unexported, not embedded continue @@ -886,11 +930,8 @@ func (x *TypeInfos) rget(rt reflect.Type, indexstack []int, fnameToHastag map[st ft = ft.Elem() } if ft.Kind() == reflect.Struct { - indexstack2 := make([]int, len(indexstack)+1, len(indexstack)+4) - copy(indexstack2, indexstack) - indexstack2[len(indexstack)] = j - // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j) - x.rget(ft, indexstack2, fnameToHastag, sfi, siInfo) + // handle anonymous fields after handling all the non-anon fields + anonFields = append(anonFields, anonField{ft, j}) continue } } @@ -901,26 +942,39 @@ func (x *TypeInfos) rget(rt reflect.Type, indexstack []int, fnameToHastag map[st continue } - // do not let fields with same name in embedded structs override field at higher level. - // this must be done after anonymous check, to allow anonymous field - // still include their child fields - if _, ok := fnameToHastag[f.Name]; ok { - continue - } if f.Name == "" { panic(noFieldNameToStructFieldInfoErr) } + + for _, k := range pv.fNames { + if k == f.Name { + continue LOOP + } + } + pv.fNames = append(pv.fNames, f.Name) + if si == nil { si = parseStructFieldInfo(f.Name, stag) } else if si.encName == "" { si.encName = f.Name } + + for _, k := range pv.encNames { + if k == si.encName { + continue LOOP + } + } + pv.encNames = append(pv.encNames, si.encName) + // si.ikind = int(f.Type.Kind()) if len(indexstack) == 0 { si.i = int16(j) } else { si.i = -1 - si.is = append(append(make([]int, 0, len(indexstack)+4), indexstack...), j) + si.is = make([]int, len(indexstack)+1) + copy(si.is, indexstack) + si.is[len(indexstack)] = j + // si.is = append(append(make([]int, 0, len(indexstack)+4), indexstack...), j) } if siInfo != nil { @@ -928,8 +982,26 @@ func (x *TypeInfos) rget(rt reflect.Type, indexstack []int, fnameToHastag map[st si.omitEmpty = true } } - *sfi = append(*sfi, si) - fnameToHastag[f.Name] = stag != "" + pv.sfis = append(pv.sfis, si) + } + + // now handle anonymous fields +LOOP2: + for _, af := range anonFields { + // if etypes contains this, then do not call rget again (as the fields are already seen here) + ftid := reflect.ValueOf(af.ft).Pointer() + for _, k := range pv.etypes { + if k == ftid { + continue LOOP2 + } + } + pv.etypes = append(pv.etypes, ftid) + + indexstack2 := make([]int, len(indexstack)+1) + copy(indexstack2, indexstack) + indexstack2[len(indexstack)] = af.idx + // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j) + x.rget(af.ft, ftid, indexstack2, pv, siInfo) } } @@ -1127,3 +1199,73 @@ type bytesISlice []bytesI func (p bytesISlice) Len() int { return len(p) } func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 } func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +// ----------------- + +type set []uintptr + +func (s *set) add(v uintptr) (exists bool) { + // e.ci is always nil, or len >= 1 + // defer func() { fmt.Printf("$$$$$$$$$$$ cirRef Add: %v, exists: %v\n", v, exists) }() + x := *s + if x == nil { + x = make([]uintptr, 1, 8) + x[0] = v + *s = x + return + } + // typically, length will be 1. make this perform. + if len(x) == 1 { + if j := x[0]; j == 0 { + x[0] = v + } else if j == v { + exists = true + } else { + x = append(x, v) + *s = x + } + return + } + // check if it exists + for _, j := range x { + if j == v { + exists = true + return + } + } + // try to replace a "deleted" slot + for i, j := range x { + if j == 0 { + x[i] = v + return + } + } + // if unable to replace deleted slot, just append it. + x = append(x, v) + *s = x + return +} + +func (s *set) remove(v uintptr) (exists bool) { + // defer func() { fmt.Printf("$$$$$$$$$$$ cirRef Rm: %v, exists: %v\n", v, exists) }() + x := *s + if len(x) == 0 { + return + } + if len(x) == 1 { + if x[0] == v { + x[0] = 0 + } + return + } + for i, j := range x { + if j == v { + exists = true + x[i] = 0 // set it to 0, as way to delete it. + // copy(x[i:], x[i+1:]) + // x = x[:len(x)-1] + return + } + } + return +} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go deleted file mode 100644 index e1dea52f4..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// All non-std package dependencies related to testing live in this file, -// so porting to different environment is easy (just update functions). -// -// This file sets up the variables used, including testInitFns. -// Each file should add initialization that should be performed -// after flags are parsed. -// -// init is a multi-step process: -// - setup vars (handled by init functions in each file) -// - parse flags -// - setup derived vars (handled by pre-init registered functions - registered in init function) -// - post init (handled by post-init registered functions - registered in init function) -// This way, no one has to manage carefully control the initialization -// using file names, etc. -// -// Tests which require external dependencies need the -tag=x parameter. -// They should be run as: -// go test -tags=x -run=. -// Benchmarks should also take this parameter, to include the sereal, xdr, etc. -// To run against codecgen, etc, make sure you pass extra parameters. -// Example usage: -// go test "-tags=x codecgen unsafe" -bench=. -// -// To fully test everything: -// go test -tags=x -benchtime=100ms -tv -bg -bi -brw -bu -v -run=. -bench=. - -// Handling flags -// codec_test.go will define a set of global flags for testing, including: -// - Use Reset -// - Use IO reader/writer (vs direct bytes) -// - Set Canonical -// - Set InternStrings -// - Use Symbols -// -// This way, we can test them all by running same set of tests with a different -// set of flags. -// -// Following this, all the benchmarks will utilize flags set by codec_test.go -// and will not redefine these "global" flags. - -import ( - "bytes" - "errors" - "flag" - "fmt" - "reflect" - "sync" - "testing" -) - -type testHED struct { - H Handle - E *Encoder - D *Decoder -} - -var ( - testNoopH = NoopHandle(8) - testMsgpackH = &MsgpackHandle{} - testBincH = &BincHandle{} - testSimpleH = &SimpleHandle{} - testCborH = &CborHandle{} - testJsonH = &JsonHandle{} - - testHandles []Handle - testPreInitFns []func() - testPostInitFns []func() - - testOnce sync.Once - - testHEDs []testHED -) - -func init() { - testHEDs = make([]testHED, 0, 32) - testHandles = append(testHandles, - testNoopH, testMsgpackH, testBincH, testSimpleH, - testCborH, testJsonH) -} - -func testHEDGet(h Handle) *testHED { - for i := range testHEDs { - v := &testHEDs[i] - if v.H == h { - return v - } - } - testHEDs = append(testHEDs, testHED{h, NewEncoder(nil, h), NewDecoder(nil, h)}) - return &testHEDs[len(testHEDs)-1] -} - -func testInitAll() { - flag.Parse() - for _, f := range testPreInitFns { - f() - } - for _, f := range testPostInitFns { - f() - } -} - -func testCodecEncode(ts interface{}, bsIn []byte, - fn func([]byte) *bytes.Buffer, h Handle) (bs []byte, err error) { - // bs = make([]byte, 0, approxSize) - var e *Encoder - var buf *bytes.Buffer - if testUseReset { - e = testHEDGet(h).E - } else { - e = NewEncoder(nil, h) - } - if testUseIoEncDec { - buf = fn(bsIn) - e.Reset(buf) - } else { - bs = bsIn - e.ResetBytes(&bs) - } - if testUseMust { - e.MustEncode(ts) - } else { - err = e.Encode(ts) - } - if testUseIoEncDec { - bs = buf.Bytes() - } - return -} - -func testCodecDecode(bs []byte, ts interface{}, h Handle) (err error) { - var d *Decoder - var buf *bytes.Reader - if testUseReset { - d = testHEDGet(h).D - } else { - d = NewDecoder(nil, h) - } - if testUseIoEncDec { - buf = bytes.NewReader(bs) - d.Reset(buf) - } else { - d.ResetBytes(bs) - } - if testUseMust { - d.MustDecode(ts) - } else { - err = d.Decode(ts) - } - return -} - -// ----- functions below are used only by tests (not benchmarks) - -const ( - testLogToT = true - failNowOnFail = true -) - -func checkErrT(t *testing.T, err error) { - if err != nil { - logT(t, err.Error()) - failT(t) - } -} - -func checkEqualT(t *testing.T, v1 interface{}, v2 interface{}, desc string) (err error) { - if err = deepEqual(v1, v2); err != nil { - logT(t, "Not Equal: %s: %v. v1: %v, v2: %v", desc, err, v1, v2) - failT(t) - } - return -} - -func failT(t *testing.T) { - if failNowOnFail { - t.FailNow() - } else { - t.Fail() - } -} - -// --- these functions are used by both benchmarks and tests - -func deepEqual(v1, v2 interface{}) (err error) { - if !reflect.DeepEqual(v1, v2) { - err = errors.New("Not Match") - } - return -} - -func logT(x interface{}, format string, args ...interface{}) { - if t, ok := x.(*testing.T); ok && t != nil && testLogToT { - if testVerbose { - t.Logf(format, args...) - } - } else if b, ok := x.(*testing.B); ok && b != nil && testLogToT { - b.Logf(format, args...) - } else { - if len(format) == 0 || format[len(format)-1] != '\n' { - format = format + "\n" - } - fmt.Printf(format, args...) - } -} - -func approxDataSize(rv reflect.Value) (sum int) { - switch rk := rv.Kind(); rk { - case reflect.Invalid: - case reflect.Ptr, reflect.Interface: - sum += int(rv.Type().Size()) - sum += approxDataSize(rv.Elem()) - case reflect.Slice: - sum += int(rv.Type().Size()) - for j := 0; j < rv.Len(); j++ { - sum += approxDataSize(rv.Index(j)) - } - case reflect.String: - sum += int(rv.Type().Size()) - sum += rv.Len() - case reflect.Map: - sum += int(rv.Type().Size()) - for _, mk := range rv.MapKeys() { - sum += approxDataSize(mk) - sum += approxDataSize(rv.MapIndex(mk)) - } - case reflect.Struct: - //struct size already includes the full data size. - //sum += int(rv.Type().Size()) - for j := 0; j < rv.NumField(); j++ { - sum += approxDataSize(rv.Field(j)) - } - default: - //pure value types - sum += int(rv.Type().Size()) - } - return -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go index a18a5f706..a04dfcb9d 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/json.go @@ -43,18 +43,23 @@ import ( //-------------------------------- -var jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'} +var ( + jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'} -var jsonFloat64Pow10 = [...]float64{ - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, - 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, - 1e20, 1e21, 1e22, -} + jsonFloat64Pow10 = [...]float64{ + 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + 1e20, 1e21, 1e22, + } -var jsonUint64Pow10 = [...]uint64{ - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, - 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, -} + jsonUint64Pow10 = [...]uint64{ + 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + } + + // jsonTabs and jsonSpaces are used as caches for indents + jsonTabs, jsonSpaces string +) const ( // jsonUnreadAfterDecNum controls whether we unread after decoding a number. @@ -85,8 +90,23 @@ const ( jsonNumUintMaxVal = 1< 1<<53 || v < -(1<<53)) { + e.w.writen1('"') + e.w.writeb(strconv.AppendInt(e.b[:0], v, 10)) + e.w.writen1('"') + return + } e.w.writeb(strconv.AppendInt(e.b[:0], v, 10)) } func (e *jsonEncDriver) EncodeUint(v uint64) { + if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 { + e.w.writen1('"') + e.w.writeb(strconv.AppendUint(e.b[:0], v, 10)) + e.w.writen1('"') + return + } e.w.writeb(strconv.AppendUint(e.b[:0], v, 10)) } @@ -165,11 +243,17 @@ func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) { } func (e *jsonEncDriver) EncodeArrayStart(length int) { + if e.d { + e.dl++ + } e.w.writen1('[') e.c = containerArrayStart } func (e *jsonEncDriver) EncodeMapStart(length int) { + if e.d { + e.dl++ + } e.w.writen1('{') e.c = containerMapStart } @@ -564,6 +648,11 @@ func (d *jsonDecDriver) decNum(storeBytes bool) { d.tok = b } b := d.tok + var str bool + if b == '"' { + str = true + b = d.r.readn1() + } if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) { d.d.errorf("json: decNum: got first char '%c'", b) return @@ -578,6 +667,10 @@ func (d *jsonDecDriver) decNum(storeBytes bool) { n.reset() d.bs = d.bs[:0] + if str && storeBytes { + d.bs = append(d.bs, '"') + } + // The format of a number is as below: // parsing: sign? digit* dot? digit* e? sign? digit* // states: 0 1* 2 3* 4 5* 6 7 @@ -668,6 +761,14 @@ LOOP: default: break LOOP } + case '"': + if str { + if storeBytes { + d.bs = append(d.bs, '"') + } + b, eof = r.readn1eof() + } + break LOOP default: break LOOP } @@ -1033,6 +1134,24 @@ type JsonHandle struct { // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way. // If not configured, raw bytes are encoded to/from base64 text. RawBytesExt InterfaceExt + + // Indent indicates how a value is encoded. + // - If positive, indent by that number of spaces. + // - If negative, indent by that number of tabs. + Indent int8 + + // IntegerAsString controls how integers (signed and unsigned) are encoded. + // + // Per the JSON Spec, JSON numbers are 64-bit floating point numbers. + // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision. + // This can be mitigated by configuring how to encode integers. + // + // IntegerAsString interpretes the following values: + // - if 'L', then encode integers > 2^53 as a json string. + // - if 'A', then encode all integers as a json string + // containing the exact integer representation as a decimal. + // - else encode all integers as a json number (default) + IntegerAsString uint8 } func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) { @@ -1040,26 +1159,48 @@ func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceE } func (h *JsonHandle) newEncDriver(e *Encoder) encDriver { - hd := jsonEncDriver{e: e, w: e.w, h: h} + hd := jsonEncDriver{e: e, h: h} hd.bs = hd.b[:0] - hd.se.i = h.RawBytesExt + + hd.reset() + return &hd } func (h *JsonHandle) newDecDriver(d *Decoder) decDriver { // d := jsonDecDriver{r: r.(*bytesDecReader), h: h} - hd := jsonDecDriver{d: d, r: d.r, h: h} + hd := jsonDecDriver{d: d, h: h} hd.bs = hd.b[:0] - hd.se.i = h.RawBytesExt + hd.reset() return &hd } func (e *jsonEncDriver) reset() { e.w = e.e.w + e.se.i = e.h.RawBytesExt + if e.bs != nil { + e.bs = e.bs[:0] + } + e.d, e.dt, e.dl, e.ds = false, false, 0, "" + e.c = 0 + if e.h.Indent > 0 { + e.d = true + e.ds = jsonSpaces[:e.h.Indent] + } else if e.h.Indent < 0 { + e.d = true + e.dt = true + e.ds = jsonTabs[:-(e.h.Indent)] + } } func (d *jsonDecDriver) reset() { d.r = d.d.r + d.se.i = d.h.RawBytesExt + if d.bs != nil { + d.bs = d.bs[:0] + } + d.c, d.tok = 0, 0 + d.n.reset() } var jsonEncodeTerminate = []byte{' '} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go index 5eb4c9636..f9f872362 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/msgpack.go @@ -374,7 +374,7 @@ func (d *msgpackDecDriver) DecodeNaked() { } if n.v == valueTypeUint && d.h.SignedInteger { n.v = valueTypeInt - n.i = int64(n.v) + n.i = int64(n.u) } return } @@ -729,6 +729,7 @@ func (e *msgpackEncDriver) reset() { func (d *msgpackDecDriver) reset() { d.r = d.d.r + d.bd, d.bdRead = 0, false } //-------------------------------------------------- diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh b/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh index 98f442487..909f4bb0f 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/prebuild.sh @@ -171,7 +171,7 @@ do 'xf') zforce=1;; 'xb') zbak=1;; 'xx') zexternal=1;; - *) echo "prebuild.sh accepts [-fb] only"; return 1;; + *) echo "prebuild.sh accepts [-fbx] only"; return 1;; esac done shift $((OPTIND-1)) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go deleted file mode 100644 index bedd7b0dc..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go +++ /dev/null @@ -1,30 +0,0 @@ -//+build x - -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// These tests are used to verify msgpack and cbor implementations against their python libraries. -// If you have the library installed, you can enable the tests back by running: go test -tags=x . -// Look at test.py for how to setup your environment. - -import ( - "testing" -) - -func TestMsgpackPythonGenStreams(t *testing.T) { - doTestPythonGenStreams(t, "msgpack", testMsgpackH) -} - -func TestCborPythonGenStreams(t *testing.T) { - doTestPythonGenStreams(t, "cbor", testCborH) -} - -func TestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) { - doTestMsgpackRpcSpecGoClientToPythonSvc(t) -} - -func TestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) { - doTestMsgpackRpcSpecPythonClientToGoSvc(t) -} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/simple.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/simple.go index c15049650..7c0ba7aff 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/simple.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/simple.go @@ -512,6 +512,7 @@ func (e *simpleEncDriver) reset() { func (d *simpleDecDriver) reset() { d.r = d.d.r + d.bd, d.bdRead = 0, false } var _ decDriver = (*simpleDecDriver)(nil) diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py b/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py index dfe3b0c9a..c0ad20b34 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/test.py @@ -9,6 +9,8 @@ # sudo apt-get install python-pip # pip install --user msgpack-python msgpack-rpc-python cbor +# Ensure all "string" keys are utf strings (else encoded as bytes) + import cbor, msgpack, msgpackrpc, sys, os, threading def get_test_data_list(): @@ -26,35 +28,39 @@ def get_test_data_list(): -3232.0, -6464646464.0, 3232.0, + 6464.0, 6464646464.0, False, True, + u"null", None, u"someday", - u"", - u"bytestring", 1328176922000002000, + u"", -2206187877999998000, + u"bytestring", 270, + u"none", -2013855847999995777, #-6795364578871345152, ] l1 = [ { "true": True, "false": False }, - { "true": "True", + { "true": u"True", "false": False, "uint16(1616)": 1616 }, { "list": [1616, 32323232, True, -3232.0, {"TRUE":True, "FALSE":False}, [True, False] ], "int32":32323232, "bool": True, - "LONG STRING": "123456789012345678901234567890123456789012345678901234567890", - "SHORT STRING": "1234567890" }, - { True: "true", 8: False, "false": 0 } + "LONG STRING": u"123456789012345678901234567890123456789012345678901234567890", + "SHORT STRING": u"1234567890" }, + { True: "true", 138: False, "false": 200 } ] l = [] l.extend(l0) l.append(l0) + l.append(1) l.extend(l1) return l diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh b/Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh index b1602ea7e..00857b620 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/tests.sh @@ -6,6 +6,7 @@ _run() { # 1. VARIATIONS: regular (t), canonical (c), IO R/W (i), # binc-nosymbols (n), struct2array (s), intern string (e), + # json-indent (d), circular (l) # 2. MODE: reflection (r), external (x), codecgen (g), unsafe (u), notfastpath (f) # 3. OPTIONS: verbose (v), reset (z), must (m), # @@ -16,7 +17,7 @@ _run() { zargs="" local OPTIND OPTIND=1 - while getopts "xurtcinsvgzmef" flag + while getopts "_xurtcinsvgzmefdl" flag do case "x$flag" in 'xr') ;; @@ -27,6 +28,7 @@ _run() { 'xv') zargs="$zargs -tv" ;; 'xz') zargs="$zargs -tr" ;; 'xm') zargs="$zargs -tm" ;; + 'xl') zargs="$zargs -tl" ;; *) ;; esac done @@ -35,15 +37,19 @@ _run() { # echo ">>>>>>> TAGS: $ztags" OPTIND=1 - while getopts "xurtcinsvgzmef" flag + while getopts "_xurtcinsvgzmefdl" flag do case "x$flag" in 'xt') printf ">>>>>>> REGULAR : "; go test "-tags=$ztags" $zargs ; sleep 2 ;; 'xc') printf ">>>>>>> CANONICAL : "; go test "-tags=$ztags" $zargs -tc; sleep 2 ;; 'xi') printf ">>>>>>> I/O : "; go test "-tags=$ztags" $zargs -ti; sleep 2 ;; - 'xn') printf ">>>>>>> NO_SYMBOLS : "; go test "-tags=$ztags" $zargs -tn; sleep 2 ;; + 'xn') printf ">>>>>>> NO_SYMBOLS : "; go test "-tags=$ztags" -run=Binc $zargs -tn; sleep 2 ;; 'xs') printf ">>>>>>> TO_ARRAY : "; go test "-tags=$ztags" $zargs -ts; sleep 2 ;; 'xe') printf ">>>>>>> INTERN : "; go test "-tags=$ztags" $zargs -te; sleep 2 ;; + 'xd') printf ">>>>>>> INDENT : "; + go test "-tags=$ztags" -run=JsonCodecsTable -td=-1 $zargs; + go test "-tags=$ztags" -run=JsonCodecsTable -td=8 $zargs; + sleep 2 ;; *) ;; esac done @@ -55,20 +61,20 @@ _run() { # echo ">>>>>>> RUNNING VARIATIONS OF TESTS" if [[ "x$@" = "x" ]]; then # All: r, x, g, gu - _run "-rtcinsm" # regular - _run "-rtcinsmz" # regular with reset - _run "-rtcinsmf" # regular with no fastpath (notfastpath) - _run "-xtcinsm" # external - _run "-gxtcinsm" # codecgen: requires external - _run "-gxutcinsm" # codecgen + unsafe + _run "-_tcinsed_ml" # regular + _run "-_tcinsed_ml_z" # regular with reset + _run "-_tcinsed_ml_f" # regular with no fastpath (notfastpath) + _run "-x_tcinsed_ml" # external + _run "-gx_tcinsed_ml" # codecgen: requires external + _run "-gxu_tcinsed_ml" # codecgen + unsafe elif [[ "x$@" = "x-Z" ]]; then # Regular - _run "-rtcinsm" # regular - _run "-rtcinsmz" # regular with reset + _run "-_tcinsed_ml" # regular + _run "-_tcinsed_ml_z" # regular with reset elif [[ "x$@" = "x-F" ]]; then # regular with notfastpath - _run "-rtcinsmf" # regular - _run "-rtcinsmzf" # regular with reset + _run "-_tcinsed_ml_f" # regular + _run "-_tcinsed_ml_zf" # regular with reset else _run "$@" fi diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/time.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/time.go index fc4c63e1d..718b731ec 100644 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/time.go +++ b/Godeps/_workspace/src/github.com/ugorji/go/codec/time.go @@ -5,11 +5,22 @@ package codec import ( "fmt" + "reflect" "time" ) var ( - timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} + timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} + timeExtEncFn = func(rv reflect.Value) (bs []byte, err error) { + defer panicToErr(&err) + bs = timeExt{}.WriteExt(rv.Interface()) + return + } + timeExtDecFn = func(rv reflect.Value, bs []byte) (err error) { + defer panicToErr(&err) + timeExt{}.ReadExt(rv.Interface(), bs) + return + } ) type timeExt struct{} diff --git a/Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go deleted file mode 100644 index 4ec28e131..000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go +++ /dev/null @@ -1,203 +0,0 @@ -// // +build testing - -// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved. -// Use of this source code is governed by a MIT license found in the LICENSE file. - -package codec - -// This file contains values used by tests and benchmarks. -// JSON/BSON do not like maps with keys that are not strings, -// so we only use maps with string keys here. - -import ( - "math" - "time" -) - -var testStrucTime = time.Date(2012, 2, 2, 2, 2, 2, 2000, time.UTC).UTC() - -type AnonInTestStruc struct { - AS string - AI64 int64 - AI16 int16 - AUi64 uint64 - ASslice []string - AI64slice []int64 - AF64slice []float64 - // AMI32U32 map[int32]uint32 - // AMU32F64 map[uint32]float64 // json/bson do not like it - AMSU16 map[string]uint16 -} - -type AnonInTestStrucIntf struct { - Islice []interface{} - Ms map[string]interface{} - Nintf interface{} //don't set this, so we can test for nil - T time.Time -} - -type TestStruc struct { - _struct struct{} `codec:",omitempty"` //set omitempty for every field - - S string - I64 int64 - I16 int16 - Ui64 uint64 - Ui8 uint8 - B bool - By uint8 // byte: msgp doesn't like byte - - Sslice []string - I64slice []int64 - I16slice []int16 - Ui64slice []uint64 - Ui8slice []uint8 - Bslice []bool - Byslice []byte - - Iptrslice []*int64 - - // TODO: test these separately, specifically for reflection and codecgen. - // Unfortunately, ffjson doesn't support these. Its compilation even fails. - // Ui64array [4]uint64 - // Ui64slicearray [][4]uint64 - - AnonInTestStruc - - //M map[interface{}]interface{} `json:"-",bson:"-"` - Msi64 map[string]int64 - - // make this a ptr, so that it could be set or not. - // for comparison (e.g. with msgp), give it a struct tag (so it is not inlined), - // make this one omitempty (so it is included if nil). - *AnonInTestStrucIntf `codec:",omitempty"` - - Nmap map[string]bool //don't set this, so we can test for nil - Nslice []byte //don't set this, so we can test for nil - Nint64 *int64 //don't set this, so we can test for nil - Mtsptr map[string]*TestStruc - Mts map[string]TestStruc - Its []*TestStruc - Nteststruc *TestStruc -} - -// small struct for testing that codecgen works for unexported types -type tLowerFirstLetter struct { - I int - u uint64 - S string - b []byte -} - -func newTestStruc(depth int, bench bool, useInterface, useStringKeyOnly bool) (ts *TestStruc) { - var i64a, i64b, i64c, i64d int64 = 64, 6464, 646464, 64646464 - - ts = &TestStruc{ - S: "some string", - I64: math.MaxInt64 * 2 / 3, // 64, - I16: 1616, - Ui64: uint64(int64(math.MaxInt64 * 2 / 3)), // 64, //don't use MaxUint64, as bson can't write it - Ui8: 160, - B: true, - By: 5, - - Sslice: []string{"one", "two", "three"}, - I64slice: []int64{1111, 2222, 3333}, - I16slice: []int16{44, 55, 66}, - Ui64slice: []uint64{12121212, 34343434, 56565656}, - Ui8slice: []uint8{210, 211, 212}, - Bslice: []bool{true, false, true, false}, - Byslice: []byte{13, 14, 15}, - - Msi64: map[string]int64{ - "one": 1, - "two": 2, - }, - AnonInTestStruc: AnonInTestStruc{ - // There's more leeway in altering this. - AS: "A-String", - AI64: -64646464, - AI16: 1616, - AUi64: 64646464, - // (U+1D11E)G-clef character may be represented in json as "\uD834\uDD1E". - // single reverse solidus character may be represented in json as "\u005C". - // include these in ASslice below. - ASslice: []string{"Aone", "Atwo", "Athree", - "Afour.reverse_solidus.\u005c", "Afive.Gclef.\U0001d11E"}, - AI64slice: []int64{1, -22, 333, -4444, 55555, -666666}, - AMSU16: map[string]uint16{"1": 1, "22": 2, "333": 3, "4444": 4}, - AF64slice: []float64{11.11e-11, 22.22E+22, 33.33E-33, 44.44e+44, 555.55E-6, 666.66E6}, - }, - } - if useInterface { - ts.AnonInTestStrucIntf = &AnonInTestStrucIntf{ - Islice: []interface{}{"true", true, "no", false, uint64(288), float64(0.4)}, - Ms: map[string]interface{}{ - "true": "true", - "int64(9)": false, - }, - T: testStrucTime, - } - } - - //For benchmarks, some things will not work. - if !bench { - //json and bson require string keys in maps - //ts.M = map[interface{}]interface{}{ - // true: "true", - // int8(9): false, - //} - //gob cannot encode nil in element in array (encodeArray: nil element) - ts.Iptrslice = []*int64{nil, &i64a, nil, &i64b, nil, &i64c, nil, &i64d, nil} - // ts.Iptrslice = nil - } - if !useStringKeyOnly { - // ts.AnonInTestStruc.AMU32F64 = map[uint32]float64{1: 1, 2: 2, 3: 3} // Json/Bson barf - } - if depth > 0 { - depth-- - if ts.Mtsptr == nil { - ts.Mtsptr = make(map[string]*TestStruc) - } - if ts.Mts == nil { - ts.Mts = make(map[string]TestStruc) - } - ts.Mtsptr["0"] = newTestStruc(depth, bench, useInterface, useStringKeyOnly) - ts.Mts["0"] = *(ts.Mtsptr["0"]) - ts.Its = append(ts.Its, ts.Mtsptr["0"]) - } - return -} - -// Some other types - -type Sstring string -type Bbool bool -type Sstructsmall struct { - A int -} - -type Sstructbig struct { - A int - B bool - c string - // Sval Sstruct - Ssmallptr *Sstructsmall - Ssmall *Sstructsmall - Sptr *Sstructbig -} - -type SstructbigMapBySlice struct { - _struct struct{} `codec:",toarray"` - A int - B bool - c string - // Sval Sstruct - Ssmallptr *Sstructsmall - Ssmall *Sstructsmall - Sptr *Sstructbig -} - -type Sinterface interface { - Noop() -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE b/Godeps/_workspace/src/golang.org/x/net/LICENSE similarity index 83% rename from Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE rename to Godeps/_workspace/src/golang.org/x/net/LICENSE index 0e5fb8728..6a66aea5e 100644 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE +++ b/Godeps/_workspace/src/golang.org/x/net/LICENSE @@ -1,16 +1,16 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. +Copyright (c) 2009 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 + * 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 + * 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 + * 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. diff --git a/Godeps/_workspace/src/golang.org/x/net/PATENTS b/Godeps/_workspace/src/golang.org/x/net/PATENTS new file mode 100644 index 000000000..733099041 --- /dev/null +++ b/Godeps/_workspace/src/golang.org/x/net/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google 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, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/Godeps/_workspace/src/golang.org/x/net/context/context_test.go b/Godeps/_workspace/src/golang.org/x/net/context/context_test.go deleted file mode 100644 index e64afa64c..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/context_test.go +++ /dev/null @@ -1,575 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context - -import ( - "fmt" - "math/rand" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -// otherContext is a Context that's not one of the types defined in context.go. -// This lets us test code paths that differ based on the underlying type of the -// Context. -type otherContext struct { - Context -} - -func TestBackground(t *testing.T) { - c := Background() - if c == nil { - t.Fatalf("Background returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.Background"; got != want { - t.Errorf("Background().String() = %q want %q", got, want) - } -} - -func TestTODO(t *testing.T) { - c := TODO() - if c == nil { - t.Fatalf("TODO returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.TODO"; got != want { - t.Errorf("TODO().String() = %q want %q", got, want) - } -} - -func TestWithCancel(t *testing.T) { - c1, cancel := WithCancel(Background()) - - if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { - t.Errorf("c1.String() = %q want %q", got, want) - } - - o := otherContext{c1} - c2, _ := WithCancel(o) - contexts := []Context{c1, o, c2} - - for i, c := range contexts { - if d := c.Done(); d == nil { - t.Errorf("c[%d].Done() == %v want non-nil", i, d) - } - if e := c.Err(); e != nil { - t.Errorf("c[%d].Err() == %v want nil", i, e) - } - - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - } - - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - - for i, c := range contexts { - select { - case <-c.Done(): - default: - t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) - } - if e := c.Err(); e != Canceled { - t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) - } - } -} - -func TestParentFinishesChild(t *testing.T) { - // Context tree: - // parent -> cancelChild - // parent -> valueChild -> timerChild - parent, cancel := WithCancel(Background()) - cancelChild, stop := WithCancel(parent) - defer stop() - valueChild := WithValue(parent, "key", "value") - timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) - defer stop() - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-cancelChild.Done(): - t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) - case x := <-timerChild.Done(): - t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) - case x := <-valueChild.Done(): - t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) - default: - } - - // The parent's children should contain the two cancelable children. - pc := parent.(*cancelCtx) - cc := cancelChild.(*cancelCtx) - tc := timerChild.(*timerCtx) - pc.mu.Lock() - if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { - t.Errorf("bad linkage: pc.children = %v, want %v and %v", - pc.children, cc, tc) - } - pc.mu.Unlock() - - if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) - } - if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) - } - - cancel() - - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) - } - pc.mu.Unlock() - - // parent and children should all be finished. - check := func(ctx Context, name string) { - select { - case <-ctx.Done(): - default: - t.Errorf("<-%s.Done() blocked, but shouldn't have", name) - } - if e := ctx.Err(); e != Canceled { - t.Errorf("%s.Err() == %v want %v", name, e, Canceled) - } - } - check(parent, "parent") - check(cancelChild, "cancelChild") - check(valueChild, "valueChild") - check(timerChild, "timerChild") - - // WithCancel should return a canceled context on a canceled parent. - precanceledChild := WithValue(parent, "key", "value") - select { - case <-precanceledChild.Done(): - default: - t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") - } - if e := precanceledChild.Err(); e != Canceled { - t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) - } -} - -func TestChildFinishesFirst(t *testing.T) { - cancelable, stop := WithCancel(Background()) - defer stop() - for _, parent := range []Context{Background(), cancelable} { - child, cancel := WithCancel(parent) - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-child.Done(): - t.Errorf("<-child.Done() == %v want nothing (it should block)", x) - default: - } - - cc := child.(*cancelCtx) - pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() - if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { - t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) - } - - if pcok { - pc.mu.Lock() - if len(pc.children) != 1 || !pc.children[cc] { - t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) - } - pc.mu.Unlock() - } - - cancel() - - if pcok { - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) - } - pc.mu.Unlock() - } - - // child should be finished. - select { - case <-child.Done(): - default: - t.Errorf("<-child.Done() blocked, but shouldn't have") - } - if e := child.Err(); e != Canceled { - t.Errorf("child.Err() == %v want %v", e, Canceled) - } - - // parent should not be finished. - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - default: - } - if e := parent.Err(); e != nil { - t.Errorf("parent.Err() == %v want nil", e) - } - } -} - -func testDeadline(c Context, wait time.Duration, t *testing.T) { - select { - case <-time.After(wait): - t.Fatalf("context should have timed out") - case <-c.Done(): - } - if e := c.Err(); e != DeadlineExceeded { - t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) - } -} - -func TestDeadline(t *testing.T) { - c, _ := WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 200*time.Millisecond, t) - - c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - o := otherContext{c} - testDeadline(o, 200*time.Millisecond, t) - - c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) - o = otherContext{c} - c, _ = WithDeadline(o, time.Now().Add(300*time.Millisecond)) - testDeadline(c, 200*time.Millisecond, t) -} - -func TestTimeout(t *testing.T) { - c, _ := WithTimeout(Background(), 100*time.Millisecond) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 200*time.Millisecond, t) - - c, _ = WithTimeout(Background(), 100*time.Millisecond) - o := otherContext{c} - testDeadline(o, 200*time.Millisecond, t) - - c, _ = WithTimeout(Background(), 100*time.Millisecond) - o = otherContext{c} - c, _ = WithTimeout(o, 300*time.Millisecond) - testDeadline(c, 200*time.Millisecond, t) -} - -func TestCanceledTimeout(t *testing.T) { - c, _ := WithTimeout(Background(), 200*time.Millisecond) - o := otherContext{c} - c, cancel := WithTimeout(o, 400*time.Millisecond) - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - select { - case <-c.Done(): - default: - t.Errorf("<-c.Done() blocked, but shouldn't have") - } - if e := c.Err(); e != Canceled { - t.Errorf("c.Err() == %v want %v", e, Canceled) - } -} - -type key1 int -type key2 int - -var k1 = key1(1) -var k2 = key2(1) // same int as k1, different type -var k3 = key2(3) // same type as k2, different int - -func TestValues(t *testing.T) { - check := func(c Context, nm, v1, v2, v3 string) { - if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { - t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) - } - if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { - t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) - } - if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { - t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) - } - } - - c0 := Background() - check(c0, "c0", "", "", "") - - c1 := WithValue(Background(), k1, "c1k1") - check(c1, "c1", "c1k1", "", "") - - if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { - t.Errorf("c.String() = %q want %q", got, want) - } - - c2 := WithValue(c1, k2, "c2k2") - check(c2, "c2", "c1k1", "c2k2", "") - - c3 := WithValue(c2, k3, "c3k3") - check(c3, "c2", "c1k1", "c2k2", "c3k3") - - c4 := WithValue(c3, k1, nil) - check(c4, "c4", "", "c2k2", "c3k3") - - o0 := otherContext{Background()} - check(o0, "o0", "", "", "") - - o1 := otherContext{WithValue(Background(), k1, "c1k1")} - check(o1, "o1", "c1k1", "", "") - - o2 := WithValue(o1, k2, "o2k2") - check(o2, "o2", "c1k1", "o2k2", "") - - o3 := otherContext{c4} - check(o3, "o3", "", "c2k2", "c3k3") - - o4 := WithValue(o3, k3, nil) - check(o4, "o4", "", "c2k2", "") -} - -func TestAllocs(t *testing.T) { - bg := Background() - for _, test := range []struct { - desc string - f func() - limit float64 - gccgoLimit float64 - }{ - { - desc: "Background()", - f: func() { Background() }, - limit: 0, - gccgoLimit: 0, - }, - { - desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), - f: func() { - c := WithValue(bg, k1, nil) - c.Value(k1) - }, - limit: 3, - gccgoLimit: 3, - }, - { - desc: "WithTimeout(bg, 15*time.Millisecond)", - f: func() { - c, _ := WithTimeout(bg, 15*time.Millisecond) - <-c.Done() - }, - limit: 8, - gccgoLimit: 15, - }, - { - desc: "WithCancel(bg)", - f: func() { - c, cancel := WithCancel(bg) - cancel() - <-c.Done() - }, - limit: 5, - gccgoLimit: 8, - }, - { - desc: "WithTimeout(bg, 100*time.Millisecond)", - f: func() { - c, cancel := WithTimeout(bg, 100*time.Millisecond) - cancel() - <-c.Done() - }, - limit: 8, - gccgoLimit: 25, - }, - } { - limit := test.limit - if runtime.Compiler == "gccgo" { - // gccgo does not yet do escape analysis. - // TOOD(iant): Remove this when gccgo does do escape analysis. - limit = test.gccgoLimit - } - if n := testing.AllocsPerRun(100, test.f); n > limit { - t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) - } - } -} - -func TestSimultaneousCancels(t *testing.T) { - root, cancel := WithCancel(Background()) - m := map[Context]CancelFunc{root: cancel} - q := []Context{root} - // Create a tree of contexts. - for len(q) != 0 && len(m) < 100 { - parent := q[0] - q = q[1:] - for i := 0; i < 4; i++ { - ctx, cancel := WithCancel(parent) - m[ctx] = cancel - q = append(q, ctx) - } - } - // Start all the cancels in a random order. - var wg sync.WaitGroup - wg.Add(len(m)) - for _, cancel := range m { - go func(cancel CancelFunc) { - cancel() - wg.Done() - }(cancel) - } - // Wait on all the contexts in a random order. - for ctx := range m { - select { - case <-ctx.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) - } - } - // Wait for all the cancel functions to return. - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) - } -} - -func TestInterlockedCancels(t *testing.T) { - parent, cancelParent := WithCancel(Background()) - child, cancelChild := WithCancel(parent) - go func() { - parent.Done() - cancelChild() - }() - cancelParent() - select { - case <-child.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) - } -} - -func TestLayersCancel(t *testing.T) { - testLayers(t, time.Now().UnixNano(), false) -} - -func TestLayersTimeout(t *testing.T) { - testLayers(t, time.Now().UnixNano(), true) -} - -func testLayers(t *testing.T, seed int64, testTimeout bool) { - rand.Seed(seed) - errorf := func(format string, a ...interface{}) { - t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) - } - const ( - timeout = 200 * time.Millisecond - minLayers = 30 - ) - type value int - var ( - vals []*value - cancels []CancelFunc - numTimers int - ctx = Background() - ) - for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { - switch rand.Intn(3) { - case 0: - v := new(value) - ctx = WithValue(ctx, v, v) - vals = append(vals, v) - case 1: - var cancel CancelFunc - ctx, cancel = WithCancel(ctx) - cancels = append(cancels, cancel) - case 2: - var cancel CancelFunc - ctx, cancel = WithTimeout(ctx, timeout) - cancels = append(cancels, cancel) - numTimers++ - } - } - checkValues := func(when string) { - for _, key := range vals { - if val := ctx.Value(key).(*value); key != val { - errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) - } - } - } - select { - case <-ctx.Done(): - errorf("ctx should not be canceled yet") - default: - } - if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { - t.Errorf("ctx.String() = %q want prefix %q", s, prefix) - } - t.Log(ctx) - checkValues("before cancel") - if testTimeout { - select { - case <-ctx.Done(): - case <-time.After(timeout + timeout/10): - errorf("ctx should have timed out") - } - checkValues("after timeout") - } else { - cancel := cancels[rand.Intn(len(cancels))] - cancel() - select { - case <-ctx.Done(): - default: - errorf("ctx should be canceled") - } - checkValues("after cancel") - } -} - -func TestCancelRemoves(t *testing.T) { - checkChildren := func(when string, ctx Context, want int) { - if got := len(ctx.(*cancelCtx).children); got != want { - t.Errorf("%s: context has %d children, want %d", when, got, want) - } - } - - ctx, _ := WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel := WithCancel(ctx) - checkChildren("with WithCancel child ", ctx, 1) - cancel() - checkChildren("after cancelling WithCancel child", ctx, 0) - - ctx, _ = WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel = WithTimeout(ctx, 60*time.Minute) - checkChildren("with WithTimeout child ", ctx, 1) - cancel() - checkChildren("after cancelling WithTimeout child", ctx, 0) -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go deleted file mode 100644 index 47b53d7f1..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go +++ /dev/null @@ -1,72 +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. - -package ctxhttp - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "golang.org/x/net/context" -) - -const ( - requestDuration = 100 * time.Millisecond - requestBody = "ok" -) - -func TestNoTimeout(t *testing.T) { - ctx := context.Background() - resp, err := doRequest(ctx) - - if resp == nil || err != nil { - t.Fatalf("error received from client: %v %v", err, resp) - } -} -func TestCancel(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - go func() { - time.Sleep(requestDuration / 2) - cancel() - }() - - resp, err := doRequest(ctx) - - if resp != nil || err == nil { - t.Fatalf("expected error, didn't get one. resp: %v", resp) - } - if err != ctx.Err() { - t.Fatalf("expected error from context but got: %v", err) - } -} - -func TestCancelAfterRequest(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - - resp, err := doRequest(ctx) - - // Cancel before reading the body. - // Request.Body should still be readable after the context is canceled. - cancel() - - b, err := ioutil.ReadAll(resp.Body) - if err != nil || string(b) != requestBody { - t.Fatalf("could not read body: %q %v", b, err) - } -} - -func doRequest(ctx context.Context) (*http.Response, error) { - var okHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(requestDuration) - w.Write([]byte(requestBody)) - }) - - serv := httptest.NewServer(okHandler) - defer serv.Close() - - return Get(ctx, nil, serv.URL) -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go b/Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go deleted file mode 100644 index a6754dc36..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context_test - -import ( - "fmt" - "time" - - "golang.org/x/net/context" -) - -func ExampleWithTimeout() { - // Pass a context with a timeout to tell a blocking function that it - // should abandon its work after the timeout elapses. - ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) - select { - case <-time.After(200 * time.Millisecond): - fmt.Println("overslept") - case <-ctx.Done(): - fmt.Println(ctx.Err()) // prints "context deadline exceeded" - } - // Output: - // context deadline exceeded -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials.go b/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials.go deleted file mode 100644 index 452fb8c12..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2014 The oauth2 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 clientcredentials implements the OAuth2.0 "client credentials" token flow, -// also known as the "two-legged OAuth 2.0". -// -// This should be used when the client is acting on its own behalf or when the client -// is the resource owner. It may also be used when requesting access to protected -// resources based on an authorization previously arranged with the authorization -// server. -// -// See http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4 -package clientcredentials - -import ( - "net/http" - "net/url" - "strings" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/internal" -) - -// tokenFromInternal maps an *internal.Token struct into -// an *oauth2.Token struct. -func tokenFromInternal(t *internal.Token) *oauth2.Token { - if t == nil { - return nil - } - tk := &oauth2.Token{ - AccessToken: t.AccessToken, - TokenType: t.TokenType, - RefreshToken: t.RefreshToken, - Expiry: t.Expiry, - } - return tk.WithExtra(t.Raw) -} - -// retrieveToken takes a *Config and uses that to retrieve an *internal.Token. -// This token is then mapped from *internal.Token into an *oauth2.Token which is -// returned along with an error. -func retrieveToken(ctx context.Context, c *Config, v url.Values) (*oauth2.Token, error) { - tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.TokenURL, v) - if err != nil { - return nil, err - } - return tokenFromInternal(tk), nil -} - -// Client Credentials Config describes a 2-legged OAuth2 flow, with both the -// client application information and the server's endpoint URLs. -type Config struct { - // ClientID is the application's ID. - ClientID string - - // ClientSecret is the application's secret. - ClientSecret string - - // TokenURL is the resource server's token endpoint - // URL. This is a constant specific to each server. - TokenURL string - - // Scope specifies optional requested permissions. - Scopes []string -} - -// Token uses client credentials to retreive a token. -// The HTTP client to use is derived from the context. -// If nil, http.DefaultClient is used. -func (c *Config) Token(ctx context.Context) (*oauth2.Token, error) { - return retrieveToken(ctx, c, url.Values{ - "grant_type": {"client_credentials"}, - "scope": internal.CondVal(strings.Join(c.Scopes, " ")), - }) -} - -// Client returns an HTTP client using the provided token. -// The token will auto-refresh as necessary. The underlying -// HTTP transport will be obtained using the provided context. -// The returned client and its Transport should not be modified. -func (c *Config) Client(ctx context.Context) *http.Client { - return oauth2.NewClient(ctx, c.TokenSource(ctx)) -} - -// TokenSource returns a TokenSource that returns t until t expires, -// automatically refreshing it as necessary using the provided context and the -// client ID and client secret. -// -// Most users will use Config.Client instead. -func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource { - source := &tokenSource{ - ctx: ctx, - conf: c, - } - return oauth2.ReuseTokenSource(nil, source) -} - -type tokenSource struct { - ctx context.Context - conf *Config -} - -// Token refreshes the token by using a new client credentials request. -// tokens received this way do not include a refresh token -func (c *tokenSource) Token() (*oauth2.Token, error) { - return retrieveToken(c.ctx, c.conf, url.Values{ - "grant_type": {"client_credentials"}, - "scope": internal.CondVal(strings.Join(c.conf.Scopes, " ")), - }) -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials_test.go deleted file mode 100644 index ab319e082..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2014 The oauth2 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 clientcredentials - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "golang.org/x/oauth2" -) - -func newConf(url string) *Config { - return &Config{ - ClientID: "CLIENT_ID", - ClientSecret: "CLIENT_SECRET", - Scopes: []string{"scope1", "scope2"}, - TokenURL: url + "/token", - } -} - -type mockTransport struct { - rt func(req *http.Request) (resp *http.Response, err error) -} - -func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { - return t.rt(req) -} - -func TestTokenRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("authenticate client request URL = %q; want %q", r.URL, "/token") - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - if got, want := r.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; got != want { - t.Errorf("Content-Type header = %q; want %q", got, want) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - r.Body.Close() - } - if err != nil { - t.Errorf("failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&grant_type=client_credentials&scope=scope1+scope2" { - t.Errorf("payload = %q; want %q", string(body), "client_id=CLIENT_ID&grant_type=client_credentials&scope=scope1+scope2") - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Token(oauth2.NoContext) - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("token invalid. got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Access token = %q; want %q", tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c") - } - if tok.TokenType != "bearer" { - t.Errorf("token type = %q; want %q", tok.TokenType, "bearer") - } -} - -func TestTokenRefreshRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=client_credentials&scope=scope1+scope2" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(oauth2.NoContext) - c.Get(ts.URL + "/somethingelse") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/example_test.go deleted file mode 100644 index 8be278855..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/example_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2014 The oauth2 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 oauth2_test - -import ( - "fmt" - "log" - - "golang.org/x/oauth2" -) - -func ExampleConfig() { - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - Scopes: []string{"SCOPE1", "SCOPE2"}, - Endpoint: oauth2.Endpoint{ - AuthURL: "https://provider.com/o/oauth2/auth", - TokenURL: "https://provider.com/o/oauth2/token", - }, - } - - // Redirect user to consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline) - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Use the authorization code that is pushed to the redirect URL. - // NewTransportWithCode will do the handshake to retrieve - // an access token and initiate a Transport that is - // authorized and authenticated by the retrieved token. - var code string - if _, err := fmt.Scan(&code); err != nil { - log.Fatal(err) - } - tok, err := conf.Exchange(oauth2.NoContext, code) - if err != nil { - log.Fatal(err) - } - - client := conf.Client(oauth2.NoContext, tok) - client.Get("...") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/facebook/facebook.go b/Godeps/_workspace/src/golang.org/x/oauth2/facebook/facebook.go deleted file mode 100644 index 9c816ff80..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/facebook/facebook.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015 The oauth2 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 facebook provides constants for using OAuth2 to access Facebook. -package facebook - -import ( - "golang.org/x/oauth2" -) - -// Endpoint is Facebook's OAuth 2.0 endpoint. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://www.facebook.com/dialog/oauth", - TokenURL: "https://graph.facebook.com/oauth/access_token", -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/github/github.go b/Godeps/_workspace/src/golang.org/x/oauth2/github/github.go deleted file mode 100644 index 82ca623dd..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/github/github.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2014 The oauth2 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 github provides constants for using OAuth2 to access Github. -package github - -import ( - "golang.org/x/oauth2" -) - -// Endpoint is Github's OAuth 2.0 endpoint. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://github.com/login/oauth/authorize", - TokenURL: "https://github.com/login/oauth/access_token", -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go deleted file mode 100644 index 17262802a..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2014 The oauth2 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 appenginevm !appengine - -package google_test - -import ( - "fmt" - "io/ioutil" - "log" - "net/http" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/appengine" - "google.golang.org/appengine/urlfetch" -) - -func ExampleDefaultClient() { - client, err := google.DefaultClient(oauth2.NoContext, - "https://www.googleapis.com/auth/devstorage.full_control") - if err != nil { - log.Fatal(err) - } - client.Get("...") -} - -func Example_webServer() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - RedirectURL: "YOUR_REDIRECT_URL", - Scopes: []string{ - "https://www.googleapis.com/auth/bigquery", - "https://www.googleapis.com/auth/blogger", - }, - Endpoint: google.Endpoint, - } - // Redirect user to Google's consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state") - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Handle the exchange code to initiate a transport. - tok, err := conf.Exchange(oauth2.NoContext, "authorization-code") - if err != nil { - log.Fatal(err) - } - client := conf.Client(oauth2.NoContext, tok) - client.Get("...") -} - -func ExampleJWTConfigFromJSON() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - // Navigate to your project, then see the "Credentials" page - // under "APIs & Auth". - // To create a service account client, click "Create new Client ID", - // select "Service Account", and click "Create Client ID". A JSON - // key file will then be downloaded to your computer. - data, err := ioutil.ReadFile("/path/to/your-project-key.json") - if err != nil { - log.Fatal(err) - } - conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/bigquery") - if err != nil { - log.Fatal(err) - } - // Initiate an http.Client. The following GET request will be - // authorized and authenticated on the behalf of - // your service account. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func ExampleSDKConfig() { - // The credentials will be obtained from the first account that - // has been authorized with `gcloud auth login`. - conf, err := google.NewSDKConfig("") - if err != nil { - log.Fatal(err) - } - // Initiate an http.Client. The following GET request will be - // authorized and authenticated on the behalf of the SDK user. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func Example_serviceAccount() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - conf := &jwt.Config{ - Email: "xxx@developer.gserviceaccount.com", - // The contents of your RSA private key or your PEM file - // that contains a private key. - // If you have a p12 file instead, you - // can use `openssl` to export the private key into a pem file. - // - // $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes - // - // The field only supports PEM containers with no passphrase. - // The openssl command will convert p12 keys to passphrase-less PEM containers. - PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."), - Scopes: []string{ - "https://www.googleapis.com/auth/bigquery", - "https://www.googleapis.com/auth/blogger", - }, - TokenURL: google.JWTTokenURL, - // If you would like to impersonate a user, you can - // create a transport with a subject. The following GET - // request will be made on the behalf of user@example.com. - // Optional. - Subject: "user@example.com", - } - // Initiate an http.Client, the following GET request will be - // authorized and authenticated on the behalf of user@example.com. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func ExampleAppEngineTokenSource() { - var req *http.Request // from the ServeHTTP handler - ctx := appengine.NewContext(req) - client := &http.Client{ - Transport: &oauth2.Transport{ - Source: google.AppEngineTokenSource(ctx, "https://www.googleapis.com/auth/bigquery"), - Base: &urlfetch.Transport{ - Context: ctx, - }, - }, - } - client.Get("...") -} - -func ExampleComputeTokenSource() { - client := &http.Client{ - Transport: &oauth2.Transport{ - // Fetch from Google Compute Engine's metadata server to retrieve - // an access token for the provided account. - // If no account is specified, "default" is used. - Source: google.ComputeTokenSource(""), - }, - } - client.Get("...") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/google_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/google_test.go deleted file mode 100644 index 4cc01884b..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/google_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2015 The oauth2 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 google - -import ( - "strings" - "testing" -) - -var webJSONKey = []byte(` -{ - "web": { - "auth_uri": "https://google.com/o/oauth2/auth", - "client_secret": "3Oknc4jS_wA2r9i", - "token_uri": "https://google.com/o/oauth2/token", - "client_email": "222-nprqovg5k43uum874cs9osjt2koe97g8@developer.gserviceaccount.com", - "redirect_uris": ["https://www.example.com/oauth2callback"], - "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/222-nprqovg5k43uum874cs9osjt2koe97g8@developer.gserviceaccount.com", - "client_id": "222-nprqovg5k43uum874cs9osjt2koe97g8.apps.googleusercontent.com", - "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", - "javascript_origins": ["https://www.example.com"] - } -}`) - -var installedJSONKey = []byte(`{ - "installed": { - "client_id": "222-installed.apps.googleusercontent.com", - "redirect_uris": ["https://www.example.com/oauth2callback"] - } -}`) - -func TestConfigFromJSON(t *testing.T) { - conf, err := ConfigFromJSON(webJSONKey, "scope1", "scope2") - if err != nil { - t.Error(err) - } - if got, want := conf.ClientID, "222-nprqovg5k43uum874cs9osjt2koe97g8.apps.googleusercontent.com"; got != want { - t.Errorf("ClientID = %q; want %q", got, want) - } - if got, want := conf.ClientSecret, "3Oknc4jS_wA2r9i"; got != want { - t.Errorf("ClientSecret = %q; want %q", got, want) - } - if got, want := conf.RedirectURL, "https://www.example.com/oauth2callback"; got != want { - t.Errorf("RedictURL = %q; want %q", got, want) - } - if got, want := strings.Join(conf.Scopes, ","), "scope1,scope2"; got != want { - t.Errorf("Scopes = %q; want %q", got, want) - } - if got, want := conf.Endpoint.AuthURL, "https://google.com/o/oauth2/auth"; got != want { - t.Errorf("AuthURL = %q; want %q", got, want) - } - if got, want := conf.Endpoint.TokenURL, "https://google.com/o/oauth2/token"; got != want { - t.Errorf("TokenURL = %q; want %q", got, want) - } -} - -func TestConfigFromJSON_Installed(t *testing.T) { - conf, err := ConfigFromJSON(installedJSONKey) - if err != nil { - t.Error(err) - } - if got, want := conf.ClientID, "222-installed.apps.googleusercontent.com"; got != want { - t.Errorf("ClientID = %q; want %q", got, want) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go deleted file mode 100644 index 79df88964..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2015 The oauth2 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 google - -import "testing" - -func TestSDKConfig(t *testing.T) { - sdkConfigPath = func() (string, error) { - return "testdata/gcloud", nil - } - - tests := []struct { - account string - accessToken string - err bool - }{ - {"", "bar_access_token", false}, - {"foo@example.com", "foo_access_token", false}, - {"bar@example.com", "bar_access_token", false}, - {"baz@serviceaccount.example.com", "", true}, - } - for _, tt := range tests { - c, err := NewSDKConfig(tt.account) - if got, want := err != nil, tt.err; got != want { - if !tt.err { - t.Errorf("expected no error, got error: %v", tt.err, err) - } else { - t.Errorf("expected error, got none") - } - continue - } - if err != nil { - continue - } - tok := c.initialToken - if tok == nil { - t.Errorf("expected token %q, got: nil", tt.accessToken) - continue - } - if tok.AccessToken != tt.accessToken { - t.Errorf("expected token %q, got: %q", tt.accessToken, tok.AccessToken) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials b/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials deleted file mode 100644 index ff5eefbd0..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/credentials +++ /dev/null @@ -1,122 +0,0 @@ -{ - "data": [ - { - "credential": { - "_class": "OAuth2Credentials", - "_module": "oauth2client.client", - "access_token": "foo_access_token", - "client_id": "foo_client_id", - "client_secret": "foo_client_secret", - "id_token": { - "at_hash": "foo_at_hash", - "aud": "foo_aud", - "azp": "foo_azp", - "cid": "foo_cid", - "email": "foo@example.com", - "email_verified": true, - "exp": 1420573614, - "iat": 1420569714, - "id": "1337", - "iss": "accounts.google.com", - "sub": "1337", - "token_hash": "foo_token_hash", - "verified_email": true - }, - "invalid": false, - "refresh_token": "foo_refresh_token", - "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "token_expiry": "2015-01-09T00:51:51Z", - "token_response": { - "access_token": "foo_access_token", - "expires_in": 3600, - "id_token": "foo_id_token", - "token_type": "Bearer" - }, - "token_uri": "https://accounts.google.com/o/oauth2/token", - "user_agent": "Cloud SDK Command Line Tool" - }, - "key": { - "account": "foo@example.com", - "clientId": "foo_client_id", - "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "type": "google-cloud-sdk" - } - }, - { - "credential": { - "_class": "OAuth2Credentials", - "_module": "oauth2client.client", - "access_token": "bar_access_token", - "client_id": "bar_client_id", - "client_secret": "bar_client_secret", - "id_token": { - "at_hash": "bar_at_hash", - "aud": "bar_aud", - "azp": "bar_azp", - "cid": "bar_cid", - "email": "bar@example.com", - "email_verified": true, - "exp": 1420573614, - "iat": 1420569714, - "id": "1337", - "iss": "accounts.google.com", - "sub": "1337", - "token_hash": "bar_token_hash", - "verified_email": true - }, - "invalid": false, - "refresh_token": "bar_refresh_token", - "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "token_expiry": "2015-01-09T00:51:51Z", - "token_response": { - "access_token": "bar_access_token", - "expires_in": 3600, - "id_token": "bar_id_token", - "token_type": "Bearer" - }, - "token_uri": "https://accounts.google.com/o/oauth2/token", - "user_agent": "Cloud SDK Command Line Tool" - }, - "key": { - "account": "bar@example.com", - "clientId": "bar_client_id", - "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "type": "google-cloud-sdk" - } - }, - { - "credential": { - "_class": "ServiceAccountCredentials", - "_kwargs": {}, - "_module": "oauth2client.client", - "_private_key_id": "00000000000000000000000000000000", - "_private_key_pkcs8_text": "-----BEGIN RSA PRIVATE KEY-----\nMIICWwIBAAKBgQCt3fpiynPSaUhWSIKMGV331zudwJ6GkGmvQtwsoK2S2LbvnSwU\nNxgj4fp08kIDR5p26wF4+t/HrKydMwzftXBfZ9UmLVJgRdSswmS5SmChCrfDS5OE\nvFFcN5+6w1w8/Nu657PF/dse8T0bV95YrqyoR0Osy8WHrUOMSIIbC3hRuwIDAQAB\nAoGAJrGE/KFjn0sQ7yrZ6sXmdLawrM3mObo/2uI9T60+k7SpGbBX0/Pi6nFrJMWZ\nTVONG7P3Mu5aCPzzuVRYJB0j8aldSfzABTY3HKoWCczqw1OztJiEseXGiYz4QOyr\nYU3qDyEpdhS6q6wcoLKGH+hqRmz6pcSEsc8XzOOu7s4xW8kCQQDkc75HjhbarCnd\nJJGMe3U76+6UGmdK67ltZj6k6xoB5WbTNChY9TAyI2JC+ppYV89zv3ssj4L+02u3\nHIHFGxsHAkEAwtU1qYb1tScpchPobnYUFiVKJ7KA8EZaHVaJJODW/cghTCV7BxcJ\nbgVvlmk4lFKn3lPKAgWw7PdQsBTVBUcCrQJATPwoIirizrv3u5soJUQxZIkENAqV\nxmybZx9uetrzP7JTrVbFRf0SScMcyN90hdLJiQL8+i4+gaszgFht7sNMnwJAAbfj\nq0UXcauQwALQ7/h2oONfTg5S+MuGC/AxcXPSMZbMRGGoPh3D5YaCv27aIuS/ukQ+\n6dmm/9AGlCb64fsIWQJAPaokbjIifo+LwC5gyK73Mc4t8nAOSZDenzd/2f6TCq76\nS1dcnKiPxaED7W/y6LJiuBT2rbZiQ2L93NJpFZD/UA==\n-----END RSA PRIVATE KEY-----\n", - "_revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "_scopes": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "_service_account_email": "baz@serviceaccount.example.com", - "_service_account_id": "baz.serviceaccount.example.com", - "_token_uri": "https://accounts.google.com/o/oauth2/token", - "_user_agent": "Cloud SDK Command Line Tool", - "access_token": null, - "assertion_type": null, - "client_id": null, - "client_secret": null, - "id_token": null, - "invalid": false, - "refresh_token": null, - "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", - "service_account_name": "baz@serviceaccount.example.com", - "token_expiry": null, - "token_response": null, - "user_agent": "Cloud SDK Command Line Tool" - }, - "key": { - "account": "baz@serviceaccount.example.com", - "clientId": "baz_client_id", - "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", - "type": "google-cloud-sdk" - } - } - ], - "file_version": 1 -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/properties b/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/properties deleted file mode 100644 index 025de886c..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/testdata/gcloud/properties +++ /dev/null @@ -1,2 +0,0 @@ -[core] -account = bar@example.com \ No newline at end of file diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2_test.go deleted file mode 100644 index 014a351e0..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 The oauth2 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 internal contains support packages for oauth2 package. -package internal - -import ( - "reflect" - "strings" - "testing" -) - -func TestParseINI(t *testing.T) { - tests := []struct { - ini string - want map[string]map[string]string - }{ - { - `root = toor -[foo] -bar = hop -ini = nin -`, - map[string]map[string]string{ - "": map[string]string{"root": "toor"}, - "foo": map[string]string{"bar": "hop", "ini": "nin"}, - }, - }, - { - `[empty] -[section] -empty= -`, - map[string]map[string]string{ - "": map[string]string{}, - "empty": map[string]string{}, - "section": map[string]string{"empty": ""}, - }, - }, - { - `ignore -[invalid -=stuff -;comment=true -`, - map[string]map[string]string{ - "": map[string]string{}, - }, - }, - } - for _, tt := range tests { - result, err := ParseINI(strings.NewReader(tt.ini)) - if err != nil { - t.Errorf("ParseINI(%q) error %v, want: no error", tt.ini, err) - continue - } - if !reflect.DeepEqual(result, tt.want) { - t.Errorf("ParseINI(%q) = %#v, want: %#v", tt.ini, result, tt.want) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/token_test.go deleted file mode 100644 index 864f6fa07..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2014 The oauth2 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 internal contains support packages for oauth2 package. -package internal - -import ( - "fmt" - "testing" -) - -func Test_providerAuthHeaderWorks(t *testing.T) { - for _, p := range brokenAuthHeaderProviders { - if providerAuthHeaderWorks(p) { - t.Errorf("URL: %s not found in list", p) - } - p := fmt.Sprintf("%ssomesuffix", p) - if providerAuthHeaderWorks(p) { - t.Errorf("URL: %s not found in list", p) - } - } - p := "https://api.not-in-the-list-example.com/" - if !providerAuthHeaderWorks(p) { - t.Errorf("URL: %s found in list", p) - } - -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go deleted file mode 100644 index 6d618836e..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2014 The oauth2 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 jwt_test - -import ( - "golang.org/x/oauth2" - "golang.org/x/oauth2/jwt" -) - -func ExampleJWTConfig() { - conf := &jwt.Config{ - Email: "xxx@developer.com", - // The contents of your RSA private key or your PEM file - // that contains a private key. - // If you have a p12 file instead, you - // can use `openssl` to export the private key into a pem file. - // - // $ openssl pkcs12 -in key.p12 -out key.pem -nodes - // - // It only supports PEM containers with no passphrase. - PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."), - Subject: "user@example.com", - TokenURL: "https://provider.com/o/oauth2/token", - } - // Initiate an http.Client, the following GET request will be - // authorized and authenticated on the behalf of user@example.com. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go deleted file mode 100644 index da922c3d0..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2014 The oauth2 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 jwt - -import ( - "net/http" - "net/http/httptest" - "testing" - - "golang.org/x/oauth2" -) - -var dummyPrivateKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE -DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY -fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK -1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr -k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9 -/E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt -3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn -2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3 -nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK -6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf -5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e -DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1 -M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g -z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y -1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK -J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U -f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx -QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA -cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr -Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw -5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg -KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84 -OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd -mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ -5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg== ------END RSA PRIVATE KEY-----`) - -func TestJWTFetch_JSONResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{ - "access_token": "90d64460d14870c08c81352a05dedd3465940a7c", - "scope": "user", - "token_type": "bearer", - "expires_in": 3600 - }`)) - })) - defer ts.Close() - - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(oauth2.NoContext).Token() - if err != nil { - t.Fatal(err) - } - if !tok.Valid() { - t.Errorf("Token invalid") - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v", tok.TokenType) - } - if tok.Expiry.IsZero() { - t.Errorf("Unexpected token expiry, %#v", tok.Expiry) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -func TestJWTFetch_BadResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(oauth2.NoContext).Token() - if err != nil { - t.Fatal(err) - } - if tok == nil { - t.Fatalf("token is nil") - } - if tok.Valid() { - t.Errorf("token is valid. want invalid.") - } - if tok.AccessToken != "" { - t.Errorf("Unexpected non-empty access token %q.", tok.AccessToken) - } - if want := "bearer"; tok.TokenType != want { - t.Errorf("TokenType = %q; want %q", tok.TokenType, want) - } - scope := tok.Extra("scope") - if want := "user"; scope != want { - t.Errorf("token scope = %q; want %q", scope, want) - } -} - -func TestJWTFetch_BadResponseType(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(oauth2.NoContext).Token() - if err == nil { - t.Error("got a token; expected error") - if tok.AccessToken != "" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/linkedin/linkedin.go b/Godeps/_workspace/src/golang.org/x/oauth2/linkedin/linkedin.go deleted file mode 100644 index d93fded6a..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/linkedin/linkedin.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015 The oauth2 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 linkedin provides constants for using OAuth2 to access LinkedIn. -package linkedin - -import ( - "golang.org/x/oauth2" -) - -// Endpoint is LinkedIn's OAuth 2.0 endpoint. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://www.linkedin.com/uas/oauth2/authorization", - TokenURL: "https://www.linkedin.com/uas/oauth2/accessToken", -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/oauth2_test.go deleted file mode 100644 index 2f7d731c1..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2_test.go +++ /dev/null @@ -1,422 +0,0 @@ -// Copyright 2014 The oauth2 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 oauth2 - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "strconv" - "testing" - "time" - - "golang.org/x/net/context" -) - -type mockTransport struct { - rt func(req *http.Request) (resp *http.Response, err error) -} - -func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { - return t.rt(req) -} - -type mockCache struct { - token *Token - readErr error -} - -func (c *mockCache) ReadToken() (*Token, error) { - return c.token, c.readErr -} - -func (c *mockCache) WriteToken(*Token) { - // do nothing -} - -func newConf(url string) *Config { - return &Config{ - ClientID: "CLIENT_ID", - ClientSecret: "CLIENT_SECRET", - RedirectURL: "REDIRECT_URL", - Scopes: []string{"scope1", "scope2"}, - Endpoint: Endpoint{ - AuthURL: url + "/auth", - TokenURL: url + "/token", - }, - } -} - -func TestAuthCodeURL(t *testing.T) { - conf := newConf("server") - url := conf.AuthCodeURL("foo", AccessTypeOffline, ApprovalForce) - if url != "server/auth?access_type=offline&approval_prompt=force&client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=foo" { - t.Errorf("Auth code URL doesn't match the expected, found: %v", url) - } -} - -func TestAuthCodeURL_CustomParam(t *testing.T) { - conf := newConf("server") - param := SetAuthURLParam("foo", "bar") - url := conf.AuthCodeURL("baz", param) - if url != "server/auth?client_id=CLIENT_ID&foo=bar&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=baz" { - t.Errorf("Auth code URL doesn't match the expected, found: %v", url) - } -} - -func TestAuthCodeURL_Optional(t *testing.T) { - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "/auth-url", - TokenURL: "/token-url", - }, - } - url := conf.AuthCodeURL("") - if url != "/auth-url?client_id=CLIENT_ID&response_type=code" { - t.Fatalf("Auth code URL doesn't match the expected, found: %v", url) - } -} - -func TestExchangeRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(NoContext, "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -func TestExchangeRequest_JSONResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(NoContext, "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -const day = 24 * time.Hour - -func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) { - seconds := int32(day.Seconds()) - jsonNumberType := reflect.TypeOf(json.Number("0")) - for _, c := range []struct { - expires string - expect error - }{ - {fmt.Sprintf(`"expires_in": %d`, seconds), nil}, - {fmt.Sprintf(`"expires_in": "%d"`, seconds), nil}, // PayPal case - {fmt.Sprintf(`"expires": %d`, seconds), nil}, // Facebook case - {`"expires": false`, &json.UnmarshalTypeError{Value: "bool", Type: jsonNumberType}}, // wrong type - {`"expires": {}`, &json.UnmarshalTypeError{Value: "object", Type: jsonNumberType}}, // wrong type - {`"expires": "zzz"`, &strconv.NumError{Func: "ParseInt", Num: "zzz", Err: strconv.ErrSyntax}}, // wrong value - } { - testExchangeRequest_JSONResponse_expiry(t, c.expires, c.expect) - } -} - -func testExchangeRequest_JSONResponse_expiry(t *testing.T, exp string, expect error) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(fmt.Sprintf(`{"access_token": "90d", "scope": "user", "token_type": "bearer", %s}`, exp))) - })) - defer ts.Close() - conf := newConf(ts.URL) - t1 := time.Now().Add(day) - tok, err := conf.Exchange(NoContext, "exchange-code") - t2 := time.Now().Add(day) - // Do a fmt.Sprint comparison so either side can be - // nil. fmt.Sprint just stringifies them to "", and no - // non-nil expected error ever stringifies as "", so this - // isn't terribly disgusting. We do this because Go 1.4 and - // Go 1.5 return a different deep value for - // json.UnmarshalTypeError. In Go 1.5, the - // json.UnmarshalTypeError contains a new field with a new - // non-zero value. Rather than ignore it here with reflect or - // add new files and +build tags, just look at the strings. - if fmt.Sprint(err) != fmt.Sprint(expect) { - t.Errorf("Error = %v; want %v", err, expect) - } - if err != nil { - return - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expiry := tok.Expiry - if expiry.Before(t1) || expiry.After(t2) { - t.Errorf("Unexpected value for Expiry: %v (shold be between %v and %v)", expiry, t1, t2) - } -} - -func TestExchangeRequest_BadResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(NoContext, "code") - if err != nil { - t.Fatal(err) - } - if tok.AccessToken != "" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } -} - -func TestExchangeRequest_BadResponseType(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - _, err := conf.Exchange(NoContext, "exchange-code") - if err == nil { - t.Error("expected error from invalid access_token type") - } -} - -func TestExchangeRequest_NonBasicAuth(t *testing.T) { - tr := &mockTransport{ - rt: func(r *http.Request) (w *http.Response, err error) { - headerAuth := r.Header.Get("Authorization") - if headerAuth != "" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - return nil, errors.New("no response") - }, - } - c := &http.Client{Transport: tr} - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "https://accounts.google.com/auth", - TokenURL: "https://accounts.google.com/token", - }, - } - - ctx := context.WithValue(context.Background(), HTTPClient, c) - conf.Exchange(ctx, "code") -} - -func TestPasswordCredentialsTokenRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer r.Body.Close() - expected := "/token" - if r.URL.String() != expected { - t.Errorf("URL = %q; want %q", r.URL, expected) - } - headerAuth := r.Header.Get("Authorization") - expected = "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" - if headerAuth != expected { - t.Errorf("Authorization header = %q; want %q", headerAuth, expected) - } - headerContentType := r.Header.Get("Content-Type") - expected = "application/x-www-form-urlencoded" - if headerContentType != expected { - t.Errorf("Content-Type header = %q; want %q", headerContentType, expected) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - expected = "client_id=CLIENT_ID&grant_type=password&password=password1&scope=scope1+scope2&username=user1" - if string(body) != expected { - t.Errorf("res.Body = %q; want %q", string(body), expected) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.PasswordCredentialsToken(NoContext, "user1", "password1") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expected := "90d64460d14870c08c81352a05dedd3465940a7c" - if tok.AccessToken != expected { - t.Errorf("AccessToken = %q; want %q", tok.AccessToken, expected) - } - expected = "bearer" - if tok.TokenType != expected { - t.Errorf("TokenType = %q; want %q", tok.TokenType, expected) - } -} - -func TestTokenRefreshRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(NoContext, &Token{RefreshToken: "REFRESH_TOKEN"}) - c.Get(ts.URL + "/somethingelse") -} - -func TestFetchWithNoRefreshToken(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(NoContext, nil) - _, err := c.Get(ts.URL + "/somethingelse") - if err == nil { - t.Errorf("Fetch should return an error if no refresh token is set") - } -} - -func TestRefreshToken_RefreshTokenReplacement(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":"ACCESS TOKEN", "scope": "user", "token_type": "bearer", "refresh_token": "NEW REFRESH TOKEN"}`)) - return - })) - defer ts.Close() - conf := newConf(ts.URL) - tkr := tokenRefresher{ - conf: conf, - ctx: NoContext, - refreshToken: "OLD REFRESH TOKEN", - } - tk, err := tkr.Token() - if err != nil { - t.Errorf("Unexpected refreshToken error returned: %v", err) - return - } - if tk.RefreshToken != tkr.refreshToken { - t.Errorf("tokenRefresher.refresh_token = %s; want %s", tkr.refreshToken, tk.RefreshToken) - } -} - -func TestConfigClientWithToken(t *testing.T) { - tok := &Token{ - AccessToken: "abc123", - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer %s", tok.AccessToken); got != want { - t.Errorf("Authorization header = %q; want %q", got, want) - } - return - })) - defer ts.Close() - conf := newConf(ts.URL) - - c := conf.Client(NoContext, tok) - req, err := http.NewRequest("GET", ts.URL, nil) - if err != nil { - t.Error(err) - } - _, err = c.Do(req) - if err != nil { - t.Error(err) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go b/Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go deleted file mode 100644 index f0b66f97d..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015 The oauth2 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 odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. -package odnoklassniki - -import ( - "golang.org/x/oauth2" -) - -// Endpoint is Odnoklassniki's OAuth 2.0 endpoint. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://www.odnoklassniki.ru/oauth/authorize", - TokenURL: "https://api.odnoklassniki.ru/oauth/token.do", -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/paypal/paypal.go b/Godeps/_workspace/src/golang.org/x/oauth2/paypal/paypal.go deleted file mode 100644 index a99366b6e..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/paypal/paypal.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2015 The oauth2 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 paypal provides constants for using OAuth2 to access PayPal. -package paypal - -import ( - "golang.org/x/oauth2" -) - -// Endpoint is PayPal's OAuth 2.0 endpoint in live (production) environment. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize", - TokenURL: "https://api.paypal.com/v1/identity/openidconnect/tokenservice", -} - -// SandboxEndpoint is PayPal's OAuth 2.0 endpoint in sandbox (testing) environment. -var SandboxEndpoint = oauth2.Endpoint{ - AuthURL: "https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize", - TokenURL: "https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice", -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/token_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/token_test.go deleted file mode 100644 index 739eeb2a2..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/token_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The oauth2 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 oauth2 - -import ( - "testing" - "time" -) - -func TestTokenExtra(t *testing.T) { - type testCase struct { - key string - val interface{} - want interface{} - } - const key = "extra-key" - cases := []testCase{ - {key: key, val: "abc", want: "abc"}, - {key: key, val: 123, want: 123}, - {key: key, val: "", want: ""}, - {key: "other-key", val: "def", want: nil}, - } - for _, tc := range cases { - extra := make(map[string]interface{}) - extra[tc.key] = tc.val - tok := &Token{raw: extra} - if got, want := tok.Extra(key), tc.want; got != want { - t.Errorf("Extra(%q) = %q; want %q", key, got, want) - } - } -} - -func TestTokenExpiry(t *testing.T) { - now := time.Now() - cases := []struct { - name string - tok *Token - want bool - }{ - {name: "12 seconds", tok: &Token{Expiry: now.Add(12 * time.Second)}, want: false}, - {name: "10 seconds", tok: &Token{Expiry: now.Add(expiryDelta)}, want: true}, - } - for _, tc := range cases { - if got, want := tc.tok.expired(), tc.want; got != want { - t.Errorf("expired (%q) = %v; want %v", tc.name, got, want) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go deleted file mode 100644 index 35cb25ed5..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package oauth2 - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" -) - -type tokenSource struct{ token *Token } - -func (t *tokenSource) Token() (*Token, error) { - return t.token, nil -} - -func TestTransportTokenSource(t *testing.T) { - ts := &tokenSource{ - token: &Token{ - AccessToken: "abc", - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Authorization") != "Bearer abc" { - t.Errorf("Transport doesn't set the Authorization header from the fetched token") - } - }) - defer server.Close() - client := http.Client{Transport: tr} - client.Get(server.URL) -} - -// Test for case-sensitive token types, per https://github.com/golang/oauth2/issues/113 -func TestTransportTokenSourceTypes(t *testing.T) { - const val = "abc" - tests := []struct { - key string - val string - want string - }{ - {key: "bearer", val: val, want: "Bearer abc"}, - {key: "mac", val: val, want: "MAC abc"}, - {key: "basic", val: val, want: "Basic abc"}, - } - for _, tc := range tests { - ts := &tokenSource{ - token: &Token{ - AccessToken: tc.val, - TokenType: tc.key, - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), tc.want; got != want { - t.Errorf("Authorization header (%q) = %q; want %q", val, got, want) - } - }) - defer server.Close() - client := http.Client{Transport: tr} - client.Get(server.URL) - } -} - -func TestTokenValidNoAccessToken(t *testing.T) { - token := &Token{} - if token.Valid() { - t.Errorf("Token should not be valid with no access token") - } -} - -func TestExpiredWithExpiry(t *testing.T) { - token := &Token{ - Expiry: time.Now().Add(-5 * time.Hour), - } - if token.Valid() { - t.Errorf("Token should not be valid if it expired in the past") - } -} - -func newMockServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(handler)) -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/vk/vk.go b/Godeps/_workspace/src/golang.org/x/oauth2/vk/vk.go deleted file mode 100644 index 00e929357..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/vk/vk.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015 The oauth2 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 vk provides constants for using OAuth2 to access VK.com. -package vk - -import ( - "golang.org/x/oauth2" -) - -// Endpoint is VK's OAuth 2.0 endpoint. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://oauth.vk.com/authorize", - TokenURL: "https://oauth.vk.com/access_token", -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE b/Godeps/_workspace/src/google.golang.org/api/LICENSE similarity index 83% rename from Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE rename to Godeps/_workspace/src/google.golang.org/api/LICENSE index 0e5fb8728..263aa7a0c 100644 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE +++ b/Godeps/_workspace/src/google.golang.org/api/LICENSE @@ -1,16 +1,16 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. +Copyright (c) 2011 Google Inc. 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 + * 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 + * 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 + * 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. diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/json_test.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/json_test.go deleted file mode 100644 index b2f921913..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/json_test.go +++ /dev/null @@ -1,367 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "encoding/json" - "reflect" - "testing" - - "google.golang.org/api/googleapi" -) - -type schema struct { - // Basic types - B bool `json:"b,omitempty"` - F float64 `json:"f,omitempty"` - I int64 `json:"i,omitempty"` - Istr int64 `json:"istr,omitempty,string"` - Str string `json:"str,omitempty"` - - // Pointers to basic types - PB *bool `json:"pb,omitempty"` - PF *float64 `json:"pf,omitempty"` - PI *int64 `json:"pi,omitempty"` - PIStr *int64 `json:"pistr,omitempty,string"` - PStr *string `json:"pstr,omitempty"` - - // Other types - Int64s googleapi.Int64s `json:"i64s,omitempty"` - S []int `json:"s,omitempty"` - M map[string]string `json:"m,omitempty"` - Any interface{} `json:"any,omitempty"` - Child *child `json:"child,omitempty"` - - ForceSendFields []string `json:"-"` -} - -type child struct { - B bool `json:"childbool,omitempty"` -} - -type testCase struct { - s schema - want string -} - -func TestBasics(t *testing.T) { - for _, tc := range []testCase{ - { - s: schema{}, - want: `{}`, - }, - { - s: schema{ - ForceSendFields: []string{"B", "F", "I", "Istr", "Str", "PB", "PF", "PI", "PIStr", "PStr"}, - }, - want: `{"b":false,"f":0.0,"i":0,"istr":"0","str":""}`, - }, - { - s: schema{ - B: true, - F: 1.2, - I: 1, - Istr: 2, - Str: "a", - PB: googleapi.Bool(true), - PF: googleapi.Float64(1.2), - PI: googleapi.Int64(int64(1)), - PIStr: googleapi.Int64(int64(2)), - PStr: googleapi.String("a"), - }, - want: `{"b":true,"f":1.2,"i":1,"istr":"2","str":"a","pb":true,"pf":1.2,"pi":1,"pistr":"2","pstr":"a"}`, - }, - { - s: schema{ - B: false, - F: 0.0, - I: 0, - Istr: 0, - Str: "", - PB: googleapi.Bool(false), - PF: googleapi.Float64(0.0), - PI: googleapi.Int64(int64(0)), - PIStr: googleapi.Int64(int64(0)), - PStr: googleapi.String(""), - }, - want: `{"pb":false,"pf":0.0,"pi":0,"pistr":"0","pstr":""}`, - }, - { - s: schema{ - B: false, - F: 0.0, - I: 0, - Istr: 0, - Str: "", - PB: googleapi.Bool(false), - PF: googleapi.Float64(0.0), - PI: googleapi.Int64(int64(0)), - PIStr: googleapi.Int64(int64(0)), - PStr: googleapi.String(""), - ForceSendFields: []string{"B", "F", "I", "Istr", "Str", "PB", "PF", "PI", "PIStr", "PStr"}, - }, - want: `{"b":false,"f":0.0,"i":0,"istr":"0","str":"","pb":false,"pf":0.0,"pi":0,"pistr":"0","pstr":""}`, - }, - } { - checkMarshalJSON(t, tc) - } -} - -func TestSliceFields(t *testing.T) { - for _, tc := range []testCase{ - { - s: schema{}, - want: `{}`, - }, - { - s: schema{S: []int{}, Int64s: googleapi.Int64s{}}, - want: `{}`, - }, - { - s: schema{S: []int{1}, Int64s: googleapi.Int64s{1}}, - want: `{"s":[1],"i64s":["1"]}`, - }, - { - s: schema{ - ForceSendFields: []string{"S", "Int64s"}, - }, - want: `{"s":[],"i64s":[]}`, - }, - { - s: schema{ - S: []int{}, - Int64s: googleapi.Int64s{}, - ForceSendFields: []string{"S", "Int64s"}, - }, - want: `{"s":[],"i64s":[]}`, - }, - { - s: schema{ - S: []int{1}, - Int64s: googleapi.Int64s{1}, - ForceSendFields: []string{"S", "Int64s"}, - }, - want: `{"s":[1],"i64s":["1"]}`, - }, - } { - checkMarshalJSON(t, tc) - } -} - -func TestMapField(t *testing.T) { - for _, tc := range []testCase{ - { - s: schema{}, - want: `{}`, - }, - { - s: schema{M: make(map[string]string)}, - want: `{}`, - }, - { - s: schema{M: map[string]string{"a": "b"}}, - want: `{"m":{"a":"b"}}`, - }, - { - s: schema{ - ForceSendFields: []string{"M"}, - }, - want: `{"m":{}}`, - }, - { - s: schema{ - M: make(map[string]string), - ForceSendFields: []string{"M"}, - }, - want: `{"m":{}}`, - }, - { - s: schema{ - M: map[string]string{"a": "b"}, - ForceSendFields: []string{"M"}, - }, - want: `{"m":{"a":"b"}}`, - }, - } { - checkMarshalJSON(t, tc) - } -} - -type anyType struct { - Field int -} - -func (a anyType) MarshalJSON() ([]byte, error) { - return []byte(`"anyType value"`), nil -} - -func TestAnyField(t *testing.T) { - // ForceSendFields has no effect on nil interfaces and interfaces that contain nil pointers. - var nilAny *anyType - for _, tc := range []testCase{ - { - s: schema{}, - want: `{}`, - }, - { - s: schema{Any: nilAny}, - want: `{"any": null}`, - }, - { - s: schema{Any: &anyType{}}, - want: `{"any":"anyType value"}`, - }, - { - s: schema{Any: anyType{}}, - want: `{"any":"anyType value"}`, - }, - { - s: schema{ - ForceSendFields: []string{"Any"}, - }, - want: `{}`, - }, - { - s: schema{ - Any: nilAny, - ForceSendFields: []string{"Any"}, - }, - want: `{"any": null}`, - }, - { - s: schema{ - Any: &anyType{}, - ForceSendFields: []string{"Any"}, - }, - want: `{"any":"anyType value"}`, - }, - { - s: schema{ - Any: anyType{}, - ForceSendFields: []string{"Any"}, - }, - want: `{"any":"anyType value"}`, - }, - } { - checkMarshalJSON(t, tc) - } -} - -func TestSubschema(t *testing.T) { - // Subschemas are always stored as pointers, so ForceSendFields has no effect on them. - for _, tc := range []testCase{ - { - s: schema{}, - want: `{}`, - }, - { - s: schema{ - ForceSendFields: []string{"Child"}, - }, - want: `{}`, - }, - { - s: schema{Child: &child{}}, - want: `{"child":{}}`, - }, - { - s: schema{ - Child: &child{}, - ForceSendFields: []string{"Child"}, - }, - want: `{"child":{}}`, - }, - { - s: schema{Child: &child{B: true}}, - want: `{"child":{"childbool":true}}`, - }, - - { - s: schema{ - Child: &child{B: true}, - ForceSendFields: []string{"Child"}, - }, - want: `{"child":{"childbool":true}}`, - }, - } { - checkMarshalJSON(t, tc) - } -} - -// checkMarshalJSON verifies that calling schemaToMap on tc.s yields a result which is equivalent to tc.want. -func checkMarshalJSON(t *testing.T, tc testCase) { - doCheckMarshalJSON(t, tc.s, tc.s.ForceSendFields, tc.want) - if len(tc.s.ForceSendFields) == 0 { - // verify that the code path used when ForceSendFields - // is non-empty produces the same output as the fast - // path that is used when it is empty. - doCheckMarshalJSON(t, tc.s, []string{"dummy"}, tc.want) - } -} - -func doCheckMarshalJSON(t *testing.T, s schema, forceSendFields []string, wantJSON string) { - encoded, err := MarshalJSON(s, forceSendFields) - if err != nil { - t.Fatalf("encoding json:\n got err: %v", err) - } - - // The expected and obtained JSON can differ in field ordering, so unmarshal before comparing. - var got interface{} - var want interface{} - err = json.Unmarshal(encoded, &got) - if err != nil { - t.Fatalf("decoding json:\n got err: %v", err) - } - err = json.Unmarshal([]byte(wantJSON), &want) - if err != nil { - t.Fatalf("decoding json:\n got err: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Errorf("schemaToMap:\ngot :%s\nwant:%s", got, want) - } -} - -func TestParseJSONTag(t *testing.T) { - for _, tc := range []struct { - tag string - want jsonTag - }{ - { - tag: "-", - want: jsonTag{ignore: true}, - }, { - tag: "name,omitempty", - want: jsonTag{apiName: "name"}, - }, { - tag: "name,omitempty,string", - want: jsonTag{apiName: "name", stringFormat: true}, - }, - } { - got, err := parseJSONTag(tc.tag) - if err != nil { - t.Fatalf("parsing json:\n got err: %v\ntag: %q", err, tc.tag) - } - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("parseJSONTage:\ngot :%s\nwant:%s", got, tc.want) - } - } -} -func TestParseMalformedJSONTag(t *testing.T) { - for _, tag := range []string{ - "", - "name", - "name,", - "name,blah", - "name,blah,string", - ",omitempty", - ",omitempty,string", - "name,omitempty,string,blah", - } { - _, err := parseJSONTag(tag) - if err == nil { - t.Fatalf("parsing json: expected err, got nil for tag: %v", tag) - } - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/media_test.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/media_test.go deleted file mode 100644 index 72edb453e..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/media_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "reflect" - "testing" -) - -// errReader reads out of a buffer until it is empty, then returns the specified error. -type errReader struct { - buf []byte - err error -} - -var errBang error = errors.New("bang") - -func (er *errReader) Read(p []byte) (int, error) { - if len(er.buf) == 0 { - if er.err == nil { - return 0, io.EOF - } - return 0, er.err - } - n := copy(p, er.buf) - er.buf = er.buf[n:] - return n, nil -} - -func TestAll(t *testing.T) { - type testCase struct { - data []byte // the data to read from the Reader - finalErr error // error to return after data has been read - - wantContentType string - wantContentTypeResult bool - } - - for _, tc := range []testCase{ - { - data: []byte{0, 0, 0, 0}, - finalErr: nil, - wantContentType: "application/octet-stream", - wantContentTypeResult: true, - }, - { - data: []byte(""), - finalErr: nil, - wantContentType: "text/plain; charset=utf-8", - wantContentTypeResult: true, - }, - { - data: []byte(""), - finalErr: errBang, - wantContentType: "text/plain; charset=utf-8", - wantContentTypeResult: false, - }, - { - data: []byte("abc"), - finalErr: nil, - wantContentType: "text/plain; charset=utf-8", - wantContentTypeResult: true, - }, - { - data: []byte("abc"), - finalErr: errBang, - wantContentType: "text/plain; charset=utf-8", - wantContentTypeResult: false, - }, - // The following examples contain more bytes than are buffered for sniffing. - { - data: bytes.Repeat([]byte("a"), 513), - finalErr: nil, - wantContentType: "text/plain; charset=utf-8", - wantContentTypeResult: true, - }, - { - data: bytes.Repeat([]byte("a"), 513), - finalErr: errBang, - wantContentType: "text/plain; charset=utf-8", - wantContentTypeResult: true, // true because error is after first 512 bytes. - }, - } { - er := &errReader{buf: tc.data, err: tc.finalErr} - - sct := NewContentSniffer(er) - - // Even if was an error during the first 512 bytes, we should still be able to read those bytes. - buf, err := ioutil.ReadAll(sct) - - if !reflect.DeepEqual(buf, tc.data) { - t.Fatalf("Failed reading buffer: got: %q; want:%q", buf, tc.data) - } - - if err != tc.finalErr { - t.Fatalf("Reading buffer error: got: %v; want: %v", err, tc.finalErr) - } - - ct, ok := sct.ContentType() - if ok != tc.wantContentTypeResult { - t.Fatalf("Content type result got: %v; want: %v", ok, tc.wantContentTypeResult) - } - if ok && ct != tc.wantContentType { - t.Fatalf("Content type got: %q; want: %q", ct, tc.wantContentType) - } - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi_test.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi_test.go deleted file mode 100644 index 75d33ea09..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi_test.go +++ /dev/null @@ -1,599 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package googleapi - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "testing" - "time" - - "golang.org/x/net/context" -) - -type SetOpaqueTest struct { - in *url.URL - wantRequestURI string -} - -var setOpaqueTests = []SetOpaqueTest{ - // no path - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - }, - "http://www.golang.org", - }, - // path - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - Path: "/", - }, - "http://www.golang.org/", - }, - // file with hex escaping - { - &url.URL{ - Scheme: "https", - Host: "www.golang.org", - Path: "/file%20one&two", - }, - "https://www.golang.org/file%20one&two", - }, - // query - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - Path: "/", - RawQuery: "q=go+language", - }, - "http://www.golang.org/?q=go+language", - }, - // file with hex escaping in path plus query - { - &url.URL{ - Scheme: "https", - Host: "www.golang.org", - Path: "/file%20one&two", - RawQuery: "q=go+language", - }, - "https://www.golang.org/file%20one&two?q=go+language", - }, - // query with hex escaping - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - Path: "/", - RawQuery: "q=go%20language", - }, - "http://www.golang.org/?q=go%20language", - }, -} - -// prefixTmpl is a template for the expected prefix of the output of writing -// an HTTP request. -const prefixTmpl = "GET %v HTTP/1.1\r\nHost: %v\r\n" - -func TestSetOpaque(t *testing.T) { - for _, test := range setOpaqueTests { - u := *test.in - SetOpaque(&u) - - w := &bytes.Buffer{} - r := &http.Request{URL: &u} - if err := r.Write(w); err != nil { - t.Errorf("write request: %v", err) - continue - } - - prefix := fmt.Sprintf(prefixTmpl, test.wantRequestURI, test.in.Host) - if got := string(w.Bytes()); !strings.HasPrefix(got, prefix) { - t.Errorf("got %q expected prefix %q", got, prefix) - } - } -} - -type ExpandTest struct { - in string - expansions map[string]string - want string -} - -var expandTests = []ExpandTest{ - // no expansions - { - "http://www.golang.org/", - map[string]string{}, - "http://www.golang.org/", - }, - // one expansion, no escaping - { - "http://www.golang.org/{bucket}/delete", - map[string]string{ - "bucket": "red", - }, - "http://www.golang.org/red/delete", - }, - // one expansion, with hex escapes - { - "http://www.golang.org/{bucket}/delete", - map[string]string{ - "bucket": "red/blue", - }, - "http://www.golang.org/red%2Fblue/delete", - }, - // one expansion, with space - { - "http://www.golang.org/{bucket}/delete", - map[string]string{ - "bucket": "red or blue", - }, - "http://www.golang.org/red%20or%20blue/delete", - }, - // expansion not found - { - "http://www.golang.org/{object}/delete", - map[string]string{ - "bucket": "red or blue", - }, - "http://www.golang.org//delete", - }, - // multiple expansions - { - "http://www.golang.org/{one}/{two}/{three}/get", - map[string]string{ - "one": "ONE", - "two": "TWO", - "three": "THREE", - }, - "http://www.golang.org/ONE/TWO/THREE/get", - }, - // utf-8 characters - { - "http://www.golang.org/{bucket}/get", - map[string]string{ - "bucket": "£100", - }, - "http://www.golang.org/%C2%A3100/get", - }, - // punctuations - { - "http://www.golang.org/{bucket}/get", - map[string]string{ - "bucket": `/\@:,.`, - }, - "http://www.golang.org/%2F%5C%40%3A%2C./get", - }, - // mis-matched brackets - { - "http://www.golang.org/{bucket/get", - map[string]string{ - "bucket": "red", - }, - "http://www.golang.org/{bucket/get", - }, - // "+" prefix for suppressing escape - // See also: http://tools.ietf.org/html/rfc6570#section-3.2.3 - { - "http://www.golang.org/{+topic}", - map[string]string{ - "topic": "/topics/myproject/mytopic", - }, - // The double slashes here look weird, but it's intentional - "http://www.golang.org//topics/myproject/mytopic", - }, -} - -func TestExpand(t *testing.T) { - for i, test := range expandTests { - u := url.URL{ - Path: test.in, - } - Expand(&u, test.expansions) - got := u.Path - if got != test.want { - t.Errorf("got %q expected %q in test %d", got, test.want, i+1) - } - } -} - -type CheckResponseTest struct { - in *http.Response - bodyText string - want error - errText string -} - -var checkResponseTests = []CheckResponseTest{ - { - &http.Response{ - StatusCode: http.StatusOK, - }, - "", - nil, - "", - }, - { - &http.Response{ - StatusCode: http.StatusInternalServerError, - }, - `{"error":{}}`, - &Error{ - Code: http.StatusInternalServerError, - Body: `{"error":{}}`, - }, - `googleapi: got HTTP response code 500 with body: {"error":{}}`, - }, - { - &http.Response{ - StatusCode: http.StatusNotFound, - }, - `{"error":{"message":"Error message for StatusNotFound."}}`, - &Error{ - Code: http.StatusNotFound, - Message: "Error message for StatusNotFound.", - Body: `{"error":{"message":"Error message for StatusNotFound."}}`, - }, - "googleapi: Error 404: Error message for StatusNotFound.", - }, - { - &http.Response{ - StatusCode: http.StatusBadRequest, - }, - `{"error":"invalid_token","error_description":"Invalid Value"}`, - &Error{ - Code: http.StatusBadRequest, - Body: `{"error":"invalid_token","error_description":"Invalid Value"}`, - }, - `googleapi: got HTTP response code 400 with body: {"error":"invalid_token","error_description":"Invalid Value"}`, - }, - { - &http.Response{ - StatusCode: http.StatusBadRequest, - }, - `{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`, - &Error{ - Code: http.StatusBadRequest, - Errors: []ErrorItem{ - { - Reason: "keyInvalid", - Message: "Bad Request", - }, - }, - Body: `{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`, - Message: "Bad Request", - }, - "googleapi: Error 400: Bad Request, keyInvalid", - }, -} - -func TestCheckResponse(t *testing.T) { - for _, test := range checkResponseTests { - res := test.in - if test.bodyText != "" { - res.Body = ioutil.NopCloser(strings.NewReader(test.bodyText)) - } - g := CheckResponse(res) - if !reflect.DeepEqual(g, test.want) { - t.Errorf("CheckResponse: got %v, want %v", g, test.want) - gotJson, err := json.Marshal(g) - if err != nil { - t.Error(err) - } - wantJson, err := json.Marshal(test.want) - if err != nil { - t.Error(err) - } - t.Errorf("json(got): %q\njson(want): %q", string(gotJson), string(wantJson)) - } - if g != nil && g.Error() != test.errText { - t.Errorf("CheckResponse: unexpected error message.\nGot: %q\nwant: %q", g, test.errText) - } - } -} - -type VariantPoint struct { - Type string - Coordinates []float64 -} - -type VariantTest struct { - in map[string]interface{} - result bool - want VariantPoint -} - -var coords = []interface{}{1.0, 2.0} - -var variantTests = []VariantTest{ - { - in: map[string]interface{}{ - "type": "Point", - "coordinates": coords, - }, - result: true, - want: VariantPoint{ - Type: "Point", - Coordinates: []float64{1.0, 2.0}, - }, - }, - { - in: map[string]interface{}{ - "type": "Point", - "bogus": coords, - }, - result: true, - want: VariantPoint{ - Type: "Point", - }, - }, -} - -func TestVariantType(t *testing.T) { - for _, test := range variantTests { - if g := VariantType(test.in); g != test.want.Type { - t.Errorf("VariantType(%v): got %v, want %v", test.in, g, test.want.Type) - } - } -} - -func TestConvertVariant(t *testing.T) { - for _, test := range variantTests { - g := VariantPoint{} - r := ConvertVariant(test.in, &g) - if r != test.result { - t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, r, test.result) - } - if !reflect.DeepEqual(g, test.want) { - t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, g, test.want) - } - } -} - -type unexpectedReader struct{} - -func (unexpectedReader) Read([]byte) (int, error) { - return 0, fmt.Errorf("unexpected read in test.") -} - -var contentRangeRE = regexp.MustCompile(`^bytes (\d+)\-(\d+)/(\d+)$`) - -func (t *testTransport) RoundTrip(req *http.Request) (*http.Response, error) { - t.req = req - if rng := req.Header.Get("Content-Range"); rng != "" && !strings.HasPrefix(rng, "bytes */") { // Read the data - m := contentRangeRE.FindStringSubmatch(rng) - if len(m) != 4 { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - start, err := strconv.ParseInt(m[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - end, err := strconv.ParseInt(m[2], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - totalSize, err := strconv.ParseInt(m[3], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - partialSize := end - start + 1 - t.buf, err = ioutil.ReadAll(req.Body) - if err != nil || int64(len(t.buf)) != partialSize { - return nil, fmt.Errorf("unable to read %v bytes from request data, n=%v: %v", partialSize, len(t.buf), err) - } - if totalSize == end+1 { - t.statusCode = 200 // signify completion of transfer - } - } - f := ioutil.NopCloser(unexpectedReader{}) - res := &http.Response{ - Body: f, - StatusCode: t.statusCode, - Header: http.Header{}, - } - if t.rangeVal != "" { - res.Header.Set("Range", t.rangeVal) - } - return res, nil -} - -type testTransport struct { - req *http.Request - statusCode int - rangeVal string - want int64 - buf []byte -} - -var statusTests = []*testTransport{ - &testTransport{statusCode: 308, want: 0}, - &testTransport{statusCode: 308, rangeVal: "bytes=0-0", want: 1}, - &testTransport{statusCode: 308, rangeVal: "bytes=0-42", want: 43}, -} - -func TestTransferStatus(t *testing.T) { - ctx := context.Background() - for _, tr := range statusTests { - rx := &ResumableUpload{ - Client: &http.Client{Transport: tr}, - } - g, _, err := rx.transferStatus(ctx) - if err != nil { - t.Error(err) - } - if g != tr.want { - t.Errorf("transferStatus got %v, want %v", g, tr.want) - } - } -} - -func (t *interruptedTransport) RoundTrip(req *http.Request) (*http.Response, error) { - t.req = req - if rng := req.Header.Get("Content-Range"); rng != "" && !strings.HasPrefix(rng, "bytes */") { - t.interruptCount += 1 - if t.interruptCount%7 == 0 { // Respond with a "service unavailable" error - res := &http.Response{ - StatusCode: http.StatusServiceUnavailable, - Header: http.Header{}, - } - t.rangeVal = fmt.Sprintf("bytes=0-%v", len(t.buf)-1) // Set the response for next time - return res, nil - } - m := contentRangeRE.FindStringSubmatch(rng) - if len(m) != 4 { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - start, err := strconv.ParseInt(m[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - end, err := strconv.ParseInt(m[2], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - totalSize, err := strconv.ParseInt(m[3], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - partialSize := end - start + 1 - buf, err := ioutil.ReadAll(req.Body) - if err != nil || int64(len(buf)) != partialSize { - return nil, fmt.Errorf("unable to read %v bytes from request data, n=%v: %v", partialSize, len(buf), err) - } - t.buf = append(t.buf, buf...) - if totalSize == end+1 { - t.statusCode = 200 // signify completion of transfer - } - } - f := ioutil.NopCloser(unexpectedReader{}) - res := &http.Response{ - Body: f, - StatusCode: t.statusCode, - Header: http.Header{}, - } - if t.rangeVal != "" { - res.Header.Set("Range", t.rangeVal) - } - return res, nil -} - -type interruptedTransport struct { - req *http.Request - statusCode int - rangeVal string - interruptCount int - buf []byte - progressUpdates []int64 -} - -func (tr *interruptedTransport) ProgressUpdate(current int64) { - tr.progressUpdates = append(tr.progressUpdates, current) -} - -func TestInterruptedTransferChunks(t *testing.T) { - f, err := os.Open("googleapi.go") - if err != nil { - t.Fatalf("unable to open googleapi.go: %v", err) - } - defer f.Close() - slurp, err := ioutil.ReadAll(f) - if err != nil { - t.Fatalf("unable to slurp file: %v", err) - } - st, err := f.Stat() - if err != nil { - t.Fatalf("unable to stat googleapi.go: %v", err) - } - tr := &interruptedTransport{ - statusCode: 308, - buf: make([]byte, 0, st.Size()), - } - oldChunkSize := chunkSize - defer func() { chunkSize = oldChunkSize }() - chunkSize = 100 // override to process small chunks for test. - - sleep = func(time.Duration) {} // override time.Sleep - rx := &ResumableUpload{ - Client: &http.Client{Transport: tr}, - Media: f, - MediaType: "text/plain", - ContentLength: st.Size(), - Callback: tr.ProgressUpdate, - } - res, err := rx.Upload(context.Background()) - if err != nil || res == nil || res.StatusCode != http.StatusOK { - if res == nil { - t.Errorf("transferChunks not successful, res=nil: %v", err) - } else { - t.Errorf("transferChunks not successful, statusCode=%v: %v", res.StatusCode, err) - } - } - if len(tr.buf) != len(slurp) || bytes.Compare(tr.buf, slurp) != 0 { - t.Errorf("transferred file corrupted:\ngot %s\nwant %s", tr.buf, slurp) - } - want := []int64{} - for i := chunkSize; i <= st.Size(); i += chunkSize { - want = append(want, i) - } - if st.Size()%chunkSize != 0 { - want = append(want, st.Size()) - } - if !reflect.DeepEqual(tr.progressUpdates, want) { - t.Errorf("progress update error, got %v, want %v", tr.progressUpdates, want) - } -} - -func TestCancelUpload(t *testing.T) { - f, err := os.Open("googleapi.go") - if err != nil { - t.Fatalf("unable to open googleapi.go: %v", err) - } - defer f.Close() - st, err := f.Stat() - if err != nil { - t.Fatalf("unable to stat googleapi.go: %v", err) - } - tr := &interruptedTransport{ - statusCode: 308, - buf: make([]byte, 0, st.Size()), - } - oldChunkSize := chunkSize - defer func() { chunkSize = oldChunkSize }() - chunkSize = 100 // override to process small chunks for test. - - sleep = func(time.Duration) {} // override time.Sleep - rx := &ResumableUpload{ - Client: &http.Client{Transport: tr}, - Media: f, - MediaType: "text/plain", - ContentLength: st.Size(), - Callback: tr.ProgressUpdate, - } - ctx, cancelFunc := context.WithCancel(context.Background()) - cancelFunc() // stop the upload that hasn't started yet - res, err := rx.Upload(ctx) - if err == nil || res == nil || res.StatusCode != http.StatusRequestTimeout { - if res == nil { - t.Errorf("transferChunks not successful, got res=nil, err=%v, want StatusRequestTimeout", err) - } else { - t.Errorf("transferChunks not successful, got statusCode=%v, err=%v, want StatusRequestTimeout", res.StatusCode, err) - } - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/transport/apikey.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/transport/apikey.go deleted file mode 100644 index eca1ea250..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/transport/apikey.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2012 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package transport contains HTTP transports used to make -// authenticated API requests. -package transport - -import ( - "errors" - "net/http" -) - -// APIKey is an HTTP Transport which wraps an underlying transport and -// appends an API Key "key" parameter to the URL of outgoing requests. -type APIKey struct { - // Key is the API Key to set on requests. - Key string - - // Transport is the underlying HTTP transport. - // If nil, http.DefaultTransport is used. - Transport http.RoundTripper -} - -func (t *APIKey) RoundTrip(req *http.Request) (*http.Response, error) { - rt := t.Transport - if rt == nil { - rt = http.DefaultTransport - if rt == nil { - return nil, errors.New("googleapi/transport: no Transport specified or available") - } - } - newReq := *req - args := newReq.URL.Query() - args.Set("key", t.Key) - newReq.URL.RawQuery = args.Encode() - return rt.RoundTrip(&newReq) -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/types_test.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/types_test.go deleted file mode 100644 index a6b204515..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/types_test.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package googleapi - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestTypes(t *testing.T) { - type T struct { - I32 Int32s - I64 Int64s - U32 Uint32s - U64 Uint64s - F64 Float64s - } - v := &T{ - I32: Int32s{-1, 2, 3}, - I64: Int64s{-1, 2, 1 << 33}, - U32: Uint32s{1, 2}, - U64: Uint64s{1, 2, 1 << 33}, - F64: Float64s{1.5, 3.33}, - } - got, err := json.Marshal(v) - if err != nil { - t.Fatal(err) - } - want := `{"I32":["-1","2","3"],"I64":["-1","2","8589934592"],"U32":["1","2"],"U64":["1","2","8589934592"],"F64":["1.5","3.33"]}` - if string(got) != want { - t.Fatalf("Marshal mismatch.\n got: %s\nwant: %s\n", got, want) - } - - v2 := new(T) - if err := json.Unmarshal(got, v2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(v, v2) { - t.Fatalf("Unmarshal didn't produce same results.\n got: %#v\nwant: %#v\n", v, v2) - } -} diff --git a/Godeps/_workspace/src/google.golang.org/cloud/LICENSE b/Godeps/_workspace/src/google.golang.org/cloud/LICENSE new file mode 100644 index 000000000..a4c5efd82 --- /dev/null +++ b/Godeps/_workspace/src/google.golang.org/cloud/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 2014 Google Inc. + + 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/Godeps/_workspace/src/google.golang.org/cloud/internal/datastore/datastore_v1.pb.go b/Godeps/_workspace/src/google.golang.org/cloud/internal/datastore/datastore_v1.pb.go deleted file mode 100644 index be903e5ce..000000000 --- a/Godeps/_workspace/src/google.golang.org/cloud/internal/datastore/datastore_v1.pb.go +++ /dev/null @@ -1,1633 +0,0 @@ -// Code generated by protoc-gen-go. -// source: datastore_v1.proto -// DO NOT EDIT! - -/* -Package pb is a generated protocol buffer package. - -It is generated from these files: - datastore_v1.proto - -It has these top-level messages: - PartitionId - Key - Value - Property - Entity - EntityResult - Query - KindExpression - PropertyReference - PropertyExpression - PropertyOrder - Filter - CompositeFilter - PropertyFilter - GqlQuery - GqlQueryArg - QueryResultBatch - Mutation - MutationResult - ReadOptions - LookupRequest - LookupResponse - RunQueryRequest - RunQueryResponse - BeginTransactionRequest - BeginTransactionResponse - RollbackRequest - RollbackResponse - CommitRequest - CommitResponse - AllocateIdsRequest - AllocateIdsResponse -*/ -package pb - -import proto "github.com/golang/protobuf/proto" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = math.Inf - -// Specifies what data the 'entity' field contains. -// A ResultType is either implied (for example, in LookupResponse.found it -// is always FULL) or specified by context (for example, in message -// QueryResultBatch, field 'entity_result_type' specifies a ResultType -// for all the values in field 'entity_result'). -type EntityResult_ResultType int32 - -const ( - EntityResult_FULL EntityResult_ResultType = 1 - EntityResult_PROJECTION EntityResult_ResultType = 2 - // The entity may have no key. - // A property value may have meaning 18. - EntityResult_KEY_ONLY EntityResult_ResultType = 3 -) - -var EntityResult_ResultType_name = map[int32]string{ - 1: "FULL", - 2: "PROJECTION", - 3: "KEY_ONLY", -} -var EntityResult_ResultType_value = map[string]int32{ - "FULL": 1, - "PROJECTION": 2, - "KEY_ONLY": 3, -} - -func (x EntityResult_ResultType) Enum() *EntityResult_ResultType { - p := new(EntityResult_ResultType) - *p = x - return p -} -func (x EntityResult_ResultType) String() string { - return proto.EnumName(EntityResult_ResultType_name, int32(x)) -} -func (x *EntityResult_ResultType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(EntityResult_ResultType_value, data, "EntityResult_ResultType") - if err != nil { - return err - } - *x = EntityResult_ResultType(value) - return nil -} - -type PropertyExpression_AggregationFunction int32 - -const ( - PropertyExpression_FIRST PropertyExpression_AggregationFunction = 1 -) - -var PropertyExpression_AggregationFunction_name = map[int32]string{ - 1: "FIRST", -} -var PropertyExpression_AggregationFunction_value = map[string]int32{ - "FIRST": 1, -} - -func (x PropertyExpression_AggregationFunction) Enum() *PropertyExpression_AggregationFunction { - p := new(PropertyExpression_AggregationFunction) - *p = x - return p -} -func (x PropertyExpression_AggregationFunction) String() string { - return proto.EnumName(PropertyExpression_AggregationFunction_name, int32(x)) -} -func (x *PropertyExpression_AggregationFunction) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PropertyExpression_AggregationFunction_value, data, "PropertyExpression_AggregationFunction") - if err != nil { - return err - } - *x = PropertyExpression_AggregationFunction(value) - return nil -} - -type PropertyOrder_Direction int32 - -const ( - PropertyOrder_ASCENDING PropertyOrder_Direction = 1 - PropertyOrder_DESCENDING PropertyOrder_Direction = 2 -) - -var PropertyOrder_Direction_name = map[int32]string{ - 1: "ASCENDING", - 2: "DESCENDING", -} -var PropertyOrder_Direction_value = map[string]int32{ - "ASCENDING": 1, - "DESCENDING": 2, -} - -func (x PropertyOrder_Direction) Enum() *PropertyOrder_Direction { - p := new(PropertyOrder_Direction) - *p = x - return p -} -func (x PropertyOrder_Direction) String() string { - return proto.EnumName(PropertyOrder_Direction_name, int32(x)) -} -func (x *PropertyOrder_Direction) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PropertyOrder_Direction_value, data, "PropertyOrder_Direction") - if err != nil { - return err - } - *x = PropertyOrder_Direction(value) - return nil -} - -type CompositeFilter_Operator int32 - -const ( - CompositeFilter_AND CompositeFilter_Operator = 1 -) - -var CompositeFilter_Operator_name = map[int32]string{ - 1: "AND", -} -var CompositeFilter_Operator_value = map[string]int32{ - "AND": 1, -} - -func (x CompositeFilter_Operator) Enum() *CompositeFilter_Operator { - p := new(CompositeFilter_Operator) - *p = x - return p -} -func (x CompositeFilter_Operator) String() string { - return proto.EnumName(CompositeFilter_Operator_name, int32(x)) -} -func (x *CompositeFilter_Operator) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(CompositeFilter_Operator_value, data, "CompositeFilter_Operator") - if err != nil { - return err - } - *x = CompositeFilter_Operator(value) - return nil -} - -type PropertyFilter_Operator int32 - -const ( - PropertyFilter_LESS_THAN PropertyFilter_Operator = 1 - PropertyFilter_LESS_THAN_OR_EQUAL PropertyFilter_Operator = 2 - PropertyFilter_GREATER_THAN PropertyFilter_Operator = 3 - PropertyFilter_GREATER_THAN_OR_EQUAL PropertyFilter_Operator = 4 - PropertyFilter_EQUAL PropertyFilter_Operator = 5 - PropertyFilter_HAS_ANCESTOR PropertyFilter_Operator = 11 -) - -var PropertyFilter_Operator_name = map[int32]string{ - 1: "LESS_THAN", - 2: "LESS_THAN_OR_EQUAL", - 3: "GREATER_THAN", - 4: "GREATER_THAN_OR_EQUAL", - 5: "EQUAL", - 11: "HAS_ANCESTOR", -} -var PropertyFilter_Operator_value = map[string]int32{ - "LESS_THAN": 1, - "LESS_THAN_OR_EQUAL": 2, - "GREATER_THAN": 3, - "GREATER_THAN_OR_EQUAL": 4, - "EQUAL": 5, - "HAS_ANCESTOR": 11, -} - -func (x PropertyFilter_Operator) Enum() *PropertyFilter_Operator { - p := new(PropertyFilter_Operator) - *p = x - return p -} -func (x PropertyFilter_Operator) String() string { - return proto.EnumName(PropertyFilter_Operator_name, int32(x)) -} -func (x *PropertyFilter_Operator) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PropertyFilter_Operator_value, data, "PropertyFilter_Operator") - if err != nil { - return err - } - *x = PropertyFilter_Operator(value) - return nil -} - -// The possible values for the 'more_results' field. -type QueryResultBatch_MoreResultsType int32 - -const ( - QueryResultBatch_NOT_FINISHED QueryResultBatch_MoreResultsType = 1 - QueryResultBatch_MORE_RESULTS_AFTER_LIMIT QueryResultBatch_MoreResultsType = 2 - // results after the limit. - QueryResultBatch_NO_MORE_RESULTS QueryResultBatch_MoreResultsType = 3 -) - -var QueryResultBatch_MoreResultsType_name = map[int32]string{ - 1: "NOT_FINISHED", - 2: "MORE_RESULTS_AFTER_LIMIT", - 3: "NO_MORE_RESULTS", -} -var QueryResultBatch_MoreResultsType_value = map[string]int32{ - "NOT_FINISHED": 1, - "MORE_RESULTS_AFTER_LIMIT": 2, - "NO_MORE_RESULTS": 3, -} - -func (x QueryResultBatch_MoreResultsType) Enum() *QueryResultBatch_MoreResultsType { - p := new(QueryResultBatch_MoreResultsType) - *p = x - return p -} -func (x QueryResultBatch_MoreResultsType) String() string { - return proto.EnumName(QueryResultBatch_MoreResultsType_name, int32(x)) -} -func (x *QueryResultBatch_MoreResultsType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(QueryResultBatch_MoreResultsType_value, data, "QueryResultBatch_MoreResultsType") - if err != nil { - return err - } - *x = QueryResultBatch_MoreResultsType(value) - return nil -} - -type ReadOptions_ReadConsistency int32 - -const ( - ReadOptions_DEFAULT ReadOptions_ReadConsistency = 0 - ReadOptions_STRONG ReadOptions_ReadConsistency = 1 - ReadOptions_EVENTUAL ReadOptions_ReadConsistency = 2 -) - -var ReadOptions_ReadConsistency_name = map[int32]string{ - 0: "DEFAULT", - 1: "STRONG", - 2: "EVENTUAL", -} -var ReadOptions_ReadConsistency_value = map[string]int32{ - "DEFAULT": 0, - "STRONG": 1, - "EVENTUAL": 2, -} - -func (x ReadOptions_ReadConsistency) Enum() *ReadOptions_ReadConsistency { - p := new(ReadOptions_ReadConsistency) - *p = x - return p -} -func (x ReadOptions_ReadConsistency) String() string { - return proto.EnumName(ReadOptions_ReadConsistency_name, int32(x)) -} -func (x *ReadOptions_ReadConsistency) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(ReadOptions_ReadConsistency_value, data, "ReadOptions_ReadConsistency") - if err != nil { - return err - } - *x = ReadOptions_ReadConsistency(value) - return nil -} - -type BeginTransactionRequest_IsolationLevel int32 - -const ( - BeginTransactionRequest_SNAPSHOT BeginTransactionRequest_IsolationLevel = 0 - // conflict if their mutations conflict. For example: - // Read(A),Write(B) may not conflict with Read(B),Write(A), - // but Read(B),Write(B) does conflict with Read(B),Write(B). - BeginTransactionRequest_SERIALIZABLE BeginTransactionRequest_IsolationLevel = 1 -) - -var BeginTransactionRequest_IsolationLevel_name = map[int32]string{ - 0: "SNAPSHOT", - 1: "SERIALIZABLE", -} -var BeginTransactionRequest_IsolationLevel_value = map[string]int32{ - "SNAPSHOT": 0, - "SERIALIZABLE": 1, -} - -func (x BeginTransactionRequest_IsolationLevel) Enum() *BeginTransactionRequest_IsolationLevel { - p := new(BeginTransactionRequest_IsolationLevel) - *p = x - return p -} -func (x BeginTransactionRequest_IsolationLevel) String() string { - return proto.EnumName(BeginTransactionRequest_IsolationLevel_name, int32(x)) -} -func (x *BeginTransactionRequest_IsolationLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(BeginTransactionRequest_IsolationLevel_value, data, "BeginTransactionRequest_IsolationLevel") - if err != nil { - return err - } - *x = BeginTransactionRequest_IsolationLevel(value) - return nil -} - -type CommitRequest_Mode int32 - -const ( - CommitRequest_TRANSACTIONAL CommitRequest_Mode = 1 - CommitRequest_NON_TRANSACTIONAL CommitRequest_Mode = 2 -) - -var CommitRequest_Mode_name = map[int32]string{ - 1: "TRANSACTIONAL", - 2: "NON_TRANSACTIONAL", -} -var CommitRequest_Mode_value = map[string]int32{ - "TRANSACTIONAL": 1, - "NON_TRANSACTIONAL": 2, -} - -func (x CommitRequest_Mode) Enum() *CommitRequest_Mode { - p := new(CommitRequest_Mode) - *p = x - return p -} -func (x CommitRequest_Mode) String() string { - return proto.EnumName(CommitRequest_Mode_name, int32(x)) -} -func (x *CommitRequest_Mode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(CommitRequest_Mode_value, data, "CommitRequest_Mode") - if err != nil { - return err - } - *x = CommitRequest_Mode(value) - return nil -} - -// An identifier for a particular subset of entities. -// -// Entities are partitioned into various subsets, each used by different -// datasets and different namespaces within a dataset and so forth. -// -// All input partition IDs are normalized before use. -// A partition ID is normalized as follows: -// If the partition ID is unset or is set to an empty partition ID, replace it -// with the context partition ID. -// Otherwise, if the partition ID has no dataset ID, assign it the context -// partition ID's dataset ID. -// Unless otherwise documented, the context partition ID has the dataset ID set -// to the context dataset ID and no other partition dimension set. -// -// A partition ID is empty if all of its fields are unset. -// -// Partition dimension: -// A dimension may be unset. -// A dimension's value must never be "". -// A dimension's value must match [A-Za-z\d\.\-_]{1,100} -// If the value of any dimension matches regex "__.*__", -// the partition is reserved/read-only. -// A reserved/read-only partition ID is forbidden in certain documented contexts. -// -// Dataset ID: -// A dataset id's value must never be "". -// A dataset id's value must match -// ([a-z\d\-]{1,100}~)?([a-z\d][a-z\d\-\.]{0,99}:)?([a-z\d][a-z\d\-]{0,99} -type PartitionId struct { - // The dataset ID. - DatasetId *string `protobuf:"bytes,3,opt,name=dataset_id" json:"dataset_id,omitempty"` - // The namespace. - Namespace *string `protobuf:"bytes,4,opt,name=namespace" json:"namespace,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PartitionId) Reset() { *m = PartitionId{} } -func (m *PartitionId) String() string { return proto.CompactTextString(m) } -func (*PartitionId) ProtoMessage() {} - -func (m *PartitionId) GetDatasetId() string { - if m != nil && m.DatasetId != nil { - return *m.DatasetId - } - return "" -} - -func (m *PartitionId) GetNamespace() string { - if m != nil && m.Namespace != nil { - return *m.Namespace - } - return "" -} - -// A unique identifier for an entity. -// If a key's partition id or any of its path kinds or names are -// reserved/read-only, the key is reserved/read-only. -// A reserved/read-only key is forbidden in certain documented contexts. -type Key struct { - // Entities are partitioned into subsets, currently identified by a dataset - // (usually implicitly specified by the project) and namespace ID. - // Queries are scoped to a single partition. - PartitionId *PartitionId `protobuf:"bytes,1,opt,name=partition_id" json:"partition_id,omitempty"` - // The entity path. - // An entity path consists of one or more elements composed of a kind and a - // string or numerical identifier, which identify entities. The first - // element identifies a root entity, the second element identifies - // a child of the root entity, the third element a child of the - // second entity, and so forth. The entities identified by all prefixes of - // the path are called the element's ancestors. - // An entity path is always fully complete: ALL of the entity's ancestors - // are required to be in the path along with the entity identifier itself. - // The only exception is that in some documented cases, the identifier in the - // last path element (for the entity) itself may be omitted. A path can never - // be empty. - PathElement []*Key_PathElement `protobuf:"bytes,2,rep,name=path_element" json:"path_element,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Key) Reset() { *m = Key{} } -func (m *Key) String() string { return proto.CompactTextString(m) } -func (*Key) ProtoMessage() {} - -func (m *Key) GetPartitionId() *PartitionId { - if m != nil { - return m.PartitionId - } - return nil -} - -func (m *Key) GetPathElement() []*Key_PathElement { - if m != nil { - return m.PathElement - } - return nil -} - -// A (kind, ID/name) pair used to construct a key path. -// -// At most one of name or ID may be set. -// If either is set, the element is complete. -// If neither is set, the element is incomplete. -type Key_PathElement struct { - // The kind of the entity. - // A kind matching regex "__.*__" is reserved/read-only. - // A kind must not contain more than 500 characters. - // Cannot be "". - Kind *string `protobuf:"bytes,1,req,name=kind" json:"kind,omitempty"` - // The ID of the entity. - // Never equal to zero. Values less than zero are discouraged and will not - // be supported in the future. - Id *int64 `protobuf:"varint,2,opt,name=id" json:"id,omitempty"` - // The name of the entity. - // A name matching regex "__.*__" is reserved/read-only. - // A name must not be more than 500 characters. - // Cannot be "". - Name *string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Key_PathElement) Reset() { *m = Key_PathElement{} } -func (m *Key_PathElement) String() string { return proto.CompactTextString(m) } -func (*Key_PathElement) ProtoMessage() {} - -func (m *Key_PathElement) GetKind() string { - if m != nil && m.Kind != nil { - return *m.Kind - } - return "" -} - -func (m *Key_PathElement) GetId() int64 { - if m != nil && m.Id != nil { - return *m.Id - } - return 0 -} - -func (m *Key_PathElement) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// A message that can hold any of the supported value types and associated -// metadata. -// -// At most one of the Value fields may be set. -// If none are set the value is "null". -// -type Value struct { - // A boolean value. - BooleanValue *bool `protobuf:"varint,1,opt,name=boolean_value" json:"boolean_value,omitempty"` - // An integer value. - IntegerValue *int64 `protobuf:"varint,2,opt,name=integer_value" json:"integer_value,omitempty"` - // A double value. - DoubleValue *float64 `protobuf:"fixed64,3,opt,name=double_value" json:"double_value,omitempty"` - // A timestamp value. - TimestampMicrosecondsValue *int64 `protobuf:"varint,4,opt,name=timestamp_microseconds_value" json:"timestamp_microseconds_value,omitempty"` - // A key value. - KeyValue *Key `protobuf:"bytes,5,opt,name=key_value" json:"key_value,omitempty"` - // A blob key value. - BlobKeyValue *string `protobuf:"bytes,16,opt,name=blob_key_value" json:"blob_key_value,omitempty"` - // A UTF-8 encoded string value. - StringValue *string `protobuf:"bytes,17,opt,name=string_value" json:"string_value,omitempty"` - // A blob value. - BlobValue []byte `protobuf:"bytes,18,opt,name=blob_value" json:"blob_value,omitempty"` - // An entity value. - // May have no key. - // May have a key with an incomplete key path. - // May have a reserved/read-only key. - EntityValue *Entity `protobuf:"bytes,6,opt,name=entity_value" json:"entity_value,omitempty"` - // A list value. - // Cannot contain another list value. - // Cannot also have a meaning and indexing set. - ListValue []*Value `protobuf:"bytes,7,rep,name=list_value" json:"list_value,omitempty"` - // The meaning field is reserved and should not be used. - Meaning *int32 `protobuf:"varint,14,opt,name=meaning" json:"meaning,omitempty"` - // If the value should be indexed. - // - // The indexed property may be set for a - // null value. - // When indexed is true, stringValue - // is limited to 500 characters and the blob value is limited to 500 bytes. - // Exception: If meaning is set to 2, string_value is limited to 2038 - // characters regardless of indexed. - // When indexed is true, meaning 15 and 22 are not allowed, and meaning 16 - // will be ignored on input (and will never be set on output). - // Input values by default have indexed set to - // true; however, you can explicitly set indexed to - // true if you want. (An output value never has - // indexed explicitly set to true.) If a value is - // itself an entity, it cannot have indexed set to - // true. - // Exception: An entity value with meaning 9, 20 or 21 may be indexed. - Indexed *bool `protobuf:"varint,15,opt,name=indexed,def=1" json:"indexed,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Value) Reset() { *m = Value{} } -func (m *Value) String() string { return proto.CompactTextString(m) } -func (*Value) ProtoMessage() {} - -const Default_Value_Indexed bool = true - -func (m *Value) GetBooleanValue() bool { - if m != nil && m.BooleanValue != nil { - return *m.BooleanValue - } - return false -} - -func (m *Value) GetIntegerValue() int64 { - if m != nil && m.IntegerValue != nil { - return *m.IntegerValue - } - return 0 -} - -func (m *Value) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *Value) GetTimestampMicrosecondsValue() int64 { - if m != nil && m.TimestampMicrosecondsValue != nil { - return *m.TimestampMicrosecondsValue - } - return 0 -} - -func (m *Value) GetKeyValue() *Key { - if m != nil { - return m.KeyValue - } - return nil -} - -func (m *Value) GetBlobKeyValue() string { - if m != nil && m.BlobKeyValue != nil { - return *m.BlobKeyValue - } - return "" -} - -func (m *Value) GetStringValue() string { - if m != nil && m.StringValue != nil { - return *m.StringValue - } - return "" -} - -func (m *Value) GetBlobValue() []byte { - if m != nil { - return m.BlobValue - } - return nil -} - -func (m *Value) GetEntityValue() *Entity { - if m != nil { - return m.EntityValue - } - return nil -} - -func (m *Value) GetListValue() []*Value { - if m != nil { - return m.ListValue - } - return nil -} - -func (m *Value) GetMeaning() int32 { - if m != nil && m.Meaning != nil { - return *m.Meaning - } - return 0 -} - -func (m *Value) GetIndexed() bool { - if m != nil && m.Indexed != nil { - return *m.Indexed - } - return Default_Value_Indexed -} - -// An entity property. -type Property struct { - // The name of the property. - // A property name matching regex "__.*__" is reserved. - // A reserved property name is forbidden in certain documented contexts. - // The name must not contain more than 500 characters. - // Cannot be "". - Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` - // The value(s) of the property. - // Each value can have only one value property populated. For example, - // you cannot have a values list of { value: { integerValue: 22, - // stringValue: "a" } }, but you can have { value: { listValue: - // [ { integerValue: 22 }, { stringValue: "a" } ] }. - Value *Value `protobuf:"bytes,4,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Property) Reset() { *m = Property{} } -func (m *Property) String() string { return proto.CompactTextString(m) } -func (*Property) ProtoMessage() {} - -func (m *Property) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *Property) GetValue() *Value { - if m != nil { - return m.Value - } - return nil -} - -// An entity. -// -// An entity is limited to 1 megabyte when stored. That roughly -// corresponds to a limit of 1 megabyte for the serialized form of this -// message. -type Entity struct { - // The entity's key. - // - // An entity must have a key, unless otherwise documented (for example, - // an entity in Value.entityValue may have no key). - // An entity's kind is its key's path's last element's kind, - // or null if it has no key. - Key *Key `protobuf:"bytes,1,opt,name=key" json:"key,omitempty"` - // The entity's properties. - // Each property's name must be unique for its entity. - Property []*Property `protobuf:"bytes,2,rep,name=property" json:"property,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Entity) Reset() { *m = Entity{} } -func (m *Entity) String() string { return proto.CompactTextString(m) } -func (*Entity) ProtoMessage() {} - -func (m *Entity) GetKey() *Key { - if m != nil { - return m.Key - } - return nil -} - -func (m *Entity) GetProperty() []*Property { - if m != nil { - return m.Property - } - return nil -} - -// The result of fetching an entity from the datastore. -type EntityResult struct { - // The resulting entity. - Entity *Entity `protobuf:"bytes,1,req,name=entity" json:"entity,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *EntityResult) Reset() { *m = EntityResult{} } -func (m *EntityResult) String() string { return proto.CompactTextString(m) } -func (*EntityResult) ProtoMessage() {} - -func (m *EntityResult) GetEntity() *Entity { - if m != nil { - return m.Entity - } - return nil -} - -// A query. -type Query struct { - // The projection to return. If not set the entire entity is returned. - Projection []*PropertyExpression `protobuf:"bytes,2,rep,name=projection" json:"projection,omitempty"` - // The kinds to query (if empty, returns entities from all kinds). - Kind []*KindExpression `protobuf:"bytes,3,rep,name=kind" json:"kind,omitempty"` - // The filter to apply (optional). - Filter *Filter `protobuf:"bytes,4,opt,name=filter" json:"filter,omitempty"` - // The order to apply to the query results (if empty, order is unspecified). - Order []*PropertyOrder `protobuf:"bytes,5,rep,name=order" json:"order,omitempty"` - // The properties to group by (if empty, no grouping is applied to the - // result set). - GroupBy []*PropertyReference `protobuf:"bytes,6,rep,name=group_by" json:"group_by,omitempty"` - // A starting point for the query results. Optional. Query cursors are - // returned in query result batches. - StartCursor []byte `protobuf:"bytes,7,opt,name=start_cursor" json:"start_cursor,omitempty"` - // An ending point for the query results. Optional. Query cursors are - // returned in query result batches. - EndCursor []byte `protobuf:"bytes,8,opt,name=end_cursor" json:"end_cursor,omitempty"` - // The number of results to skip. Applies before limit, but after all other - // constraints (optional, defaults to 0). - Offset *int32 `protobuf:"varint,10,opt,name=offset,def=0" json:"offset,omitempty"` - // The maximum number of results to return. Applies after all other - // constraints. Optional. - Limit *int32 `protobuf:"varint,11,opt,name=limit" json:"limit,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Query) Reset() { *m = Query{} } -func (m *Query) String() string { return proto.CompactTextString(m) } -func (*Query) ProtoMessage() {} - -const Default_Query_Offset int32 = 0 - -func (m *Query) GetProjection() []*PropertyExpression { - if m != nil { - return m.Projection - } - return nil -} - -func (m *Query) GetKind() []*KindExpression { - if m != nil { - return m.Kind - } - return nil -} - -func (m *Query) GetFilter() *Filter { - if m != nil { - return m.Filter - } - return nil -} - -func (m *Query) GetOrder() []*PropertyOrder { - if m != nil { - return m.Order - } - return nil -} - -func (m *Query) GetGroupBy() []*PropertyReference { - if m != nil { - return m.GroupBy - } - return nil -} - -func (m *Query) GetStartCursor() []byte { - if m != nil { - return m.StartCursor - } - return nil -} - -func (m *Query) GetEndCursor() []byte { - if m != nil { - return m.EndCursor - } - return nil -} - -func (m *Query) GetOffset() int32 { - if m != nil && m.Offset != nil { - return *m.Offset - } - return Default_Query_Offset -} - -func (m *Query) GetLimit() int32 { - if m != nil && m.Limit != nil { - return *m.Limit - } - return 0 -} - -// A representation of a kind. -type KindExpression struct { - // The name of the kind. - Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *KindExpression) Reset() { *m = KindExpression{} } -func (m *KindExpression) String() string { return proto.CompactTextString(m) } -func (*KindExpression) ProtoMessage() {} - -func (m *KindExpression) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// A reference to a property relative to the kind expressions. -// exactly. -type PropertyReference struct { - // The name of the property. - Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyReference) Reset() { *m = PropertyReference{} } -func (m *PropertyReference) String() string { return proto.CompactTextString(m) } -func (*PropertyReference) ProtoMessage() {} - -func (m *PropertyReference) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// A representation of a property in a projection. -type PropertyExpression struct { - // The property to project. - Property *PropertyReference `protobuf:"bytes,1,req,name=property" json:"property,omitempty"` - // The aggregation function to apply to the property. Optional. - // Can only be used when grouping by at least one property. Must - // then be set on all properties in the projection that are not - // being grouped by. - AggregationFunction *PropertyExpression_AggregationFunction `protobuf:"varint,2,opt,name=aggregation_function,enum=pb.PropertyExpression_AggregationFunction" json:"aggregation_function,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyExpression) Reset() { *m = PropertyExpression{} } -func (m *PropertyExpression) String() string { return proto.CompactTextString(m) } -func (*PropertyExpression) ProtoMessage() {} - -func (m *PropertyExpression) GetProperty() *PropertyReference { - if m != nil { - return m.Property - } - return nil -} - -func (m *PropertyExpression) GetAggregationFunction() PropertyExpression_AggregationFunction { - if m != nil && m.AggregationFunction != nil { - return *m.AggregationFunction - } - return PropertyExpression_FIRST -} - -// The desired order for a specific property. -type PropertyOrder struct { - // The property to order by. - Property *PropertyReference `protobuf:"bytes,1,req,name=property" json:"property,omitempty"` - // The direction to order by. - Direction *PropertyOrder_Direction `protobuf:"varint,2,opt,name=direction,enum=pb.PropertyOrder_Direction,def=1" json:"direction,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyOrder) Reset() { *m = PropertyOrder{} } -func (m *PropertyOrder) String() string { return proto.CompactTextString(m) } -func (*PropertyOrder) ProtoMessage() {} - -const Default_PropertyOrder_Direction PropertyOrder_Direction = PropertyOrder_ASCENDING - -func (m *PropertyOrder) GetProperty() *PropertyReference { - if m != nil { - return m.Property - } - return nil -} - -func (m *PropertyOrder) GetDirection() PropertyOrder_Direction { - if m != nil && m.Direction != nil { - return *m.Direction - } - return Default_PropertyOrder_Direction -} - -// A holder for any type of filter. Exactly one field should be specified. -type Filter struct { - // A composite filter. - CompositeFilter *CompositeFilter `protobuf:"bytes,1,opt,name=composite_filter" json:"composite_filter,omitempty"` - // A filter on a property. - PropertyFilter *PropertyFilter `protobuf:"bytes,2,opt,name=property_filter" json:"property_filter,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Filter) Reset() { *m = Filter{} } -func (m *Filter) String() string { return proto.CompactTextString(m) } -func (*Filter) ProtoMessage() {} - -func (m *Filter) GetCompositeFilter() *CompositeFilter { - if m != nil { - return m.CompositeFilter - } - return nil -} - -func (m *Filter) GetPropertyFilter() *PropertyFilter { - if m != nil { - return m.PropertyFilter - } - return nil -} - -// A filter that merges the multiple other filters using the given operation. -type CompositeFilter struct { - // The operator for combining multiple filters. - Operator *CompositeFilter_Operator `protobuf:"varint,1,req,name=operator,enum=pb.CompositeFilter_Operator" json:"operator,omitempty"` - // The list of filters to combine. - // Must contain at least one filter. - Filter []*Filter `protobuf:"bytes,2,rep,name=filter" json:"filter,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompositeFilter) Reset() { *m = CompositeFilter{} } -func (m *CompositeFilter) String() string { return proto.CompactTextString(m) } -func (*CompositeFilter) ProtoMessage() {} - -func (m *CompositeFilter) GetOperator() CompositeFilter_Operator { - if m != nil && m.Operator != nil { - return *m.Operator - } - return CompositeFilter_AND -} - -func (m *CompositeFilter) GetFilter() []*Filter { - if m != nil { - return m.Filter - } - return nil -} - -// A filter on a specific property. -type PropertyFilter struct { - // The property to filter by. - Property *PropertyReference `protobuf:"bytes,1,req,name=property" json:"property,omitempty"` - // The operator to filter by. - Operator *PropertyFilter_Operator `protobuf:"varint,2,req,name=operator,enum=pb.PropertyFilter_Operator" json:"operator,omitempty"` - // The value to compare the property to. - Value *Value `protobuf:"bytes,3,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyFilter) Reset() { *m = PropertyFilter{} } -func (m *PropertyFilter) String() string { return proto.CompactTextString(m) } -func (*PropertyFilter) ProtoMessage() {} - -func (m *PropertyFilter) GetProperty() *PropertyReference { - if m != nil { - return m.Property - } - return nil -} - -func (m *PropertyFilter) GetOperator() PropertyFilter_Operator { - if m != nil && m.Operator != nil { - return *m.Operator - } - return PropertyFilter_LESS_THAN -} - -func (m *PropertyFilter) GetValue() *Value { - if m != nil { - return m.Value - } - return nil -} - -// A GQL query. -type GqlQuery struct { - QueryString *string `protobuf:"bytes,1,req,name=query_string" json:"query_string,omitempty"` - // When false, the query string must not contain a literal. - AllowLiteral *bool `protobuf:"varint,2,opt,name=allow_literal,def=0" json:"allow_literal,omitempty"` - // A named argument must set field GqlQueryArg.name. - // No two named arguments may have the same name. - // For each non-reserved named binding site in the query string, - // there must be a named argument with that name, - // but not necessarily the inverse. - NameArg []*GqlQueryArg `protobuf:"bytes,3,rep,name=name_arg" json:"name_arg,omitempty"` - // Numbered binding site @1 references the first numbered argument, - // effectively using 1-based indexing, rather than the usual 0. - // A numbered argument must NOT set field GqlQueryArg.name. - // For each binding site numbered i in query_string, - // there must be an ith numbered argument. - // The inverse must also be true. - NumberArg []*GqlQueryArg `protobuf:"bytes,4,rep,name=number_arg" json:"number_arg,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GqlQuery) Reset() { *m = GqlQuery{} } -func (m *GqlQuery) String() string { return proto.CompactTextString(m) } -func (*GqlQuery) ProtoMessage() {} - -const Default_GqlQuery_AllowLiteral bool = false - -func (m *GqlQuery) GetQueryString() string { - if m != nil && m.QueryString != nil { - return *m.QueryString - } - return "" -} - -func (m *GqlQuery) GetAllowLiteral() bool { - if m != nil && m.AllowLiteral != nil { - return *m.AllowLiteral - } - return Default_GqlQuery_AllowLiteral -} - -func (m *GqlQuery) GetNameArg() []*GqlQueryArg { - if m != nil { - return m.NameArg - } - return nil -} - -func (m *GqlQuery) GetNumberArg() []*GqlQueryArg { - if m != nil { - return m.NumberArg - } - return nil -} - -// A binding argument for a GQL query. -// Exactly one of fields value and cursor must be set. -type GqlQueryArg struct { - // Must match regex "[A-Za-z_$][A-Za-z_$0-9]*". - // Must not match regex "__.*__". - // Must not be "". - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value *Value `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - Cursor []byte `protobuf:"bytes,3,opt,name=cursor" json:"cursor,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GqlQueryArg) Reset() { *m = GqlQueryArg{} } -func (m *GqlQueryArg) String() string { return proto.CompactTextString(m) } -func (*GqlQueryArg) ProtoMessage() {} - -func (m *GqlQueryArg) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *GqlQueryArg) GetValue() *Value { - if m != nil { - return m.Value - } - return nil -} - -func (m *GqlQueryArg) GetCursor() []byte { - if m != nil { - return m.Cursor - } - return nil -} - -// A batch of results produced by a query. -type QueryResultBatch struct { - // The result type for every entity in entityResults. - EntityResultType *EntityResult_ResultType `protobuf:"varint,1,req,name=entity_result_type,enum=pb.EntityResult_ResultType" json:"entity_result_type,omitempty"` - // The results for this batch. - EntityResult []*EntityResult `protobuf:"bytes,2,rep,name=entity_result" json:"entity_result,omitempty"` - // A cursor that points to the position after the last result in the batch. - // May be absent. - EndCursor []byte `protobuf:"bytes,4,opt,name=end_cursor" json:"end_cursor,omitempty"` - // The state of the query after the current batch. - MoreResults *QueryResultBatch_MoreResultsType `protobuf:"varint,5,req,name=more_results,enum=pb.QueryResultBatch_MoreResultsType" json:"more_results,omitempty"` - // The number of results skipped because of Query.offset. - SkippedResults *int32 `protobuf:"varint,6,opt,name=skipped_results" json:"skipped_results,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *QueryResultBatch) Reset() { *m = QueryResultBatch{} } -func (m *QueryResultBatch) String() string { return proto.CompactTextString(m) } -func (*QueryResultBatch) ProtoMessage() {} - -func (m *QueryResultBatch) GetEntityResultType() EntityResult_ResultType { - if m != nil && m.EntityResultType != nil { - return *m.EntityResultType - } - return EntityResult_FULL -} - -func (m *QueryResultBatch) GetEntityResult() []*EntityResult { - if m != nil { - return m.EntityResult - } - return nil -} - -func (m *QueryResultBatch) GetEndCursor() []byte { - if m != nil { - return m.EndCursor - } - return nil -} - -func (m *QueryResultBatch) GetMoreResults() QueryResultBatch_MoreResultsType { - if m != nil && m.MoreResults != nil { - return *m.MoreResults - } - return QueryResultBatch_NOT_FINISHED -} - -func (m *QueryResultBatch) GetSkippedResults() int32 { - if m != nil && m.SkippedResults != nil { - return *m.SkippedResults - } - return 0 -} - -// A set of changes to apply. -// -// No entity in this message may have a reserved property name, -// not even a property in an entity in a value. -// No value in this message may have meaning 18, -// not even a value in an entity in another value. -// -// If entities with duplicate keys are present, an arbitrary choice will -// be made as to which is written. -type Mutation struct { - // Entities to upsert. - // Each upserted entity's key must have a complete path and - // must not be reserved/read-only. - Upsert []*Entity `protobuf:"bytes,1,rep,name=upsert" json:"upsert,omitempty"` - // Entities to update. - // Each updated entity's key must have a complete path and - // must not be reserved/read-only. - Update []*Entity `protobuf:"bytes,2,rep,name=update" json:"update,omitempty"` - // Entities to insert. - // Each inserted entity's key must have a complete path and - // must not be reserved/read-only. - Insert []*Entity `protobuf:"bytes,3,rep,name=insert" json:"insert,omitempty"` - // Insert entities with a newly allocated ID. - // Each inserted entity's key must omit the final identifier in its path and - // must not be reserved/read-only. - InsertAutoId []*Entity `protobuf:"bytes,4,rep,name=insert_auto_id" json:"insert_auto_id,omitempty"` - // Keys of entities to delete. - // Each key must have a complete key path and must not be reserved/read-only. - Delete []*Key `protobuf:"bytes,5,rep,name=delete" json:"delete,omitempty"` - // Ignore a user specified read-only period. Optional. - Force *bool `protobuf:"varint,6,opt,name=force" json:"force,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Mutation) Reset() { *m = Mutation{} } -func (m *Mutation) String() string { return proto.CompactTextString(m) } -func (*Mutation) ProtoMessage() {} - -func (m *Mutation) GetUpsert() []*Entity { - if m != nil { - return m.Upsert - } - return nil -} - -func (m *Mutation) GetUpdate() []*Entity { - if m != nil { - return m.Update - } - return nil -} - -func (m *Mutation) GetInsert() []*Entity { - if m != nil { - return m.Insert - } - return nil -} - -func (m *Mutation) GetInsertAutoId() []*Entity { - if m != nil { - return m.InsertAutoId - } - return nil -} - -func (m *Mutation) GetDelete() []*Key { - if m != nil { - return m.Delete - } - return nil -} - -func (m *Mutation) GetForce() bool { - if m != nil && m.Force != nil { - return *m.Force - } - return false -} - -// The result of applying a mutation. -type MutationResult struct { - // Number of index writes. - IndexUpdates *int32 `protobuf:"varint,1,req,name=index_updates" json:"index_updates,omitempty"` - // Keys for insertAutoId entities. One per entity from the - // request, in the same order. - InsertAutoIdKey []*Key `protobuf:"bytes,2,rep,name=insert_auto_id_key" json:"insert_auto_id_key,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MutationResult) Reset() { *m = MutationResult{} } -func (m *MutationResult) String() string { return proto.CompactTextString(m) } -func (*MutationResult) ProtoMessage() {} - -func (m *MutationResult) GetIndexUpdates() int32 { - if m != nil && m.IndexUpdates != nil { - return *m.IndexUpdates - } - return 0 -} - -func (m *MutationResult) GetInsertAutoIdKey() []*Key { - if m != nil { - return m.InsertAutoIdKey - } - return nil -} - -// Options shared by read requests. -type ReadOptions struct { - // The read consistency to use. - // Cannot be set when transaction is set. - // Lookup and ancestor queries default to STRONG, global queries default to - // EVENTUAL and cannot be set to STRONG. - ReadConsistency *ReadOptions_ReadConsistency `protobuf:"varint,1,opt,name=read_consistency,enum=pb.ReadOptions_ReadConsistency,def=0" json:"read_consistency,omitempty"` - // The transaction to use. Optional. - Transaction []byte `protobuf:"bytes,2,opt,name=transaction" json:"transaction,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ReadOptions) Reset() { *m = ReadOptions{} } -func (m *ReadOptions) String() string { return proto.CompactTextString(m) } -func (*ReadOptions) ProtoMessage() {} - -const Default_ReadOptions_ReadConsistency ReadOptions_ReadConsistency = ReadOptions_DEFAULT - -func (m *ReadOptions) GetReadConsistency() ReadOptions_ReadConsistency { - if m != nil && m.ReadConsistency != nil { - return *m.ReadConsistency - } - return Default_ReadOptions_ReadConsistency -} - -func (m *ReadOptions) GetTransaction() []byte { - if m != nil { - return m.Transaction - } - return nil -} - -// The request for Lookup. -type LookupRequest struct { - // Options for this lookup request. Optional. - ReadOptions *ReadOptions `protobuf:"bytes,1,opt,name=read_options" json:"read_options,omitempty"` - // Keys of entities to look up from the datastore. - Key []*Key `protobuf:"bytes,3,rep,name=key" json:"key,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LookupRequest) Reset() { *m = LookupRequest{} } -func (m *LookupRequest) String() string { return proto.CompactTextString(m) } -func (*LookupRequest) ProtoMessage() {} - -func (m *LookupRequest) GetReadOptions() *ReadOptions { - if m != nil { - return m.ReadOptions - } - return nil -} - -func (m *LookupRequest) GetKey() []*Key { - if m != nil { - return m.Key - } - return nil -} - -// The response for Lookup. -type LookupResponse struct { - // Entities found as ResultType.FULL entities. - Found []*EntityResult `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"` - // Entities not found as ResultType.KEY_ONLY entities. - Missing []*EntityResult `protobuf:"bytes,2,rep,name=missing" json:"missing,omitempty"` - // A list of keys that were not looked up due to resource constraints. - Deferred []*Key `protobuf:"bytes,3,rep,name=deferred" json:"deferred,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LookupResponse) Reset() { *m = LookupResponse{} } -func (m *LookupResponse) String() string { return proto.CompactTextString(m) } -func (*LookupResponse) ProtoMessage() {} - -func (m *LookupResponse) GetFound() []*EntityResult { - if m != nil { - return m.Found - } - return nil -} - -func (m *LookupResponse) GetMissing() []*EntityResult { - if m != nil { - return m.Missing - } - return nil -} - -func (m *LookupResponse) GetDeferred() []*Key { - if m != nil { - return m.Deferred - } - return nil -} - -// The request for RunQuery. -type RunQueryRequest struct { - // The options for this query. - ReadOptions *ReadOptions `protobuf:"bytes,1,opt,name=read_options" json:"read_options,omitempty"` - // Entities are partitioned into subsets, identified by a dataset (usually - // implicitly specified by the project) and namespace ID. Queries are scoped - // to a single partition. - // This partition ID is normalized with the standard default context - // partition ID, but all other partition IDs in RunQueryRequest are - // normalized with this partition ID as the context partition ID. - PartitionId *PartitionId `protobuf:"bytes,2,opt,name=partition_id" json:"partition_id,omitempty"` - // The query to run. - // Either this field or field gql_query must be set, but not both. - Query *Query `protobuf:"bytes,3,opt,name=query" json:"query,omitempty"` - // The GQL query to run. - // Either this field or field query must be set, but not both. - GqlQuery *GqlQuery `protobuf:"bytes,7,opt,name=gql_query" json:"gql_query,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RunQueryRequest) Reset() { *m = RunQueryRequest{} } -func (m *RunQueryRequest) String() string { return proto.CompactTextString(m) } -func (*RunQueryRequest) ProtoMessage() {} - -func (m *RunQueryRequest) GetReadOptions() *ReadOptions { - if m != nil { - return m.ReadOptions - } - return nil -} - -func (m *RunQueryRequest) GetPartitionId() *PartitionId { - if m != nil { - return m.PartitionId - } - return nil -} - -func (m *RunQueryRequest) GetQuery() *Query { - if m != nil { - return m.Query - } - return nil -} - -func (m *RunQueryRequest) GetGqlQuery() *GqlQuery { - if m != nil { - return m.GqlQuery - } - return nil -} - -// The response for RunQuery. -type RunQueryResponse struct { - // A batch of query results (always present). - Batch *QueryResultBatch `protobuf:"bytes,1,opt,name=batch" json:"batch,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RunQueryResponse) Reset() { *m = RunQueryResponse{} } -func (m *RunQueryResponse) String() string { return proto.CompactTextString(m) } -func (*RunQueryResponse) ProtoMessage() {} - -func (m *RunQueryResponse) GetBatch() *QueryResultBatch { - if m != nil { - return m.Batch - } - return nil -} - -// The request for BeginTransaction. -type BeginTransactionRequest struct { - // The transaction isolation level. - IsolationLevel *BeginTransactionRequest_IsolationLevel `protobuf:"varint,1,opt,name=isolation_level,enum=pb.BeginTransactionRequest_IsolationLevel,def=0" json:"isolation_level,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BeginTransactionRequest) Reset() { *m = BeginTransactionRequest{} } -func (m *BeginTransactionRequest) String() string { return proto.CompactTextString(m) } -func (*BeginTransactionRequest) ProtoMessage() {} - -const Default_BeginTransactionRequest_IsolationLevel BeginTransactionRequest_IsolationLevel = BeginTransactionRequest_SNAPSHOT - -func (m *BeginTransactionRequest) GetIsolationLevel() BeginTransactionRequest_IsolationLevel { - if m != nil && m.IsolationLevel != nil { - return *m.IsolationLevel - } - return Default_BeginTransactionRequest_IsolationLevel -} - -// The response for BeginTransaction. -type BeginTransactionResponse struct { - // The transaction identifier (always present). - Transaction []byte `protobuf:"bytes,1,opt,name=transaction" json:"transaction,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BeginTransactionResponse) Reset() { *m = BeginTransactionResponse{} } -func (m *BeginTransactionResponse) String() string { return proto.CompactTextString(m) } -func (*BeginTransactionResponse) ProtoMessage() {} - -func (m *BeginTransactionResponse) GetTransaction() []byte { - if m != nil { - return m.Transaction - } - return nil -} - -// The request for Rollback. -type RollbackRequest struct { - // The transaction identifier, returned by a call to - // beginTransaction. - Transaction []byte `protobuf:"bytes,1,req,name=transaction" json:"transaction,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RollbackRequest) Reset() { *m = RollbackRequest{} } -func (m *RollbackRequest) String() string { return proto.CompactTextString(m) } -func (*RollbackRequest) ProtoMessage() {} - -func (m *RollbackRequest) GetTransaction() []byte { - if m != nil { - return m.Transaction - } - return nil -} - -// The response for Rollback. -type RollbackResponse struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *RollbackResponse) Reset() { *m = RollbackResponse{} } -func (m *RollbackResponse) String() string { return proto.CompactTextString(m) } -func (*RollbackResponse) ProtoMessage() {} - -// The request for Commit. -type CommitRequest struct { - // The transaction identifier, returned by a call to - // beginTransaction. Must be set when mode is TRANSACTIONAL. - Transaction []byte `protobuf:"bytes,1,opt,name=transaction" json:"transaction,omitempty"` - // The mutation to perform. Optional. - Mutation *Mutation `protobuf:"bytes,2,opt,name=mutation" json:"mutation,omitempty"` - // The type of commit to perform. Either TRANSACTIONAL or NON_TRANSACTIONAL. - Mode *CommitRequest_Mode `protobuf:"varint,5,opt,name=mode,enum=pb.CommitRequest_Mode,def=1" json:"mode,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CommitRequest) Reset() { *m = CommitRequest{} } -func (m *CommitRequest) String() string { return proto.CompactTextString(m) } -func (*CommitRequest) ProtoMessage() {} - -const Default_CommitRequest_Mode CommitRequest_Mode = CommitRequest_TRANSACTIONAL - -func (m *CommitRequest) GetTransaction() []byte { - if m != nil { - return m.Transaction - } - return nil -} - -func (m *CommitRequest) GetMutation() *Mutation { - if m != nil { - return m.Mutation - } - return nil -} - -func (m *CommitRequest) GetMode() CommitRequest_Mode { - if m != nil && m.Mode != nil { - return *m.Mode - } - return Default_CommitRequest_Mode -} - -// The response for Commit. -type CommitResponse struct { - // The result of performing the mutation (if any). - MutationResult *MutationResult `protobuf:"bytes,1,opt,name=mutation_result" json:"mutation_result,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CommitResponse) Reset() { *m = CommitResponse{} } -func (m *CommitResponse) String() string { return proto.CompactTextString(m) } -func (*CommitResponse) ProtoMessage() {} - -func (m *CommitResponse) GetMutationResult() *MutationResult { - if m != nil { - return m.MutationResult - } - return nil -} - -// The request for AllocateIds. -type AllocateIdsRequest struct { - // A list of keys with incomplete key paths to allocate IDs for. - // No key may be reserved/read-only. - Key []*Key `protobuf:"bytes,1,rep,name=key" json:"key,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AllocateIdsRequest) Reset() { *m = AllocateIdsRequest{} } -func (m *AllocateIdsRequest) String() string { return proto.CompactTextString(m) } -func (*AllocateIdsRequest) ProtoMessage() {} - -func (m *AllocateIdsRequest) GetKey() []*Key { - if m != nil { - return m.Key - } - return nil -} - -// The response for AllocateIds. -type AllocateIdsResponse struct { - // The keys specified in the request (in the same order), each with - // its key path completed with a newly allocated ID. - Key []*Key `protobuf:"bytes,1,rep,name=key" json:"key,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AllocateIdsResponse) Reset() { *m = AllocateIdsResponse{} } -func (m *AllocateIdsResponse) String() string { return proto.CompactTextString(m) } -func (*AllocateIdsResponse) ProtoMessage() {} - -func (m *AllocateIdsResponse) GetKey() []*Key { - if m != nil { - return m.Key - } - return nil -} - -func init() { - proto.RegisterEnum("pb.EntityResult_ResultType", EntityResult_ResultType_name, EntityResult_ResultType_value) - proto.RegisterEnum("pb.PropertyExpression_AggregationFunction", PropertyExpression_AggregationFunction_name, PropertyExpression_AggregationFunction_value) - proto.RegisterEnum("pb.PropertyOrder_Direction", PropertyOrder_Direction_name, PropertyOrder_Direction_value) - proto.RegisterEnum("pb.CompositeFilter_Operator", CompositeFilter_Operator_name, CompositeFilter_Operator_value) - proto.RegisterEnum("pb.PropertyFilter_Operator", PropertyFilter_Operator_name, PropertyFilter_Operator_value) - proto.RegisterEnum("pb.QueryResultBatch_MoreResultsType", QueryResultBatch_MoreResultsType_name, QueryResultBatch_MoreResultsType_value) - proto.RegisterEnum("pb.ReadOptions_ReadConsistency", ReadOptions_ReadConsistency_name, ReadOptions_ReadConsistency_value) - proto.RegisterEnum("pb.BeginTransactionRequest_IsolationLevel", BeginTransactionRequest_IsolationLevel_name, BeginTransactionRequest_IsolationLevel_value) - proto.RegisterEnum("pb.CommitRequest_Mode", CommitRequest_Mode_name, CommitRequest_Mode_value) -} diff --git a/Godeps/_workspace/src/google.golang.org/cloud/internal/datastore/datastore_v1.proto b/Godeps/_workspace/src/google.golang.org/cloud/internal/datastore/datastore_v1.proto deleted file mode 100644 index bb4c199b1..000000000 --- a/Godeps/_workspace/src/google.golang.org/cloud/internal/datastore/datastore_v1.proto +++ /dev/null @@ -1,594 +0,0 @@ -// Copyright 2013 Google Inc. All Rights Reserved. -// -// The datastore v1 service proto definitions - -syntax = "proto2"; - -package pb; -option java_package = "com.google.api.services.datastore"; - - -// An identifier for a particular subset of entities. -// -// Entities are partitioned into various subsets, each used by different -// datasets and different namespaces within a dataset and so forth. -// -// All input partition IDs are normalized before use. -// A partition ID is normalized as follows: -// If the partition ID is unset or is set to an empty partition ID, replace it -// with the context partition ID. -// Otherwise, if the partition ID has no dataset ID, assign it the context -// partition ID's dataset ID. -// Unless otherwise documented, the context partition ID has the dataset ID set -// to the context dataset ID and no other partition dimension set. -// -// A partition ID is empty if all of its fields are unset. -// -// Partition dimension: -// A dimension may be unset. -// A dimension's value must never be "". -// A dimension's value must match [A-Za-z\d\.\-_]{1,100} -// If the value of any dimension matches regex "__.*__", -// the partition is reserved/read-only. -// A reserved/read-only partition ID is forbidden in certain documented contexts. -// -// Dataset ID: -// A dataset id's value must never be "". -// A dataset id's value must match -// ([a-z\d\-]{1,100}~)?([a-z\d][a-z\d\-\.]{0,99}:)?([a-z\d][a-z\d\-]{0,99} -message PartitionId { - // The dataset ID. - optional string dataset_id = 3; - // The namespace. - optional string namespace = 4; -} - -// A unique identifier for an entity. -// If a key's partition id or any of its path kinds or names are -// reserved/read-only, the key is reserved/read-only. -// A reserved/read-only key is forbidden in certain documented contexts. -message Key { - // Entities are partitioned into subsets, currently identified by a dataset - // (usually implicitly specified by the project) and namespace ID. - // Queries are scoped to a single partition. - optional PartitionId partition_id = 1; - - // A (kind, ID/name) pair used to construct a key path. - // - // At most one of name or ID may be set. - // If either is set, the element is complete. - // If neither is set, the element is incomplete. - message PathElement { - // The kind of the entity. - // A kind matching regex "__.*__" is reserved/read-only. - // A kind must not contain more than 500 characters. - // Cannot be "". - required string kind = 1; - // The ID of the entity. - // Never equal to zero. Values less than zero are discouraged and will not - // be supported in the future. - optional int64 id = 2; - // The name of the entity. - // A name matching regex "__.*__" is reserved/read-only. - // A name must not be more than 500 characters. - // Cannot be "". - optional string name = 3; - } - - // The entity path. - // An entity path consists of one or more elements composed of a kind and a - // string or numerical identifier, which identify entities. The first - // element identifies a root entity, the second element identifies - // a child of the root entity, the third element a child of the - // second entity, and so forth. The entities identified by all prefixes of - // the path are called the element's ancestors. - // An entity path is always fully complete: ALL of the entity's ancestors - // are required to be in the path along with the entity identifier itself. - // The only exception is that in some documented cases, the identifier in the - // last path element (for the entity) itself may be omitted. A path can never - // be empty. - repeated PathElement path_element = 2; -} - -// A message that can hold any of the supported value types and associated -// metadata. -// -// At most one of the Value fields may be set. -// If none are set the value is "null". -// -message Value { - // A boolean value. - optional bool boolean_value = 1; - // An integer value. - optional int64 integer_value = 2; - // A double value. - optional double double_value = 3; - // A timestamp value. - optional int64 timestamp_microseconds_value = 4; - // A key value. - optional Key key_value = 5; - // A blob key value. - optional string blob_key_value = 16; - // A UTF-8 encoded string value. - optional string string_value = 17; - // A blob value. - optional bytes blob_value = 18; - // An entity value. - // May have no key. - // May have a key with an incomplete key path. - // May have a reserved/read-only key. - optional Entity entity_value = 6; - // A list value. - // Cannot contain another list value. - // Cannot also have a meaning and indexing set. - repeated Value list_value = 7; - - // The meaning field is reserved and should not be used. - optional int32 meaning = 14; - - // If the value should be indexed. - // - // The indexed property may be set for a - // null value. - // When indexed is true, stringValue - // is limited to 500 characters and the blob value is limited to 500 bytes. - // Exception: If meaning is set to 2, string_value is limited to 2038 - // characters regardless of indexed. - // When indexed is true, meaning 15 and 22 are not allowed, and meaning 16 - // will be ignored on input (and will never be set on output). - // Input values by default have indexed set to - // true; however, you can explicitly set indexed to - // true if you want. (An output value never has - // indexed explicitly set to true.) If a value is - // itself an entity, it cannot have indexed set to - // true. - // Exception: An entity value with meaning 9, 20 or 21 may be indexed. - optional bool indexed = 15 [default = true]; -} - -// An entity property. -message Property { - // The name of the property. - // A property name matching regex "__.*__" is reserved. - // A reserved property name is forbidden in certain documented contexts. - // The name must not contain more than 500 characters. - // Cannot be "". - required string name = 1; - - // The value(s) of the property. - // Each value can have only one value property populated. For example, - // you cannot have a values list of { value: { integerValue: 22, - // stringValue: "a" } }, but you can have { value: { listValue: - // [ { integerValue: 22 }, { stringValue: "a" } ] }. - required Value value = 4; -} - -// An entity. -// -// An entity is limited to 1 megabyte when stored. That roughly -// corresponds to a limit of 1 megabyte for the serialized form of this -// message. -message Entity { - // The entity's key. - // - // An entity must have a key, unless otherwise documented (for example, - // an entity in Value.entityValue may have no key). - // An entity's kind is its key's path's last element's kind, - // or null if it has no key. - optional Key key = 1; - // The entity's properties. - // Each property's name must be unique for its entity. - repeated Property property = 2; -} - -// The result of fetching an entity from the datastore. -message EntityResult { - // Specifies what data the 'entity' field contains. - // A ResultType is either implied (for example, in LookupResponse.found it - // is always FULL) or specified by context (for example, in message - // QueryResultBatch, field 'entity_result_type' specifies a ResultType - // for all the values in field 'entity_result'). - enum ResultType { - FULL = 1; // The entire entity. - PROJECTION = 2; // A projected subset of properties. - // The entity may have no key. - // A property value may have meaning 18. - KEY_ONLY = 3; // Only the key. - } - - // The resulting entity. - required Entity entity = 1; -} - -// A query. -message Query { - // The projection to return. If not set the entire entity is returned. - repeated PropertyExpression projection = 2; - - // The kinds to query (if empty, returns entities from all kinds). - repeated KindExpression kind = 3; - - // The filter to apply (optional). - optional Filter filter = 4; - - // The order to apply to the query results (if empty, order is unspecified). - repeated PropertyOrder order = 5; - - // The properties to group by (if empty, no grouping is applied to the - // result set). - repeated PropertyReference group_by = 6; - - // A starting point for the query results. Optional. Query cursors are - // returned in query result batches. - optional bytes /* serialized QueryCursor */ start_cursor = 7; - - // An ending point for the query results. Optional. Query cursors are - // returned in query result batches. - optional bytes /* serialized QueryCursor */ end_cursor = 8; - - // The number of results to skip. Applies before limit, but after all other - // constraints (optional, defaults to 0). - optional int32 offset = 10 [default=0]; - - // The maximum number of results to return. Applies after all other - // constraints. Optional. - optional int32 limit = 11; -} - -// A representation of a kind. -message KindExpression { - // The name of the kind. - required string name = 1; -} - -// A reference to a property relative to the kind expressions. -// exactly. -message PropertyReference { - // The name of the property. - required string name = 2; -} - -// A representation of a property in a projection. -message PropertyExpression { - enum AggregationFunction { - FIRST = 1; - } - // The property to project. - required PropertyReference property = 1; - // The aggregation function to apply to the property. Optional. - // Can only be used when grouping by at least one property. Must - // then be set on all properties in the projection that are not - // being grouped by. - optional AggregationFunction aggregation_function = 2; -} - -// The desired order for a specific property. -message PropertyOrder { - enum Direction { - ASCENDING = 1; - DESCENDING = 2; - } - // The property to order by. - required PropertyReference property = 1; - // The direction to order by. - optional Direction direction = 2 [default=ASCENDING]; -} - -// A holder for any type of filter. Exactly one field should be specified. -message Filter { - // A composite filter. - optional CompositeFilter composite_filter = 1; - // A filter on a property. - optional PropertyFilter property_filter = 2; -} - -// A filter that merges the multiple other filters using the given operation. -message CompositeFilter { - enum Operator { - AND = 1; - } - - // The operator for combining multiple filters. - required Operator operator = 1; - // The list of filters to combine. - // Must contain at least one filter. - repeated Filter filter = 2; -} - -// A filter on a specific property. -message PropertyFilter { - enum Operator { - LESS_THAN = 1; - LESS_THAN_OR_EQUAL = 2; - GREATER_THAN = 3; - GREATER_THAN_OR_EQUAL = 4; - EQUAL = 5; - - HAS_ANCESTOR = 11; - } - - // The property to filter by. - required PropertyReference property = 1; - // The operator to filter by. - required Operator operator = 2; - // The value to compare the property to. - required Value value = 3; -} - -// A GQL query. -message GqlQuery { - required string query_string = 1; - // When false, the query string must not contain a literal. - optional bool allow_literal = 2 [default = false]; - // A named argument must set field GqlQueryArg.name. - // No two named arguments may have the same name. - // For each non-reserved named binding site in the query string, - // there must be a named argument with that name, - // but not necessarily the inverse. - repeated GqlQueryArg name_arg = 3; - // Numbered binding site @1 references the first numbered argument, - // effectively using 1-based indexing, rather than the usual 0. - // A numbered argument must NOT set field GqlQueryArg.name. - // For each binding site numbered i in query_string, - // there must be an ith numbered argument. - // The inverse must also be true. - repeated GqlQueryArg number_arg = 4; -} - -// A binding argument for a GQL query. -// Exactly one of fields value and cursor must be set. -message GqlQueryArg { - // Must match regex "[A-Za-z_$][A-Za-z_$0-9]*". - // Must not match regex "__.*__". - // Must not be "". - optional string name = 1; - optional Value value = 2; - optional bytes cursor = 3; -} - -// A batch of results produced by a query. -message QueryResultBatch { - // The possible values for the 'more_results' field. - enum MoreResultsType { - NOT_FINISHED = 1; // There are additional batches to fetch from this query. - MORE_RESULTS_AFTER_LIMIT = 2; // The query is finished, but there are more - // results after the limit. - NO_MORE_RESULTS = 3; // The query has been exhausted. - } - - // The result type for every entity in entityResults. - required EntityResult.ResultType entity_result_type = 1; - // The results for this batch. - repeated EntityResult entity_result = 2; - - // A cursor that points to the position after the last result in the batch. - // May be absent. - optional bytes /* serialized QueryCursor */ end_cursor = 4; - - // The state of the query after the current batch. - required MoreResultsType more_results = 5; - - // The number of results skipped because of Query.offset. - optional int32 skipped_results = 6; -} - -// A set of changes to apply. -// -// No entity in this message may have a reserved property name, -// not even a property in an entity in a value. -// No value in this message may have meaning 18, -// not even a value in an entity in another value. -// -// If entities with duplicate keys are present, an arbitrary choice will -// be made as to which is written. -message Mutation { - // Entities to upsert. - // Each upserted entity's key must have a complete path and - // must not be reserved/read-only. - repeated Entity upsert = 1; - // Entities to update. - // Each updated entity's key must have a complete path and - // must not be reserved/read-only. - repeated Entity update = 2; - // Entities to insert. - // Each inserted entity's key must have a complete path and - // must not be reserved/read-only. - repeated Entity insert = 3; - // Insert entities with a newly allocated ID. - // Each inserted entity's key must omit the final identifier in its path and - // must not be reserved/read-only. - repeated Entity insert_auto_id = 4; - // Keys of entities to delete. - // Each key must have a complete key path and must not be reserved/read-only. - repeated Key delete = 5; - // Ignore a user specified read-only period. Optional. - optional bool force = 6; -} - -// The result of applying a mutation. -message MutationResult { - // Number of index writes. - required int32 index_updates = 1; - // Keys for insertAutoId entities. One per entity from the - // request, in the same order. - repeated Key insert_auto_id_key = 2; -} - -// Options shared by read requests. -message ReadOptions { - enum ReadConsistency { - DEFAULT = 0; - STRONG = 1; - EVENTUAL = 2; - } - - // The read consistency to use. - // Cannot be set when transaction is set. - // Lookup and ancestor queries default to STRONG, global queries default to - // EVENTUAL and cannot be set to STRONG. - optional ReadConsistency read_consistency = 1 [default=DEFAULT]; - - // The transaction to use. Optional. - optional bytes /* serialized Transaction */ transaction = 2; -} - -// The request for Lookup. -message LookupRequest { - - // Options for this lookup request. Optional. - optional ReadOptions read_options = 1; - // Keys of entities to look up from the datastore. - repeated Key key = 3; -} - -// The response for Lookup. -message LookupResponse { - - // The order of results in these fields is undefined and has no relation to - // the order of the keys in the input. - - // Entities found as ResultType.FULL entities. - repeated EntityResult found = 1; - - // Entities not found as ResultType.KEY_ONLY entities. - repeated EntityResult missing = 2; - - // A list of keys that were not looked up due to resource constraints. - repeated Key deferred = 3; -} - - -// The request for RunQuery. -message RunQueryRequest { - - // The options for this query. - optional ReadOptions read_options = 1; - - // Entities are partitioned into subsets, identified by a dataset (usually - // implicitly specified by the project) and namespace ID. Queries are scoped - // to a single partition. - // This partition ID is normalized with the standard default context - // partition ID, but all other partition IDs in RunQueryRequest are - // normalized with this partition ID as the context partition ID. - optional PartitionId partition_id = 2; - - // The query to run. - // Either this field or field gql_query must be set, but not both. - optional Query query = 3; - // The GQL query to run. - // Either this field or field query must be set, but not both. - optional GqlQuery gql_query = 7; -} - -// The response for RunQuery. -message RunQueryResponse { - - // A batch of query results (always present). - optional QueryResultBatch batch = 1; - -} - -// The request for BeginTransaction. -message BeginTransactionRequest { - - enum IsolationLevel { - SNAPSHOT = 0; // Read from a consistent snapshot. Concurrent transactions - // conflict if their mutations conflict. For example: - // Read(A),Write(B) may not conflict with Read(B),Write(A), - // but Read(B),Write(B) does conflict with Read(B),Write(B). - SERIALIZABLE = 1; // Read from a consistent snapshot. Concurrent - // transactions conflict if they cannot be serialized. - // For example Read(A),Write(B) does conflict with - // Read(B),Write(A) but Read(A) may not conflict with - // Write(A). - } - - // The transaction isolation level. - optional IsolationLevel isolation_level = 1 [default=SNAPSHOT]; -} - -// The response for BeginTransaction. -message BeginTransactionResponse { - - // The transaction identifier (always present). - optional bytes /* serialized Transaction */ transaction = 1; -} - -// The request for Rollback. -message RollbackRequest { - - // The transaction identifier, returned by a call to - // beginTransaction. - required bytes /* serialized Transaction */ transaction = 1; -} - -// The response for Rollback. -message RollbackResponse { -// Empty -} - -// The request for Commit. -message CommitRequest { - - enum Mode { - TRANSACTIONAL = 1; - NON_TRANSACTIONAL = 2; - } - - // The transaction identifier, returned by a call to - // beginTransaction. Must be set when mode is TRANSACTIONAL. - optional bytes /* serialized Transaction */ transaction = 1; - // The mutation to perform. Optional. - optional Mutation mutation = 2; - // The type of commit to perform. Either TRANSACTIONAL or NON_TRANSACTIONAL. - optional Mode mode = 5 [default=TRANSACTIONAL]; -} - -// The response for Commit. -message CommitResponse { - - // The result of performing the mutation (if any). - optional MutationResult mutation_result = 1; -} - -// The request for AllocateIds. -message AllocateIdsRequest { - - // A list of keys with incomplete key paths to allocate IDs for. - // No key may be reserved/read-only. - repeated Key key = 1; -} - -// The response for AllocateIds. -message AllocateIdsResponse { - - // The keys specified in the request (in the same order), each with - // its key path completed with a newly allocated ID. - repeated Key key = 1; -} - -// Each rpc normalizes the partition IDs of the keys in its input entities, -// and always returns entities with keys with normalized partition IDs. -// (Note that applies to all entities, including entities in values.) -service DatastoreService { - // Look up some entities by key. - rpc Lookup(LookupRequest) returns (LookupResponse) { - }; - // Query for entities. - rpc RunQuery(RunQueryRequest) returns (RunQueryResponse) { - }; - // Begin a new transaction. - rpc BeginTransaction(BeginTransactionRequest) returns (BeginTransactionResponse) { - }; - // Commit a transaction, optionally creating, deleting or modifying some - // entities. - rpc Commit(CommitRequest) returns (CommitResponse) { - }; - // Roll back a transaction. - rpc Rollback(RollbackRequest) returns (RollbackResponse) { - }; - // Allocate IDs for incomplete keys (useful for referencing an entity before - // it is inserted). - rpc AllocateIds(AllocateIdsRequest) returns (AllocateIdsResponse) { - }; -} diff --git a/Godeps/_workspace/src/google.golang.org/cloud/internal/testutil/context.go b/Godeps/_workspace/src/google.golang.org/cloud/internal/testutil/context.go deleted file mode 100644 index aafd68387..000000000 --- a/Godeps/_workspace/src/google.golang.org/cloud/internal/testutil/context.go +++ /dev/null @@ -1,57 +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. - -// Package testutil contains helper functions for writing tests. -package testutil - -import ( - "io/ioutil" - "log" - "net/http" - "os" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "google.golang.org/cloud" -) - -const ( - envProjID = "GCLOUD_TESTS_GOLANG_PROJECT_ID" - envPrivateKey = "GCLOUD_TESTS_GOLANG_KEY" -) - -func Context(scopes ...string) context.Context { - key, projID := os.Getenv(envPrivateKey), os.Getenv(envProjID) - if key == "" || projID == "" { - log.Fatal("GCLOUD_TESTS_GOLANG_KEY and GCLOUD_TESTS_GOLANG_PROJECT_ID must be set. See CONTRIBUTING.md for details.") - } - jsonKey, err := ioutil.ReadFile(key) - if err != nil { - log.Fatalf("Cannot read the JSON key file, err: %v", err) - } - conf, err := google.JWTConfigFromJSON(jsonKey, scopes...) - if err != nil { - log.Fatal(err) - } - return cloud.NewContext(projID, conf.Client(oauth2.NoContext)) -} - -func NoAuthContext() context.Context { - projID := os.Getenv(envProjID) - if projID == "" { - log.Fatal("GCLOUD_TESTS_GOLANG_PROJECT_ID must be set. See CONTRIBUTING.md for details.") - } - return cloud.NewContext(projID, &http.Client{Transport: http.DefaultTransport}) -} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go deleted file mode 100644 index 90ffcc017..000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go +++ /dev/null @@ -1,902 +0,0 @@ -package yaml_test - -import ( - "errors" - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "math" - "net" - "reflect" - "strings" - "time" -) - -var unmarshalIntTest = 123 - -var unmarshalTests = []struct { - data string - value interface{} -}{ - { - "", - &struct{}{}, - }, { - "{}", &struct{}{}, - }, { - "v: hi", - map[string]string{"v": "hi"}, - }, { - "v: hi", map[string]interface{}{"v": "hi"}, - }, { - "v: true", - map[string]string{"v": "true"}, - }, { - "v: true", - map[string]interface{}{"v": true}, - }, { - "v: 10", - map[string]interface{}{"v": 10}, - }, { - "v: 0b10", - map[string]interface{}{"v": 2}, - }, { - "v: 0xA", - map[string]interface{}{"v": 10}, - }, { - "v: 4294967296", - map[string]int64{"v": 4294967296}, - }, { - "v: 0.1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .Inf", - map[string]interface{}{"v": math.Inf(+1)}, - }, { - "v: -.Inf", - map[string]interface{}{"v": math.Inf(-1)}, - }, { - "v: -10", - map[string]interface{}{"v": -10}, - }, { - "v: -.1", - map[string]interface{}{"v": -0.1}, - }, - - // Simple values. - { - "123", - &unmarshalIntTest, - }, - - // Floats from spec - { - "canonical: 6.8523e+5", - map[string]interface{}{"canonical": 6.8523e+5}, - }, { - "expo: 685.230_15e+03", - map[string]interface{}{"expo": 685.23015e+03}, - }, { - "fixed: 685_230.15", - map[string]interface{}{"fixed": 685230.15}, - }, { - "neginf: -.inf", - map[string]interface{}{"neginf": math.Inf(-1)}, - }, { - "fixed: 685_230.15", - map[string]float64{"fixed": 685230.15}, - }, - //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported - //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. - - // Bools from spec - { - "canonical: y", - map[string]interface{}{"canonical": true}, - }, { - "answer: NO", - map[string]interface{}{"answer": false}, - }, { - "logical: True", - map[string]interface{}{"logical": true}, - }, { - "option: on", - map[string]interface{}{"option": true}, - }, { - "option: on", - map[string]bool{"option": true}, - }, - // Ints from spec - { - "canonical: 685230", - map[string]interface{}{"canonical": 685230}, - }, { - "decimal: +685_230", - map[string]interface{}{"decimal": 685230}, - }, { - "octal: 02472256", - map[string]interface{}{"octal": 685230}, - }, { - "hexa: 0x_0A_74_AE", - map[string]interface{}{"hexa": 685230}, - }, { - "bin: 0b1010_0111_0100_1010_1110", - map[string]interface{}{"bin": 685230}, - }, { - "bin: -0b101010", - map[string]interface{}{"bin": -42}, - }, { - "decimal: +685_230", - map[string]int{"decimal": 685230}, - }, - - //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported - - // Nulls from spec - { - "empty:", - map[string]interface{}{"empty": nil}, - }, { - "canonical: ~", - map[string]interface{}{"canonical": nil}, - }, { - "english: null", - map[string]interface{}{"english": nil}, - }, { - "~: null key", - map[interface{}]string{nil: "null key"}, - }, { - "empty:", - map[string]*bool{"empty": nil}, - }, - - // Flow sequence - { - "seq: [A,B]", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq: [A,B,C,]", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]int{"seq": []int{1}}, - }, { - "seq: [A,1,C]", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - // Block sequence - { - "seq:\n - A\n - B", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq:\n - A\n - B\n - C", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]int{"seq": []int{1}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - - // Literal block scalar - { - "scalar: | # Comment\n\n literal\n\n \ttext\n\n", - map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, - }, - - // Folded block scalar - { - "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", - map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, - }, - - // Map inside interface with no type hints. - { - "a: {b: c}", - map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - }, - - // Structs and type conversions. - { - "hello: world", - &struct{ Hello string }{"world"}, - }, { - "a: {b: c}", - &struct{ A struct{ B string } }{struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A map[string]string }{map[string]string{"b": "c"}}, - }, { - "a: {b: c}", - &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, - }, { - "a:", - &struct{ A map[string]string }{}, - }, { - "a: 1", - &struct{ A int }{1}, - }, { - "a: 1", - &struct{ A float64 }{1}, - }, { - "a: 1.0", - &struct{ A int }{1}, - }, { - "a: 1.0", - &struct{ A uint }{1}, - }, { - "a: [1, 2]", - &struct{ A []int }{[]int{1, 2}}, - }, { - "a: 1", - &struct{ B int }{0}, - }, { - "a: 1", - &struct { - B int "a" - }{1}, - }, { - "a: y", - &struct{ A bool }{true}, - }, - - // Some cross type conversions - { - "v: 42", - map[string]uint{"v": 42}, - }, { - "v: -42", - map[string]uint{}, - }, { - "v: 4294967296", - map[string]uint64{"v": 4294967296}, - }, { - "v: -4294967296", - map[string]uint64{}, - }, - - // int - { - "int_max: 2147483647", - map[string]int{"int_max": math.MaxInt32}, - }, - { - "int_min: -2147483648", - map[string]int{"int_min": math.MinInt32}, - }, - { - "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int{}, - }, - - // int64 - { - "int64_max: 9223372036854775807", - map[string]int64{"int64_max": math.MaxInt64}, - }, - { - "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_max_base2": math.MaxInt64}, - }, - { - "int64_min: -9223372036854775808", - map[string]int64{"int64_min": math.MinInt64}, - }, - { - "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_neg_base2": -math.MaxInt64}, - }, - { - "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int64{}, - }, - - // uint - { - "uint_min: 0", - map[string]uint{"uint_min": 0}, - }, - { - "uint_max: 4294967295", - map[string]uint{"uint_max": math.MaxUint32}, - }, - { - "uint_underflow: -1", - map[string]uint{}, - }, - - // uint64 - { - "uint64_min: 0", - map[string]uint{"uint64_min": 0}, - }, - { - "uint64_max: 18446744073709551615", - map[string]uint64{"uint64_max": math.MaxUint64}, - }, - { - "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", - map[string]uint64{"uint64_max_base2": math.MaxUint64}, - }, - { - "uint64_maxint64: 9223372036854775807", - map[string]uint64{"uint64_maxint64": math.MaxInt64}, - }, - { - "uint64_underflow: -1", - map[string]uint64{}, - }, - - // float32 - { - "float32_max: 3.40282346638528859811704183484516925440e+38", - map[string]float32{"float32_max": math.MaxFloat32}, - }, - { - "float32_nonzero: 1.401298464324817070923729583289916131280e-45", - map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, - }, - { - "float32_maxuint64: 18446744073709551615", - map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, - }, - { - "float32_maxuint64+1: 18446744073709551616", - map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, - }, - - // float64 - { - "float64_max: 1.797693134862315708145274237317043567981e+308", - map[string]float64{"float64_max": math.MaxFloat64}, - }, - { - "float64_nonzero: 4.940656458412465441765687928682213723651e-324", - map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, - }, - { - "float64_maxuint64: 18446744073709551615", - map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, - }, - { - "float64_maxuint64+1: 18446744073709551616", - map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, - }, - - // Overflow cases. - { - "v: 4294967297", - map[string]int32{}, - }, { - "v: 128", - map[string]int8{}, - }, - - // Quoted values. - { - "'1': '\"2\"'", - map[interface{}]interface{}{"1": "\"2\""}, - }, { - "v:\n- A\n- 'B\n\n C'\n", - map[string][]string{"v": []string{"A", "B\nC"}}, - }, - - // Explicit tags. - { - "v: !!float '1.1'", - map[string]interface{}{"v": 1.1}, - }, { - "v: !!null ''", - map[string]interface{}{"v": nil}, - }, { - "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", - map[string]interface{}{"v": 1}, - }, - - // Anchors and aliases. - { - "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", - &struct{ A, B, C, D int }{1, 2, 1, 2}, - }, { - "a: &a {c: 1}\nb: *a", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, { - "a: &a [1, 2]\nb: *a", - &struct{ B []int }{[]int{1, 2}}, - }, - - // Bug #1133337 - { - "foo: ''", - map[string]*string{"foo": new(string)}, - }, { - "foo: null", - map[string]string{"foo": ""}, - }, { - "foo: null", - map[string]interface{}{"foo": nil}, - }, - - // Ignored field - { - "a: 1\nb: 2\n", - &struct { - A int - B int "-" - }{1, 0}, - }, - - // Bug #1191981 - { - "" + - "%YAML 1.1\n" + - "--- !!str\n" + - `"Generic line break (no glyph)\n\` + "\n" + - ` Generic line break (glyphed)\n\` + "\n" + - ` Line separator\u2028\` + "\n" + - ` Paragraph separator\u2029"` + "\n", - "" + - "Generic line break (no glyph)\n" + - "Generic line break (glyphed)\n" + - "Line separator\u2028Paragraph separator\u2029", - }, - - // Struct inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - }, - - // bug 1243827 - { - "a: -b_c", - map[string]interface{}{"a": "-b_c"}, - }, - { - "a: +b_c", - map[string]interface{}{"a": "+b_c"}, - }, - { - "a: 50cent_of_dollar", - map[string]interface{}{"a": "50cent_of_dollar"}, - }, - - // Duration - { - "a: 3s", - map[string]time.Duration{"a": 3 * time.Second}, - }, - - // Issue #24. - { - "a: ", - map[string]string{"a": ""}, - }, - - // Base 60 floats are obsolete and unsupported. - { - "a: 1:1\n", - map[string]string{"a": "1:1"}, - }, - - // Binary data. - { - "a: !!binary gIGC\n", - map[string]string{"a": "\x80\x81\x82"}, - }, { - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - map[string]string{"a": strings.Repeat("\x90", 54)}, - }, { - "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", - map[string]string{"a": strings.Repeat("\x00", 52)}, - }, - - // Ordered maps. - { - "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - }, - - // Issue #39. - { - "a:\n b:\n c: d\n", - map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, - }, - - // Custom map type. - { - "a: {b: c}", - M{"a": M{"b": "c"}}, - }, - - // Support encoding.TextUnmarshaler. - { - "a: 1.2.3.4\n", - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - }, -} - -type M map[interface{}]interface{} - -type inlineB struct { - B int - inlineC `yaml:",inline"` -} - -type inlineC struct { - C int -} - -func (s *S) TestUnmarshal(c *C) { - for _, item := range unmarshalTests { - t := reflect.ValueOf(item.value).Type() - var value interface{} - switch t.Kind() { - case reflect.Map: - value = reflect.MakeMap(t).Interface() - case reflect.String: - value = reflect.New(t).Interface() - case reflect.Ptr: - value = reflect.New(t.Elem()).Interface() - default: - c.Fatalf("missing case for %s", t) - } - err := yaml.Unmarshal([]byte(item.data), value) - if _, ok := err.(*yaml.TypeError); !ok { - c.Assert(err, IsNil) - } - if t.Kind() == reflect.String { - c.Assert(*value.(*string), Equals, item.value) - } else { - c.Assert(value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalNaN(c *C) { - value := map[string]interface{}{} - err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) - c.Assert(err, IsNil) - c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) -} - -var unmarshalErrorTests = []struct { - data, error string -}{ - {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, - {"v: [A,", "yaml: line 1: did not find expected node content"}, - {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, - {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, - {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, - {"value: -", "yaml: block sequence entries are not allowed in this context"}, - {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, - {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, - {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, -} - -func (s *S) TestUnmarshalErrors(c *C) { - for _, item := range unmarshalErrorTests { - var value interface{} - err := yaml.Unmarshal([]byte(item.data), &value) - c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) - } -} - -var unmarshalerTests = []struct { - data, tag string - value interface{} -}{ - {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, - {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, - {"_: 10", "!!int", 10}, - {"_: null", "!!null", nil}, - {`_: BAR!`, "!!str", "BAR!"}, - {`_: "BAR!"`, "!!str", "BAR!"}, - {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, -} - -var unmarshalerResult = map[int]error{} - -type unmarshalerType struct { - value interface{} -} - -func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { - if err := unmarshal(&o.value); err != nil { - return err - } - if i, ok := o.value.(int); ok { - if result, ok := unmarshalerResult[i]; ok { - return result - } - } - return nil -} - -type unmarshalerPointer struct { - Field *unmarshalerType "_" -} - -type unmarshalerValue struct { - Field unmarshalerType "_" -} - -func (s *S) TestUnmarshalerPointerField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerPointer{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - if item.value == nil { - c.Assert(obj.Field, IsNil) - } else { - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalerValueField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerValue{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } -} - -func (s *S) TestUnmarshalerWholeDocument(c *C) { - obj := &unmarshalerType{} - err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) - c.Assert(err, IsNil) - value, ok := obj.value.(map[interface{}]interface{}) - c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) - c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) -} - -func (s *S) TestUnmarshalerTypeError(c *C) { - unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} - unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} - defer func() { - delete(unmarshalerResult, 2) - delete(unmarshalerResult, 4) - }() - - type T struct { - Before int - After int - M map[string]*unmarshalerType - } - var v T - data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " foo\n"+ - " bar\n"+ - " line 1: cannot unmarshal !!str `B` into int") - c.Assert(v.M["abc"], NotNil) - c.Assert(v.M["def"], IsNil) - c.Assert(v.M["ghi"], NotNil) - c.Assert(v.M["jkl"], IsNil) - - c.Assert(v.M["abc"].value, Equals, 1) - c.Assert(v.M["ghi"].value, Equals, 3) -} - -type proxyTypeError struct{} - -func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { - var s string - var a int32 - var b int64 - if err := unmarshal(&s); err != nil { - panic(err) - } - if s == "a" { - if err := unmarshal(&b); err == nil { - panic("should have failed") - } - return unmarshal(&a) - } - if err := unmarshal(&a); err == nil { - panic("should have failed") - } - return unmarshal(&b) -} - -func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { - type T struct { - Before int - After int - M map[string]*proxyTypeError - } - var v T - data := `{before: A, m: {abc: a, def: b}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " line 1: cannot unmarshal !!str `a` into int32\n"+ - " line 1: cannot unmarshal !!str `b` into int64\n"+ - " line 1: cannot unmarshal !!str `B` into int") -} - -type failingUnmarshaler struct{} - -var failingErr = errors.New("failingErr") - -func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - return failingErr -} - -func (s *S) TestUnmarshalerError(c *C) { - err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) - c.Assert(err, Equals, failingErr) -} - -// From http://yaml.org/type/merge.html -var mergeTests = ` -anchors: - list: - - &CENTER { "x": 1, "y": 2 } - - &LEFT { "x": 0, "y": 2 } - - &BIG { "r": 10 } - - &SMALL { "r": 1 } - -# All the following maps are equal: - -plain: - # Explicit keys - "x": 1 - "y": 2 - "r": 10 - label: center/big - -mergeOne: - # Merge one map - << : *CENTER - "r": 10 - label: center/big - -mergeMultiple: - # Merge multiple maps - << : [ *CENTER, *BIG ] - label: center/big - -override: - # Override - << : [ *BIG, *LEFT, *SMALL ] - "x": 1 - label: center/big - -shortTag: - # Explicit short merge tag - !!merge "<<" : [ *CENTER, *BIG ] - label: center/big - -longTag: - # Explicit merge long tag - ! "<<" : [ *CENTER, *BIG ] - label: center/big - -inlineMap: - # Inlined map - << : {"x": 1, "y": 2, "r": 10} - label: center/big - -inlineSequenceMap: - # Inlined map in sequence - << : [ *CENTER, {"r": 10} ] - label: center/big -` - -func (s *S) TestMerge(c *C) { - var want = map[interface{}]interface{}{ - "x": 1, - "y": 2, - "r": 10, - "label": "center/big", - } - - var m map[interface{}]interface{} - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) - } -} - -func (s *S) TestMergeStruct(c *C) { - type Data struct { - X, Y, R int - Label string - } - want := Data{1, 2, 10, "center/big"} - - var m map[string]Data - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, Equals, want, Commentf("test %q failed", name)) - } -} - -var unmarshalNullTests = []func() interface{}{ - func() interface{} { var v interface{}; v = "v"; return &v }, - func() interface{} { var s = "s"; return &s }, - func() interface{} { var s = "s"; sptr := &s; return &sptr }, - func() interface{} { var i = 1; return &i }, - func() interface{} { var i = 1; iptr := &i; return &iptr }, - func() interface{} { m := map[string]int{"s": 1}; return &m }, - func() interface{} { m := map[string]int{"s": 1}; return m }, -} - -func (s *S) TestUnmarshalNull(c *C) { - for _, test := range unmarshalNullTests { - item := test() - zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() - err := yaml.Unmarshal([]byte("null"), item) - c.Assert(err, IsNil) - if reflect.TypeOf(item).Kind() == reflect.Map { - c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) - } else { - c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) - } - } -} - -//var data []byte -//func init() { -// var err error -// data, err = ioutil.ReadFile("/tmp/file.yaml") -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkUnmarshal(c *C) { -// var err error -// for i := 0; i < c.N; i++ { -// var v map[string]interface{} -// err = yaml.Unmarshal(data, &v) -// } -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkMarshal(c *C) { -// var v map[string]interface{} -// yaml.Unmarshal(data, &v) -// c.ResetTimer() -// for i := 0; i < c.N; i++ { -// yaml.Marshal(&v) -// } -//} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go deleted file mode 100644 index cdbf64a9d..000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go +++ /dev/null @@ -1,434 +0,0 @@ -package yaml_test - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" - - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "net" -) - -var marshalIntTest = 123 - -var marshalTests = []struct { - value interface{} - data string -}{ - { - nil, - "null\n", - }, { - &struct{}{}, - "{}\n", - }, { - map[string]string{"v": "hi"}, - "v: hi\n", - }, { - map[string]interface{}{"v": "hi"}, - "v: hi\n", - }, { - map[string]string{"v": "true"}, - "v: \"true\"\n", - }, { - map[string]string{"v": "false"}, - "v: \"false\"\n", - }, { - map[string]interface{}{"v": true}, - "v: true\n", - }, { - map[string]interface{}{"v": false}, - "v: false\n", - }, { - map[string]interface{}{"v": 10}, - "v: 10\n", - }, { - map[string]interface{}{"v": -10}, - "v: -10\n", - }, { - map[string]uint{"v": 42}, - "v: 42\n", - }, { - map[string]interface{}{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]int64{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]uint64{"v": 4294967296}, - "v: 4294967296\n", - }, { - map[string]interface{}{"v": "10"}, - "v: \"10\"\n", - }, { - map[string]interface{}{"v": 0.1}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": float64(0.1)}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": -0.1}, - "v: -0.1\n", - }, { - map[string]interface{}{"v": math.Inf(+1)}, - "v: .inf\n", - }, { - map[string]interface{}{"v": math.Inf(-1)}, - "v: -.inf\n", - }, { - map[string]interface{}{"v": math.NaN()}, - "v: .nan\n", - }, { - map[string]interface{}{"v": nil}, - "v: null\n", - }, { - map[string]interface{}{"v": ""}, - "v: \"\"\n", - }, { - map[string][]string{"v": []string{"A", "B"}}, - "v:\n- A\n- B\n", - }, { - map[string][]string{"v": []string{"A", "B\nC"}}, - "v:\n- A\n- |-\n B\n C\n", - }, { - map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, - "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", - }, { - map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - "a:\n b: c\n", - }, { - map[string]interface{}{"a": "-"}, - "a: '-'\n", - }, - - // Simple values. - { - &marshalIntTest, - "123\n", - }, - - // Structures - { - &struct{ Hello string }{"world"}, - "hello: world\n", - }, { - &struct { - A struct { - B string - } - }{struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{&struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{}, - "a: null\n", - }, { - &struct{ A int }{1}, - "a: 1\n", - }, { - &struct{ A []int }{[]int{1, 2}}, - "a:\n- 1\n- 2\n", - }, { - &struct { - B int "a" - }{1}, - "a: 1\n", - }, { - &struct{ A bool }{true}, - "a: true\n", - }, - - // Conditional flag - { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{1, 0}, - "a: 1\n", - }, { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{0, 0}, - "{}\n", - }, { - &struct { - A *struct{ X int } "a,omitempty" - B int "b,omitempty" - }{nil, 0}, - "{}\n", - }, - - // Flow flag - { - &struct { - A []int "a,flow" - }{[]int{1, 2}}, - "a: [1, 2]\n", - }, { - &struct { - A map[string]string "a,flow" - }{map[string]string{"b": "c", "d": "e"}}, - "a: {b: c, d: e}\n", - }, { - &struct { - A struct { - B, D string - } "a,flow" - }{struct{ B, D string }{"c", "e"}}, - "a: {b: c, d: e}\n", - }, - - // Unexported field - { - &struct { - u int - A int - }{0, 1}, - "a: 1\n", - }, - - // Ignored field - { - &struct { - A int - B int "-" - }{1, 2}, - "a: 1\n", - }, - - // Struct inlining - { - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Duration - { - map[string]time.Duration{"a": 3 * time.Second}, - "a: 3s\n", - }, - - // Issue #24: bug in map merging logic. - { - map[string]string{"a": ""}, - "a: \n", - }, - - // Issue #34: marshal unsupported base 60 floats quoted for compatibility - // with old YAML 1.1 parsers. - { - map[string]string{"a": "1:1"}, - "a: \"1:1\"\n", - }, - - // Binary data. - { - map[string]string{"a": "\x00"}, - "a: \"\\0\"\n", - }, { - map[string]string{"a": "\x80\x81\x82"}, - "a: !!binary gIGC\n", - }, { - map[string]string{"a": strings.Repeat("\x90", 54)}, - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - }, - - // Ordered maps. - { - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", - }, - - // Encode unicode as utf-8 rather than in escaped form. - { - map[string]string{"a": "你好"}, - "a: 你好\n", - }, - - // Support encoding.TextMarshaler. - { - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - "a: 1.2.3.4\n", - }, -} - -func (s *S) TestMarshal(c *C) { - for _, item := range marshalTests { - data, err := yaml.Marshal(item.value) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data) - } -} - -var marshalErrorTests = []struct { - value interface{} - error string - panic string -}{{ - value: &struct { - B int - inlineB ",inline" - }{1, inlineB{2, inlineC{3}}}, - panic: `Duplicated key 'b' in struct struct \{ B int; .*`, -}} - -func (s *S) TestMarshalErrors(c *C) { - for _, item := range marshalErrorTests { - if item.panic != "" { - c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) - } else { - _, err := yaml.Marshal(item.value) - c.Assert(err, ErrorMatches, item.error) - } - } -} - -func (s *S) TestMarshalTypeCache(c *C) { - var data []byte - var err error - func() { - type T struct{ A int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - func() { - type T struct{ B int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - c.Assert(string(data), Equals, "b: 0\n") -} - -var marshalerTests = []struct { - data string - value interface{} -}{ - {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, - {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, - {"_: 10\n", 10}, - {"_: null\n", nil}, - {"_: BAR!\n", "BAR!"}, -} - -type marshalerType struct { - value interface{} -} - -func (o marshalerType) MarshalYAML() (interface{}, error) { - return o.value, nil -} - -type marshalerValue struct { - Field marshalerType "_" -} - -func (s *S) TestMarshaler(c *C) { - for _, item := range marshalerTests { - obj := &marshalerValue{} - obj.Field.value = item.value - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, string(item.data)) - } -} - -func (s *S) TestMarshalerWholeDocument(c *C) { - obj := &marshalerType{} - obj.value = map[string]string{"hello": "world!"} - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, "hello: world!\n") -} - -type failingMarshaler struct{} - -func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { - return nil, failingErr -} - -func (s *S) TestMarshalerError(c *C) { - _, err := yaml.Marshal(&failingMarshaler{}) - c.Assert(err, Equals, failingErr) -} - -func (s *S) TestSortedOutput(c *C) { - order := []interface{}{ - false, - true, - 1, - uint(1), - 1.0, - 1.1, - 1.2, - 2, - uint(2), - 2.0, - 2.1, - "", - ".1", - ".2", - ".a", - "1", - "2", - "a!10", - "a/2", - "a/10", - "a~10", - "ab/1", - "b/1", - "b/01", - "b/2", - "b/02", - "b/3", - "b/03", - "b1", - "b01", - "b3", - "c2.10", - "c10.2", - "d1", - "d12", - "d12a", - } - m := make(map[interface{}]int) - for _, k := range order { - m[k] = 1 - } - data, err := yaml.Marshal(m) - c.Assert(err, IsNil) - out := "\n" + string(data) - last := 0 - for i, k := range order { - repr := fmt.Sprint(k) - if s, ok := k.(string); ok { - if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { - repr = `"` + repr + `"` - } - } - index := strings.Index(out, "\n"+repr+":") - if index == -1 { - c.Fatalf("%#v is not in the output: %#v", k, out) - } - if index < last { - c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) - } - last = index - } -} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go deleted file mode 100644 index c5cf1ed4f..000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package yaml_test - -import ( - . "gopkg.in/check.v1" - "testing" -) - -func Test(t *testing.T) { TestingT(t) } - -type S struct{} - -var _ = Suite(&S{}) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/LICENSE b/Godeps/_workspace/src/k8s.io/kubernetes/LICENSE new file mode 100644 index 000000000..6b4d837a4 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/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 2014 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. diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/OWNERS b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/OWNERS new file mode 100644 index 000000000..d28472e0f --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/OWNERS @@ -0,0 +1,6 @@ +assignees: + - bgrant0607 + - erictune + - lavalamp + - smarterclayton + - thockin diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/context_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/context_test.go deleted file mode 100644 index c384999ff..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/context_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package api_test - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -// TestNamespaceContext validates that a namespace can be get/set on a context object -func TestNamespaceContext(t *testing.T) { - ctx := api.NewDefaultContext() - result, ok := api.NamespaceFrom(ctx) - if !ok { - t.Errorf("Error getting namespace") - } - if api.NamespaceDefault != result { - t.Errorf("Expected: %v, Actual: %v", api.NamespaceDefault, result) - } - - ctx = api.NewContext() - result, ok = api.NamespaceFrom(ctx) - if ok { - t.Errorf("Should not be ok because there is no namespace on the context") - } -} - -// TestValidNamespace validates that namespace rules are enforced on a resource prior to create or update -func TestValidNamespace(t *testing.T) { - ctx := api.NewDefaultContext() - namespace, _ := api.NamespaceFrom(ctx) - resource := api.ReplicationController{} - if !api.ValidNamespace(ctx, &resource.ObjectMeta) { - t.Errorf("expected success") - } - if namespace != resource.Namespace { - t.Errorf("expected resource to have the default namespace assigned during validation") - } - resource = api.ReplicationController{ObjectMeta: api.ObjectMeta{Namespace: "other"}} - if api.ValidNamespace(ctx, &resource.ObjectMeta) { - t.Errorf("Expected error that resource and context errors do not match because resource has different namespace") - } - ctx = api.NewContext() - if api.ValidNamespace(ctx, &resource.ObjectMeta) { - t.Errorf("Expected error that resource and context errors do not match since context has no namespace") - } - - ctx = api.NewContext() - ns := api.NamespaceValue(ctx) - if ns != "" { - t.Errorf("Expected the empty string") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/conversion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/conversion.go index 5599db346..e0605fa09 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/conversion.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/conversion.go @@ -41,6 +41,7 @@ func init() { Convert_unversioned_ListMeta_To_unversioned_ListMeta, Convert_intstr_IntOrString_To_intstr_IntOrString, Convert_unversioned_Time_To_unversioned_Time, + Convert_string_slice_To_unversioned_Time, Convert_string_To_labels_Selector, Convert_string_To_fields_Selector, Convert_bool_ref_To_bool, @@ -116,6 +117,16 @@ func Convert_unversioned_Time_To_unversioned_Time(in *unversioned.Time, out *unv *out = *in return nil } + +// Convert_string_slice_To_unversioned_Time allows converting a URL query parameter value +func Convert_string_slice_To_unversioned_Time(input *[]string, out *unversioned.Time, s conversion.Scope) error { + str := "" + if len(*input) > 0 { + str = (*input)[0] + } + return out.UnmarshalQueryParameter(str) +} + func Convert_string_To_labels_Selector(in *string, out *labels.Selector, s conversion.Scope) error { selector, err := labels.Parse(*in) if err != nil { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/conversion_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/conversion_test.go deleted file mode 100644 index 827022270..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/conversion_test.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package api_test - -import ( - "io/ioutil" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/runtime" -) - -func BenchmarkPodConversion(b *testing.B) { - data, err := ioutil.ReadFile("pod_example.json") - if err != nil { - b.Fatalf("Unexpected error while reading file: %v", err) - } - var pod api.Pod - if err := runtime.DecodeInto(testapi.Default.Codec(), data, &pod); err != nil { - b.Fatalf("Unexpected error decoding pod: %v", err) - } - - scheme := api.Scheme - var result *api.Pod - for i := 0; i < b.N; i++ { - versionedObj, err := scheme.ConvertToVersion(&pod, testapi.Default.GroupVersion().String()) - if err != nil { - b.Fatalf("Conversion error: %v", err) - } - obj, err := scheme.ConvertToVersion(versionedObj, testapi.Default.InternalGroupVersion().String()) - if err != nil { - b.Fatalf("Conversion error: %v", err) - } - result = obj.(*api.Pod) - } - if !api.Semantic.DeepDerivative(pod, *result) { - b.Fatalf("Incorrect conversion: expected %v, got %v", pod, *result) - } -} - -func BenchmarkNodeConversion(b *testing.B) { - data, err := ioutil.ReadFile("node_example.json") - if err != nil { - b.Fatalf("Unexpected error while reading file: %v", err) - } - var node api.Node - if err := runtime.DecodeInto(testapi.Default.Codec(), data, &node); err != nil { - b.Fatalf("Unexpected error decoding node: %v", err) - } - - scheme := api.Scheme - var result *api.Node - for i := 0; i < b.N; i++ { - versionedObj, err := scheme.ConvertToVersion(&node, testapi.Default.GroupVersion().String()) - if err != nil { - b.Fatalf("Conversion error: %v", err) - } - obj, err := scheme.ConvertToVersion(versionedObj, testapi.Default.InternalGroupVersion().String()) - if err != nil { - b.Fatalf("Conversion error: %v", err) - } - result = obj.(*api.Node) - } - if !api.Semantic.DeepDerivative(node, *result) { - b.Fatalf("Incorrect conversion: expected %v, got %v", node, *result) - } -} - -func BenchmarkReplicationControllerConversion(b *testing.B) { - data, err := ioutil.ReadFile("replication_controller_example.json") - if err != nil { - b.Fatalf("Unexpected error while reading file: %v", err) - } - var replicationController api.ReplicationController - if err := runtime.DecodeInto(testapi.Default.Codec(), data, &replicationController); err != nil { - b.Fatalf("Unexpected error decoding node: %v", err) - } - - scheme := api.Scheme - var result *api.ReplicationController - for i := 0; i < b.N; i++ { - versionedObj, err := scheme.ConvertToVersion(&replicationController, testapi.Default.GroupVersion().String()) - if err != nil { - b.Fatalf("Conversion error: %v", err) - } - obj, err := scheme.ConvertToVersion(versionedObj, testapi.Default.InternalGroupVersion().String()) - if err != nil { - b.Fatalf("Conversion error: %v", err) - } - result = obj.(*api.ReplicationController) - } - if !api.Semantic.DeepDerivative(replicationController, *result) { - b.Fatalf("Incorrect conversion: expected %v, got %v", replicationController, *result) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/copy_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/copy_test.go deleted file mode 100644 index 194b5318a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/copy_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package api_test - -import ( - "math/rand" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/util" - - "github.com/google/gofuzz" -) - -func TestDeepCopyApiObjects(t *testing.T) { - for i := 0; i < *fuzzIters; i++ { - for _, version := range []unversioned.GroupVersion{testapi.Default.InternalGroupVersion(), *testapi.Default.GroupVersion()} { - f := apitesting.FuzzerFor(t, version, rand.NewSource(rand.Int63())) - for kind := range api.Scheme.KnownTypes(version) { - doDeepCopyTest(t, version.WithKind(kind), f) - } - } - } -} - -func doDeepCopyTest(t *testing.T, kind unversioned.GroupVersionKind, f *fuzz.Fuzzer) { - item, err := api.Scheme.New(kind) - if err != nil { - t.Fatalf("Could not create a %v: %s", kind, err) - } - f.Fuzz(item) - itemCopy, err := api.Scheme.DeepCopy(item) - if err != nil { - t.Errorf("Could not deep copy a %v: %s", kind, err) - return - } - - if !reflect.DeepEqual(item, itemCopy) { - t.Errorf("\nexpected: %#v\n\ngot: %#v\n\ndiff: %v", item, itemCopy, util.ObjectGoPrintSideBySide(item, itemCopy)) - } -} - -func TestDeepCopySingleType(t *testing.T) { - for i := 0; i < *fuzzIters; i++ { - for _, version := range []unversioned.GroupVersion{testapi.Default.InternalGroupVersion(), *testapi.Default.GroupVersion()} { - f := apitesting.FuzzerFor(t, version, rand.NewSource(rand.Int63())) - doDeepCopyTest(t, version.WithKind("Pod"), f) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_generated.go index ab938aac5..aa2712e10 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_generated.go @@ -2400,6 +2400,7 @@ func DeepCopy_api_ReplicationControllerSpec(in ReplicationControllerSpec, out *R 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 } @@ -2455,6 +2456,15 @@ func DeepCopy_api_ResourceQuotaSpec(in ResourceQuotaSpec, out *ResourceQuotaSpec } 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 } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_test.go deleted file mode 100644 index a251623a0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_test.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package api_test - -import ( - "io/ioutil" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/runtime" -) - -func BenchmarkPodCopy(b *testing.B) { - data, err := ioutil.ReadFile("pod_example.json") - if err != nil { - b.Fatalf("Unexpected error while reading file: %v", err) - } - var pod api.Pod - if err := runtime.DecodeInto(testapi.Default.Codec(), data, &pod); err != nil { - b.Fatalf("Unexpected error decoding pod: %v", err) - } - - var result *api.Pod - for i := 0; i < b.N; i++ { - obj, err := api.Scheme.DeepCopy(&pod) - if err != nil { - b.Fatalf("Unexpected error copying pod: %v", err) - } - result = obj.(*api.Pod) - } - if !api.Semantic.DeepEqual(pod, *result) { - b.Fatalf("Incorrect copy: expected %v, got %v", pod, *result) - } -} - -func BenchmarkNodeCopy(b *testing.B) { - data, err := ioutil.ReadFile("node_example.json") - if err != nil { - b.Fatalf("Unexpected error while reading file: %v", err) - } - var node api.Node - if err := runtime.DecodeInto(testapi.Default.Codec(), data, &node); err != nil { - b.Fatalf("Unexpected error decoding node: %v", err) - } - - var result *api.Node - for i := 0; i < b.N; i++ { - obj, err := api.Scheme.DeepCopy(&node) - if err != nil { - b.Fatalf("Unexpected error copying node: %v", err) - } - result = obj.(*api.Node) - } - if !api.Semantic.DeepEqual(node, *result) { - b.Fatalf("Incorrect copy: expected %v, got %v", node, *result) - } -} - -func BenchmarkReplicationControllerCopy(b *testing.B) { - data, err := ioutil.ReadFile("replication_controller_example.json") - if err != nil { - b.Fatalf("Unexpected error while reading file: %v", err) - } - var replicationController api.ReplicationController - if err := runtime.DecodeInto(testapi.Default.Codec(), data, &replicationController); err != nil { - b.Fatalf("Unexpected error decoding node: %v", err) - } - - var result *api.ReplicationController - for i := 0; i < b.N; i++ { - obj, err := api.Scheme.DeepCopy(&replicationController) - if err != nil { - b.Fatalf("Unexpected error copying replication controller: %v", err) - } - result = obj.(*api.ReplicationController) - } - if !api.Semantic.DeepEqual(replicationController, *result) { - b.Fatalf("Incorrect copy: expected %v, got %v", replicationController, *result) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/endpoints/util.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/endpoints/util.go index 91bc57166..7758434a1 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/endpoints/util.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/endpoints/util.go @@ -28,6 +28,16 @@ import ( hashutil "k8s.io/kubernetes/pkg/util/hash" ) +const ( + // Its value is the json representation of map[string(IP)][HostRecord] + // example: '{"10.245.1.6":{"HostName":"my-webserver"}}' + PodHostnamesAnnotation = "endpoints.beta.kubernetes.io/hostnames-map" +) + +type HostRecord struct { + HostName string +} + // RepackSubsets takes a slice of EndpointSubset objects, expands it to the full // representation, and then repacks that into the canonical layout. This // ensures that code which operates on these objects can rely on the common diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/endpoints/util_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/endpoints/util_test.go deleted file mode 100644 index a2f960317..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/endpoints/util_test.go +++ /dev/null @@ -1,444 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package endpoints - -import ( - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/types" -) - -func podRef(uid string) *api.ObjectReference { - ref := api.ObjectReference{UID: types.UID(uid)} - return &ref -} - -func TestPackSubsets(t *testing.T) { - // The downside of table-driven tests is that some things have to live outside the table. - fooObjRef := api.ObjectReference{Name: "foo"} - barObjRef := api.ObjectReference{Name: "bar"} - - testCases := []struct { - name string - given []api.EndpointSubset - expect []api.EndpointSubset - }{ - { - name: "empty everything", - given: []api.EndpointSubset{{Addresses: []api.EndpointAddress{}, Ports: []api.EndpointPort{}}}, - expect: []api.EndpointSubset{}, - }, { - name: "empty addresses", - given: []api.EndpointSubset{{Addresses: []api.EndpointAddress{}, Ports: []api.EndpointPort{{Port: 111}}}}, - expect: []api.EndpointSubset{}, - }, { - name: "empty ports", - given: []api.EndpointSubset{{Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, Ports: []api.EndpointPort{}}}, - expect: []api.EndpointSubset{}, - }, { - name: "empty ports", - given: []api.EndpointSubset{{NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, Ports: []api.EndpointPort{}}}, - expect: []api.EndpointSubset{}, - }, { - name: "one set, one ip, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, one notReady ip, one port", - given: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, one ip, one UID, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, one notReady ip, one UID, one port", - given: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, one ip, empty UID, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, one notReady ip, empty UID, one port", - given: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, two ips, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}, {IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}, {IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, two mixed ips, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - NotReadyAddresses: []api.EndpointAddress{{IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - NotReadyAddresses: []api.EndpointAddress{{IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, two duplicate ips, one port, notReady is covered by ready", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, one ip, two ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}, {Port: 222}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}, {Port: 222}}, - }}, - }, { - name: "one set, dup ips, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}, {IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, dup ips with target-refs, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4", TargetRef: &fooObjRef}, - {IP: "1.2.3.4", TargetRef: &barObjRef}, - }, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: &fooObjRef}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, dup mixed ips with target-refs, one port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4", TargetRef: &fooObjRef}, - }, - NotReadyAddresses: []api.EndpointAddress{ - {IP: "1.2.3.4", TargetRef: &barObjRef}, - }, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - // finding the same address twice is considered an error on input, only the first address+port - // reference is preserved - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: &fooObjRef}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "one set, one ip, dup ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}, {Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two sets, dup ip, dup port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two sets, dup mixed ip, dup port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two sets, dup ip, two ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 222}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}, {Port: 222}}, - }}, - }, { - name: "two sets, dup ip, dup uids, two ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 222}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}, {Port: 222}}, - }}, - }, { - name: "two sets, dup mixed ip, dup uids, two ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 222}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 222}}, - }}, - }, { - name: "two sets, two ips, dup port", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}, {IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two set, dup ip, two uids, dup ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-2")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4", TargetRef: podRef("uid-1")}, - {IP: "1.2.3.4", TargetRef: podRef("uid-2")}, - }, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two set, dup ip, with and without uid, dup ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-2")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4"}, - {IP: "1.2.3.4", TargetRef: podRef("uid-2")}, - }, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two sets, two ips, two dup ip with uid, dup port, wrong order", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "5.6.7.8", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4"}, - {IP: "1.2.3.4", TargetRef: podRef("uid-1")}, - {IP: "5.6.7.8"}, - {IP: "5.6.7.8", TargetRef: podRef("uid-1")}, - }, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two sets, two mixed ips, two dup ip with uid, dup port, wrong order, ends up with split addresses", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "5.6.7.8", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4", TargetRef: podRef("uid-1")}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "5.6.7.8"}, - }, - NotReadyAddresses: []api.EndpointAddress{ - {IP: "1.2.3.4"}, - {IP: "1.2.3.4", TargetRef: podRef("uid-1")}, - {IP: "5.6.7.8", TargetRef: podRef("uid-1")}, - }, - Ports: []api.EndpointPort{{Port: 111}}, - }}, - }, { - name: "two sets, two ips, two ports", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 222}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "5.6.7.8"}}, - Ports: []api.EndpointPort{{Port: 222}}, - }}, - }, { - name: "four sets, three ips, three ports, jumbled", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.5"}}, - Ports: []api.EndpointPort{{Port: 222}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.6"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.5"}}, - Ports: []api.EndpointPort{{Port: 333}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}, {IP: "1.2.3.6"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.5"}}, - Ports: []api.EndpointPort{{Port: 222}, {Port: 333}}, - }}, - }, { - name: "four sets, three mixed ips, three ports, jumbled", - given: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.5"}}, - Ports: []api.EndpointPort{{Port: 222}}, - }, { - Addresses: []api.EndpointAddress{{IP: "1.2.3.6"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.5"}}, - Ports: []api.EndpointPort{{Port: 333}}, - }}, - expect: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}, {IP: "1.2.3.6"}}, - Ports: []api.EndpointPort{{Port: 111}}, - }, { - NotReadyAddresses: []api.EndpointAddress{{IP: "1.2.3.5"}}, - Ports: []api.EndpointPort{{Port: 222}, {Port: 333}}, - }}, - }, - } - - for _, tc := range testCases { - result := RepackSubsets(tc.given) - if !reflect.DeepEqual(result, SortSubsets(tc.expect)) { - t.Errorf("case %q: expected %s, got %s", tc.name, spew.Sprintf("%#v", SortSubsets(tc.expect)), spew.Sprintf("%#v", result)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/errors_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/errors_test.go deleted file mode 100644 index 066bb25f2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/errors_test.go +++ /dev/null @@ -1,189 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package errors - -import ( - "errors" - "fmt" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -func TestErrorNew(t *testing.T) { - err := NewAlreadyExists(api.Resource("tests"), "1") - if !IsAlreadyExists(err) { - t.Errorf("expected to be %s", unversioned.StatusReasonAlreadyExists) - } - if IsConflict(err) { - t.Errorf("expected to not be %s", unversioned.StatusReasonConflict) - } - if IsNotFound(err) { - t.Errorf(fmt.Sprintf("expected to not be %s", unversioned.StatusReasonNotFound)) - } - if IsInvalid(err) { - t.Errorf("expected to not be %s", unversioned.StatusReasonInvalid) - } - if IsBadRequest(err) { - t.Errorf("expected to not be %s", unversioned.StatusReasonBadRequest) - } - if IsForbidden(err) { - t.Errorf("expected to not be %s", unversioned.StatusReasonForbidden) - } - if IsServerTimeout(err) { - t.Errorf("expected to not be %s", unversioned.StatusReasonServerTimeout) - } - if IsMethodNotSupported(err) { - t.Errorf("expected to not be %s", unversioned.StatusReasonMethodNotAllowed) - } - - if !IsConflict(NewConflict(api.Resource("tests"), "2", errors.New("message"))) { - t.Errorf("expected to be conflict") - } - if !IsNotFound(NewNotFound(api.Resource("tests"), "3")) { - t.Errorf("expected to be %s", unversioned.StatusReasonNotFound) - } - if !IsInvalid(NewInvalid(api.Kind("Test"), "2", nil)) { - t.Errorf("expected to be %s", unversioned.StatusReasonInvalid) - } - if !IsBadRequest(NewBadRequest("reason")) { - t.Errorf("expected to be %s", unversioned.StatusReasonBadRequest) - } - if !IsForbidden(NewForbidden(api.Resource("tests"), "2", errors.New("reason"))) { - t.Errorf("expected to be %s", unversioned.StatusReasonForbidden) - } - if !IsUnauthorized(NewUnauthorized("reason")) { - t.Errorf("expected to be %s", unversioned.StatusReasonUnauthorized) - } - if !IsServerTimeout(NewServerTimeout(api.Resource("tests"), "reason", 0)) { - t.Errorf("expected to be %s", unversioned.StatusReasonServerTimeout) - } - if time, ok := SuggestsClientDelay(NewServerTimeout(api.Resource("tests"), "doing something", 10)); time != 10 || !ok { - t.Errorf("expected to be %s", unversioned.StatusReasonServerTimeout) - } - if time, ok := SuggestsClientDelay(NewTimeoutError("test reason", 10)); time != 10 || !ok { - t.Errorf("expected to be %s", unversioned.StatusReasonTimeout) - } - if !IsMethodNotSupported(NewMethodNotSupported(api.Resource("foos"), "delete")) { - t.Errorf("expected to be %s", unversioned.StatusReasonMethodNotAllowed) - } -} - -func TestNewInvalid(t *testing.T) { - testCases := []struct { - Err *field.Error - Details *unversioned.StatusDetails - }{ - { - field.Duplicate(field.NewPath("field[0].name"), "bar"), - &unversioned.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []unversioned.StatusCause{{ - Type: unversioned.CauseTypeFieldValueDuplicate, - Field: "field[0].name", - }}, - }, - }, - { - field.Invalid(field.NewPath("field[0].name"), "bar", "detail"), - &unversioned.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []unversioned.StatusCause{{ - Type: unversioned.CauseTypeFieldValueInvalid, - Field: "field[0].name", - }}, - }, - }, - { - field.NotFound(field.NewPath("field[0].name"), "bar"), - &unversioned.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []unversioned.StatusCause{{ - Type: unversioned.CauseTypeFieldValueNotFound, - Field: "field[0].name", - }}, - }, - }, - { - field.NotSupported(field.NewPath("field[0].name"), "bar", nil), - &unversioned.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []unversioned.StatusCause{{ - Type: unversioned.CauseTypeFieldValueNotSupported, - Field: "field[0].name", - }}, - }, - }, - { - field.Required(field.NewPath("field[0].name"), ""), - &unversioned.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []unversioned.StatusCause{{ - Type: unversioned.CauseTypeFieldValueRequired, - Field: "field[0].name", - }}, - }, - }, - } - for i, testCase := range testCases { - vErr, expected := testCase.Err, testCase.Details - expected.Causes[0].Message = vErr.ErrorBody() - err := NewInvalid(api.Kind("Kind"), "name", field.ErrorList{vErr}) - status := err.(*StatusError).ErrStatus - if status.Code != 422 || status.Reason != unversioned.StatusReasonInvalid { - t.Errorf("%d: unexpected status: %#v", i, status) - } - if !reflect.DeepEqual(expected, status.Details) { - t.Errorf("%d: expected %#v, got %#v", i, expected, status.Details) - } - } -} - -func Test_reasonForError(t *testing.T) { - if e, a := unversioned.StatusReasonUnknown, reasonForError(nil); e != a { - t.Errorf("unexpected reason type: %#v", a) - } -} - -type TestType struct{} - -func (obj *TestType) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -func TestFromObject(t *testing.T) { - table := []struct { - obj runtime.Object - message string - }{ - {&unversioned.Status{Message: "foobar"}, "foobar"}, - {&TestType{}, "unexpected object: &{}"}, - } - - for _, item := range table { - if e, a := item.message, FromObject(item.obj).Error(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/etcd/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/etcd/doc.go deleted file mode 100644 index 8cc0a832e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/etcd/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package etcd provides conversion of etcd errors to API errors. -package etcd diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/etcd/etcd.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/etcd/etcd.go deleted file mode 100644 index 3e09aebaa..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/errors/etcd/etcd.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package etcd - -import ( - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/storage" -) - -// InterpretListError converts a generic error on a retrieval -// operation into the appropriate API error. -func InterpretListError(err error, qualifiedResource unversioned.GroupResource) error { - switch { - case storage.IsNotFound(err): - return errors.NewNotFound(qualifiedResource, "") - case storage.IsUnreachable(err): - return errors.NewServerTimeout(qualifiedResource, "list", 2) // TODO: make configurable or handled at a higher level - default: - return err - } -} - -// InterpretGetError converts a generic error on a retrieval -// operation into the appropriate API error. -func InterpretGetError(err error, qualifiedResource unversioned.GroupResource, name string) error { - switch { - case storage.IsNotFound(err): - return errors.NewNotFound(qualifiedResource, name) - case storage.IsUnreachable(err): - return errors.NewServerTimeout(qualifiedResource, "get", 2) // TODO: make configurable or handled at a higher level - default: - return err - } -} - -// InterpretCreateError converts a generic error on a create -// operation into the appropriate API error. -func InterpretCreateError(err error, qualifiedResource unversioned.GroupResource, name string) error { - switch { - case storage.IsNodeExist(err): - return errors.NewAlreadyExists(qualifiedResource, name) - case storage.IsUnreachable(err): - return errors.NewServerTimeout(qualifiedResource, "create", 2) // TODO: make configurable or handled at a higher level - default: - return err - } -} - -// InterpretUpdateError converts a generic error on a update -// operation into the appropriate API error. -func InterpretUpdateError(err error, qualifiedResource unversioned.GroupResource, name string) error { - switch { - case storage.IsTestFailed(err), storage.IsNodeExist(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 - default: - return err - } -} - -// InterpretDeleteError converts a generic error on a delete -// operation into the appropriate API error. -func InterpretDeleteError(err error, qualifiedResource unversioned.GroupResource, name string) error { - switch { - case storage.IsNotFound(err): - return errors.NewNotFound(qualifiedResource, name) - case storage.IsUnreachable(err): - return errors.NewServerTimeout(qualifiedResource, "delete", 2) // TODO: make configurable or handled at a higher level - default: - return err - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/field_constants.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/field_constants.go new file mode 100644 index 000000000..94a825caf --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/field_constants.go @@ -0,0 +1,38 @@ +/* +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. +*/ + +package api + +// Field path constants that are specific to the internal API +// representation. +const ( + NodeUnschedulableField = "spec.unschedulable" + ObjectNameField = "metadata.name" + PodHostField = "spec.nodeName" + PodStatusField = "status.phase" + SecretTypeField = "type" + + EventReasonField = "reason" + EventSourceField = "source" + EventTypeField = "type" + EventInvolvedKindField = "involvedObject.kind" + EventInvolvedNamespaceField = "involvedObject.namespace" + EventInvolvedNameField = "involvedObject.name" + EventInvolvedUIDField = "involvedObject.uid" + EventInvolvedAPIVersionField = "involvedObject.apiVersion" + EventInvolvedResourceVersionField = "involvedObject.resourceVersion" + EventInvolvedFieldPathField = "involvedObject.fieldPath" +) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/generate_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/generate_test.go deleted file mode 100644 index fe3cf812b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/generate_test.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package api - -import ( - "strings" - "testing" -) - -type nameGeneratorFunc func(base string) string - -func (fn nameGeneratorFunc) GenerateName(base string) string { - return fn(base) -} - -func TestGenerateName(t *testing.T) { - testCases := []struct { - meta ObjectMeta - - base string - returned string - }{ - { - returned: "", - }, - { - meta: ObjectMeta{ - GenerateName: "test", - }, - base: "test", - returned: "test", - }, - { - meta: ObjectMeta{ - Name: "foo", - GenerateName: "test", - }, - base: "test", - returned: "foo", - }, - } - - for i, testCase := range testCases { - GenerateName(nameGeneratorFunc(func(base string) string { - if base != testCase.base { - t.Errorf("%d: unexpected call with base", i) - } - return "test" - }), &testCase.meta) - expect := testCase.returned - if expect != testCase.meta.Name { - t.Errorf("%d: unexpected name: %#v", i, testCase.meta) - } - } -} - -func TestSimpleNameGenerator(t *testing.T) { - meta := &ObjectMeta{ - GenerateName: "foo", - } - GenerateName(SimpleNameGenerator, meta) - if !strings.HasPrefix(meta.Name, "foo") || meta.Name == "foo" { - t.Errorf("unexpected name: %#v", meta) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/helpers.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/helpers.go index b373b9eee..aed3c5a7a 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/helpers.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/helpers.go @@ -79,15 +79,100 @@ var Semantic = conversion.EqualitiesOrDie( }, ) -var standardResources = sets.NewString( +var standardResourceQuotaScopes = sets.NewString( + string(ResourceQuotaScopeTerminating), + string(ResourceQuotaScopeNotTerminating), + string(ResourceQuotaScopeBestEffort), + string(ResourceQuotaScopeNotBestEffort), +) + +// IsStandardResourceQuotaScope returns true if the scope is a standard value +func IsStandardResourceQuotaScope(str string) bool { + return standardResourceQuotaScopes.Has(str) +} + +var podObjectCountQuotaResources = sets.NewString( + string(ResourcePods), +) + +var podComputeQuotaResources = sets.NewString( string(ResourceCPU), string(ResourceMemory), + string(ResourceLimitsCPU), + string(ResourceLimitsMemory), + string(ResourceRequestsCPU), + string(ResourceRequestsMemory), +) + +// IsResourceQuotaScopeValidForResource returns true if the resource applies to the specified scope +func IsResourceQuotaScopeValidForResource(scope ResourceQuotaScope, resource string) bool { + switch scope { + case ResourceQuotaScopeTerminating, ResourceQuotaScopeNotTerminating, ResourceQuotaScopeNotBestEffort: + return podObjectCountQuotaResources.Has(resource) || podComputeQuotaResources.Has(resource) + case ResourceQuotaScopeBestEffort: + return podObjectCountQuotaResources.Has(resource) + default: + return true + } +} + +var standardContainerResources = sets.NewString( + string(ResourceCPU), + string(ResourceMemory), +) + +// IsStandardContainerResourceName returns true if the container can make a resource request +// for the specified resource +func IsStandardContainerResourceName(str string) bool { + return standardContainerResources.Has(str) +} + +var standardLimitRangeTypes = sets.NewString( + string(LimitTypePod), + string(LimitTypeContainer), +) + +// IsStandardLimitRangeType returns true if the type is Pod or Container +func IsStandardLimitRangeType(str string) bool { + return standardLimitRangeTypes.Has(str) +} + +var standardQuotaResources = sets.NewString( + string(ResourceCPU), + string(ResourceMemory), + string(ResourceRequestsCPU), + string(ResourceRequestsMemory), + string(ResourceLimitsCPU), + string(ResourceLimitsMemory), string(ResourcePods), string(ResourceQuotas), string(ResourceServices), string(ResourceReplicationControllers), string(ResourceSecrets), string(ResourcePersistentVolumeClaims), + string(ResourceConfigMaps), +) + +// IsStandardQuotaResourceName returns true if the resource is known to +// the quota tracking system +func IsStandardQuotaResourceName(str string) bool { + return standardQuotaResources.Has(str) +} + +var standardResources = sets.NewString( + string(ResourceCPU), + string(ResourceMemory), + string(ResourceRequestsCPU), + string(ResourceRequestsMemory), + string(ResourceLimitsCPU), + string(ResourceLimitsMemory), + string(ResourcePods), + string(ResourceQuotas), + string(ResourceServices), + string(ResourceReplicationControllers), + string(ResourceSecrets), + string(ResourceConfigMaps), + string(ResourcePersistentVolumeClaims), string(ResourceStorage), ) @@ -102,6 +187,7 @@ var integerResources = sets.NewString( string(ResourceServices), string(ResourceReplicationControllers), string(ResourceSecrets), + string(ResourceConfigMaps), string(ResourcePersistentVolumeClaims), ) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/helpers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/helpers_test.go deleted file mode 100644 index 2d6bd488f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/helpers_test.go +++ /dev/null @@ -1,299 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package api - -import ( - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/labels" - - "speter.net/go/exp/math/dec/inf" -) - -func TestConversionError(t *testing.T) { - var i int - var s string - i = 3 - s = "foo" - c := ConversionError{ - In: &i, Out: &s, - Message: "Can't make x into y, silly", - } - var e error - e = &c // ensure it implements error - msg := e.Error() - t.Logf("Message is %v", msg) - for _, part := range []string{"3", "int", "string", "Can't"} { - if !strings.Contains(msg, part) { - t.Errorf("didn't find %v", part) - } - } -} - -func TestSemantic(t *testing.T) { - table := []struct { - a, b interface{} - shouldEqual bool - }{ - {resource.MustParse("0"), resource.Quantity{}, true}, - {resource.Quantity{}, resource.MustParse("0"), true}, - {resource.Quantity{}, resource.MustParse("1m"), false}, - { - resource.Quantity{Amount: inf.NewDec(5, 0), Format: resource.BinarySI}, - resource.Quantity{Amount: inf.NewDec(5, 0), Format: resource.DecimalSI}, - true, - }, - {resource.MustParse("2m"), resource.MustParse("1m"), false}, - } - - for index, item := range table { - if e, a := item.shouldEqual, Semantic.DeepEqual(item.a, item.b); e != a { - t.Errorf("case[%d], expected %v, got %v.", index, e, a) - } - } -} - -func TestIsStandardResource(t *testing.T) { - testCases := []struct { - input string - output bool - }{ - {"cpu", true}, - {"memory", true}, - {"disk", false}, - {"blah", false}, - {"x.y.z", false}, - } - for i, tc := range testCases { - if IsStandardResourceName(tc.input) != tc.output { - t.Errorf("case[%d], expected: %t, got: %t", i, tc.output, !tc.output) - } - } -} - -func TestAddToNodeAddresses(t *testing.T) { - testCases := []struct { - existing []NodeAddress - toAdd []NodeAddress - expected []NodeAddress - }{ - { - existing: []NodeAddress{}, - toAdd: []NodeAddress{}, - expected: []NodeAddress{}, - }, - { - existing: []NodeAddress{}, - toAdd: []NodeAddress{ - {Type: NodeExternalIP, Address: "1.1.1.1"}, - {Type: NodeHostName, Address: "localhost"}, - }, - expected: []NodeAddress{ - {Type: NodeExternalIP, Address: "1.1.1.1"}, - {Type: NodeHostName, Address: "localhost"}, - }, - }, - { - existing: []NodeAddress{}, - toAdd: []NodeAddress{ - {Type: NodeExternalIP, Address: "1.1.1.1"}, - {Type: NodeExternalIP, Address: "1.1.1.1"}, - }, - expected: []NodeAddress{ - {Type: NodeExternalIP, Address: "1.1.1.1"}, - }, - }, - { - existing: []NodeAddress{ - {Type: NodeExternalIP, Address: "1.1.1.1"}, - {Type: NodeInternalIP, Address: "10.1.1.1"}, - }, - toAdd: []NodeAddress{ - {Type: NodeExternalIP, Address: "1.1.1.1"}, - {Type: NodeHostName, Address: "localhost"}, - }, - expected: []NodeAddress{ - {Type: NodeExternalIP, Address: "1.1.1.1"}, - {Type: NodeInternalIP, Address: "10.1.1.1"}, - {Type: NodeHostName, Address: "localhost"}, - }, - }, - } - - for i, tc := range testCases { - AddToNodeAddresses(&tc.existing, tc.toAdd...) - if !Semantic.DeepEqual(tc.expected, tc.existing) { - t.Errorf("case[%d], expected: %v, got: %v", i, tc.expected, tc.existing) - } - } -} - -func TestGetAccessModesFromString(t *testing.T) { - modes := GetAccessModesFromString("ROX") - if !containsAccessMode(modes, ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", ReadOnlyMany, modes) - } - - modes = GetAccessModesFromString("ROX,RWX") - if !containsAccessMode(modes, ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", ReadOnlyMany, modes) - } - if !containsAccessMode(modes, ReadWriteMany) { - t.Errorf("Expected mode %s, but got %+v", ReadWriteMany, modes) - } - - modes = GetAccessModesFromString("RWO,ROX,RWX") - if !containsAccessMode(modes, ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", ReadOnlyMany, modes) - } - if !containsAccessMode(modes, ReadWriteMany) { - t.Errorf("Expected mode %s, but got %+v", ReadWriteMany, modes) - } -} - -func TestRemoveDuplicateAccessModes(t *testing.T) { - modes := []PersistentVolumeAccessMode{ - ReadWriteOnce, ReadOnlyMany, ReadOnlyMany, ReadOnlyMany, - } - modes = removeDuplicateAccessModes(modes) - if len(modes) != 2 { - t.Errorf("Expected 2 distinct modes in set but found %v", len(modes)) - } -} - -func TestNodeSelectorRequirementsAsSelector(t *testing.T) { - matchExpressions := []NodeSelectorRequirement{{ - Key: "foo", - Operator: NodeSelectorOpIn, - Values: []string{"bar", "baz"}, - }} - mustParse := func(s string) labels.Selector { - out, e := labels.Parse(s) - if e != nil { - panic(e) - } - return out - } - tc := []struct { - in []NodeSelectorRequirement - out labels.Selector - expectErr bool - }{ - {in: nil, out: labels.Nothing()}, - {in: []NodeSelectorRequirement{}, out: labels.Nothing()}, - { - in: matchExpressions, - out: mustParse("foo in (baz,bar)"), - }, - { - in: []NodeSelectorRequirement{{ - Key: "foo", - Operator: NodeSelectorOpExists, - Values: []string{"bar", "baz"}, - }}, - expectErr: true, - }, - { - in: []NodeSelectorRequirement{{ - Key: "foo", - Operator: NodeSelectorOpGt, - Values: []string{"1.1"}, - }}, - out: mustParse("foo>1.1"), - }, - { - in: []NodeSelectorRequirement{{ - Key: "bar", - Operator: NodeSelectorOpLt, - Values: []string{"7.1"}, - }}, - out: mustParse("bar<7.1"), - }, - } - - for i, tc := range tc { - out, err := NodeSelectorRequirementsAsSelector(tc.in) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - if !reflect.DeepEqual(out, tc.out) { - t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out) - } - } -} - -func TestGetAffinityFromPod(t *testing.T) { - testCases := []struct { - pod *Pod - expectErr bool - }{ - { - pod: &Pod{}, - expectErr: false, - }, - { - pod: &Pod{ - ObjectMeta: ObjectMeta{ - Annotations: map[string]string{ - AffinityAnnotationKey: ` - {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [{ - "matchExpressions": [{ - "key": "foo", - "operator": "In", - "values": ["value1", "value2"] - }] - }] - }}}`, - }, - }, - }, - expectErr: false, - }, - { - pod: &Pod{ - ObjectMeta: ObjectMeta{ - Annotations: map[string]string{ - AffinityAnnotationKey: ` - {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [{ - "matchExpressions": [{ - "key": "foo", - `, - }, - }, - }, - expectErr: true, - }, - } - - for i, tc := range testCases { - _, err := GetAffinityFromPodAnnotations(tc.pod.Annotations) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/install/install_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/install/install_test.go deleted file mode 100644 index 0b1615350..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/install/install_test.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package install - -import ( - "encoding/json" - "reflect" - "testing" - - internal "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestResourceVersioner(t *testing.T) { - pod := internal.Pod{ObjectMeta: internal.ObjectMeta{ResourceVersion: "10"}} - version, err := accessor.ResourceVersion(&pod) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if version != "10" { - t.Errorf("unexpected version %v", version) - } - - podList := internal.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "10"}} - version, err = accessor.ResourceVersion(&podList) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if version != "10" { - t.Errorf("unexpected version %v", version) - } -} - -func TestCodec(t *testing.T) { - pod := internal.Pod{} - // We do want to use package registered rather than testapi here, because we - // want to test if the package install and package registered work as expected. - data, err := runtime.Encode(internal.Codecs.LegacyCodec(registered.GroupOrDie(internal.GroupName).GroupVersion), &pod) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - other := internal.Pod{} - if err := json.Unmarshal(data, &other); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if other.APIVersion != registered.GroupOrDie(internal.GroupName).GroupVersion.Version || other.Kind != "Pod" { - t.Errorf("unexpected unmarshalled object %#v", other) - } -} - -func TestInterfacesFor(t *testing.T) { - if _, err := registered.GroupOrDie(internal.GroupName).InterfacesFor(internal.SchemeGroupVersion); err == nil { - t.Fatalf("unexpected non-error: %v", err) - } - for i, version := range registered.GroupOrDie(internal.GroupName).GroupVersions { - if vi, err := registered.GroupOrDie(internal.GroupName).InterfacesFor(version); err != nil || vi == nil { - t.Fatalf("%d: unexpected result: %v", i, err) - } - } -} - -func TestRESTMapper(t *testing.T) { - gv := unversioned.GroupVersion{Group: "", Version: "v1"} - rcGVK := gv.WithKind("ReplicationController") - podTemplateGVK := gv.WithKind("PodTemplate") - - if gvk, err := registered.GroupOrDie(internal.GroupName).RESTMapper.KindFor(internal.SchemeGroupVersion.WithResource("replicationcontrollers")); err != nil || gvk != rcGVK { - t.Errorf("unexpected version mapping: %v %v", gvk, err) - } - - if m, err := registered.GroupOrDie(internal.GroupName).RESTMapper.RESTMapping(podTemplateGVK.GroupKind(), ""); err != nil || m.GroupVersionKind != podTemplateGVK || m.Resource != "podtemplates" { - t.Errorf("unexpected version mapping: %#v %v", m, err) - } - - for _, version := range registered.GroupOrDie(internal.GroupName).GroupVersions { - mapping, err := registered.GroupOrDie(internal.GroupName).RESTMapper.RESTMapping(rcGVK.GroupKind(), version.Version) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if mapping.Resource != "replicationControllers" && mapping.Resource != "replicationcontrollers" { - t.Errorf("incorrect resource name: %#v", mapping) - } - if mapping.GroupVersionKind.GroupVersion() != version { - t.Errorf("incorrect version: %v", mapping) - } - - interfaces, _ := registered.GroupOrDie(internal.GroupName).InterfacesFor(version) - if mapping.ObjectConvertor != interfaces.ObjectConvertor { - t.Errorf("unexpected: %#v, expected: %#v", mapping, interfaces) - } - - rc := &internal.ReplicationController{ObjectMeta: internal.ObjectMeta{Name: "foo"}} - name, err := mapping.MetadataAccessor.Name(rc) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if name != "foo" { - t.Errorf("unable to retrieve object meta with: %v", mapping.MetadataAccessor) - } - } -} - -func TestUnversioned(t *testing.T) { - for _, obj := range []runtime.Object{ - &unversioned.Status{}, - &unversioned.ExportOptions{}, - } { - if unversioned, ok := internal.Scheme.IsUnversioned(obj); !unversioned || !ok { - t.Errorf("%v is expected to be unversioned", reflect.TypeOf(obj)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/mapper.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/mapper.go index 054f74d5e..0216771ee 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/mapper.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/mapper.go @@ -43,10 +43,10 @@ func NewDefaultRESTMapper(defaultGroupVersions []unversioned.GroupVersion, inter for _, gv := range defaultGroupVersions { for kind, oType := range Scheme.KnownTypes(gv) { gvk := gv.WithKind(kind) - // TODO: Remove import path prefix check. - // We check the import path prefix because we currently stuff both "api" and "extensions" objects + // TODO: Remove import path check. + // We check the import path because we currently stuff both "api" and "extensions" objects // into the same group within Scheme since Scheme has no notion of groups yet. - if !strings.HasPrefix(oType.PkgPath(), importPathPrefix) || ignoredKinds.Has(kind) { + if !strings.Contains(oType.PkgPath(), importPathPrefix) || ignoredKinds.Has(kind) { continue } scope := meta.RESTScopeNamespace diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/help_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/help_test.go deleted file mode 100644 index 435784fdc..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/help_test.go +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package meta_test - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - - "github.com/google/gofuzz" -) - -func TestIsList(t *testing.T) { - tests := []struct { - obj runtime.Object - isList bool - }{ - {&api.PodList{}, true}, - {&api.Pod{}, false}, - } - for _, item := range tests { - if e, a := item.isList, meta.IsListType(item.obj); e != a { - t.Errorf("%v: Expected %v, got %v", reflect.TypeOf(item.obj), e, a) - } - } -} - -func TestExtractList(t *testing.T) { - pl := &api.PodList{ - Items: []api.Pod{ - {ObjectMeta: api.ObjectMeta{Name: "1"}}, - {ObjectMeta: api.ObjectMeta{Name: "2"}}, - {ObjectMeta: api.ObjectMeta{Name: "3"}}, - }, - } - list, err := meta.ExtractList(pl) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := len(list), len(pl.Items); e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - for i := range list { - if e, a := list[i].(*api.Pod).Name, pl.Items[i].Name; e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - } -} - -func TestExtractListV1(t *testing.T) { - pl := &v1.PodList{ - Items: []v1.Pod{ - {ObjectMeta: v1.ObjectMeta{Name: "1"}}, - {ObjectMeta: v1.ObjectMeta{Name: "2"}}, - {ObjectMeta: v1.ObjectMeta{Name: "3"}}, - }, - } - list, err := meta.ExtractList(pl) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := len(list), len(pl.Items); e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - for i := range list { - if e, a := list[i].(*v1.Pod).Name, pl.Items[i].Name; e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - } -} - -func TestExtractListGeneric(t *testing.T) { - pl := &api.List{ - Items: []runtime.Object{ - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}}, - &api.Service{ObjectMeta: api.ObjectMeta{Name: "2"}}, - }, - } - list, err := meta.ExtractList(pl) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := len(list), len(pl.Items); e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - if obj, ok := list[0].(*api.Pod); !ok { - t.Fatalf("Expected list[0] to be *api.Pod, it is %#v", obj) - } - if obj, ok := list[1].(*api.Service); !ok { - t.Fatalf("Expected list[1] to be *api.Service, it is %#v", obj) - } -} - -func TestExtractListGenericV1(t *testing.T) { - pl := &v1.List{ - Items: []runtime.RawExtension{ - {RawJSON: []byte("foo")}, - {RawJSON: []byte("bar")}, - {Object: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "other"}}}, - }, - } - list, err := meta.ExtractList(pl) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := len(list), len(pl.Items); e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - if obj, ok := list[0].(*runtime.Unknown); !ok { - t.Fatalf("Expected list[0] to be *runtime.Unknown, it is %#v", obj) - } - if obj, ok := list[1].(*runtime.Unknown); !ok { - t.Fatalf("Expected list[1] to be *runtime.Unknown, it is %#v", obj) - } - if obj, ok := list[2].(*v1.Pod); !ok { - t.Fatalf("Expected list[2] to be *runtime.Unknown, it is %#v", obj) - } -} - -type fakePtrInterfaceList struct { - Items *[]runtime.Object -} - -func (obj fakePtrInterfaceList) GetObjectKind() unversioned.ObjectKind { - return unversioned.EmptyObjectKind -} - -func TestExtractListOfInterfacePtrs(t *testing.T) { - pl := &fakePtrInterfaceList{ - Items: &[]runtime.Object{}, - } - list, err := meta.ExtractList(pl) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if len(list) > 0 { - t.Fatalf("Expected empty list, got %#v", list) - } -} - -type fakePtrValueList struct { - Items []*api.Pod -} - -func (obj fakePtrValueList) GetObjectKind() unversioned.ObjectKind { - return unversioned.EmptyObjectKind -} - -func TestExtractListOfValuePtrs(t *testing.T) { - pl := &fakePtrValueList{ - Items: []*api.Pod{ - {ObjectMeta: api.ObjectMeta{Name: "1"}}, - {ObjectMeta: api.ObjectMeta{Name: "2"}}, - }, - } - list, err := meta.ExtractList(pl) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := len(list), len(pl.Items); e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - for i := range list { - if obj, ok := list[i].(*api.Pod); !ok { - t.Fatalf("Expected list[%d] to be *api.Pod, it is %#v", i, obj) - } - } -} - -func TestSetList(t *testing.T) { - pl := &api.PodList{} - list := []runtime.Object{ - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}}, - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "3"}}, - } - err := meta.SetList(pl, list) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := len(list), len(pl.Items); e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - for i := range list { - if e, a := list[i].(*api.Pod).Name, pl.Items[i].Name; e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - } -} - -func TestSetListToRuntimeObjectArray(t *testing.T) { - pl := &api.List{} - list := []runtime.Object{ - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}}, - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}}, - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "3"}}, - } - err := meta.SetList(pl, list) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := len(list), len(pl.Items); e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - for i := range list { - if e, a := list[i], pl.Items[i]; e != a { - t.Fatalf("%d: unmatched: %s", i, util.ObjectDiff(e, a)) - } - } -} - -func TestSetExtractListRoundTrip(t *testing.T) { - fuzzer := fuzz.New().NilChance(0).NumElements(1, 5) - for i := 0; i < 5; i++ { - start := &api.PodList{} - fuzzer.Fuzz(&start.Items) - - list, err := meta.ExtractList(start) - if err != nil { - t.Errorf("Unexpected error %v", err) - continue - } - got := &api.PodList{} - err = meta.SetList(got, list) - if err != nil { - t.Errorf("Unexpected error %v", err) - continue - } - if e, a := start, got; !reflect.DeepEqual(e, a) { - t.Fatalf("Expected %#v, got %#v", e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/meta_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/meta_test.go deleted file mode 100644 index 5b6c35230..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/meta_test.go +++ /dev/null @@ -1,778 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package meta_test - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/types" -) - -func TestAPIObjectMeta(t *testing.T) { - j := &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: "/a", Kind: "b"}, - ObjectMeta: api.ObjectMeta{ - Namespace: "bar", - Name: "foo", - GenerateName: "prefix", - UID: "uid", - ResourceVersion: "1", - SelfLink: "some/place/only/we/know", - Labels: map[string]string{"foo": "bar"}, - Annotations: map[string]string{"x": "y"}, - }, - } - var _ meta.Object = &j.ObjectMeta - var _ meta.ObjectMetaAccessor = j - accessor, err := meta.Accessor(j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if accessor != meta.Object(&j.ObjectMeta) { - t.Fatalf("should have returned the same pointer: %#v %#v", accessor, j) - } - if e, a := "bar", accessor.GetNamespace(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "foo", accessor.GetName(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "prefix", accessor.GetGenerateName(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "uid", string(accessor.GetUID()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "1", accessor.GetResourceVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "some/place/only/we/know", accessor.GetSelfLink(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - typeAccessor, err := meta.TypeAccessor(j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := "a", typeAccessor.GetAPIVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "b", typeAccessor.GetKind(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - accessor.SetNamespace("baz") - accessor.SetName("bar") - accessor.SetGenerateName("generate") - accessor.SetUID("other") - typeAccessor.SetAPIVersion("c") - typeAccessor.SetKind("d") - accessor.SetResourceVersion("2") - accessor.SetSelfLink("google.com") - - // Prove that accessor changes the original object. - if e, a := "baz", j.Namespace; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "bar", j.Name; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "generate", j.GenerateName; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := types.UID("other"), j.UID; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "c", j.APIVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "d", j.Kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "2", j.ResourceVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "google.com", j.SelfLink; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - typeAccessor.SetAPIVersion("d") - typeAccessor.SetKind("e") - if e, a := "d", j.APIVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "e", j.Kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestGenericTypeMeta(t *testing.T) { - type TypeMeta struct { - Kind string `json:"kind,omitempty"` - Namespace string `json:"namespace,omitempty"` - Name string `json:"name,omitempty"` - GenerateName string `json:"generateName,omitempty"` - UID string `json:"uid,omitempty"` - CreationTimestamp unversioned.Time `json:"creationTimestamp,omitempty"` - SelfLink string `json:"selfLink,omitempty"` - ResourceVersion string `json:"resourceVersion,omitempty"` - APIVersion string `json:"apiVersion,omitempty"` - Labels map[string]string `json:"labels,omitempty"` - Annotations map[string]string `json:"annotations,omitempty"` - } - type Object struct { - TypeMeta `json:",inline"` - } - j := Object{ - TypeMeta{ - Namespace: "bar", - Name: "foo", - GenerateName: "prefix", - UID: "uid", - APIVersion: "a", - Kind: "b", - ResourceVersion: "1", - SelfLink: "some/place/only/we/know", - Labels: map[string]string{"foo": "bar"}, - Annotations: map[string]string{"x": "y"}, - }, - } - accessor, err := meta.Accessor(&j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := "bar", accessor.GetNamespace(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "foo", accessor.GetName(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "prefix", accessor.GetGenerateName(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "uid", string(accessor.GetUID()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "1", accessor.GetResourceVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "some/place/only/we/know", accessor.GetSelfLink(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - typeAccessor, err := meta.TypeAccessor(&j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := "a", typeAccessor.GetAPIVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "b", typeAccessor.GetKind(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - accessor.SetNamespace("baz") - accessor.SetName("bar") - accessor.SetGenerateName("generate") - accessor.SetUID("other") - typeAccessor.SetAPIVersion("c") - typeAccessor.SetKind("d") - accessor.SetResourceVersion("2") - accessor.SetSelfLink("google.com") - - // Prove that accessor changes the original object. - if e, a := "baz", j.Namespace; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "bar", j.Name; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "generate", j.GenerateName; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "other", j.UID; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "c", j.APIVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "d", j.Kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "2", j.ResourceVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "google.com", j.SelfLink; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - typeAccessor.SetAPIVersion("d") - typeAccessor.SetKind("e") - if e, a := "d", j.APIVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "e", j.Kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } -} - -type InternalTypeMeta struct { - Kind string `json:"kind,omitempty"` - Namespace string `json:"namespace,omitempty"` - Name string `json:"name,omitempty"` - GenerateName string `json:"generateName,omitempty"` - UID string `json:"uid,omitempty"` - CreationTimestamp unversioned.Time `json:"creationTimestamp,omitempty"` - SelfLink string `json:"selfLink,omitempty"` - ResourceVersion string `json:"resourceVersion,omitempty"` - APIVersion string `json:"apiVersion,omitempty"` - Labels map[string]string `json:"labels,omitempty"` - Annotations map[string]string `json:"annotations,omitempty"` -} -type InternalObject struct { - TypeMeta InternalTypeMeta `json:",inline"` -} - -func (obj *InternalObject) GetObjectKind() unversioned.ObjectKind { return obj } -func (obj *InternalObject) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { - obj.TypeMeta.APIVersion, obj.TypeMeta.Kind = gvk.ToAPIVersionAndKind() -} -func (obj *InternalObject) GroupVersionKind() *unversioned.GroupVersionKind { - return unversioned.FromAPIVersionAndKind(obj.TypeMeta.APIVersion, obj.TypeMeta.Kind) -} - -func TestGenericTypeMetaAccessor(t *testing.T) { - j := &InternalObject{ - InternalTypeMeta{ - Namespace: "bar", - Name: "foo", - GenerateName: "prefix", - UID: "uid", - APIVersion: "/a", - Kind: "b", - ResourceVersion: "1", - SelfLink: "some/place/only/we/know", - Labels: map[string]string{"foo": "bar"}, - Annotations: map[string]string{"x": "y"}, - }, - } - accessor := meta.NewAccessor() - namespace, err := accessor.Namespace(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "bar", namespace; e != a { - t.Errorf("expected %v, got %v", e, a) - } - name, err := accessor.Name(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "foo", name; e != a { - t.Errorf("expected %v, got %v", e, a) - } - generateName, err := accessor.GenerateName(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "prefix", generateName; e != a { - t.Errorf("expected %v, got %v", e, a) - } - uid, err := accessor.UID(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "uid", string(uid); e != a { - t.Errorf("expected %v, got %v", e, a) - } - apiVersion, err := accessor.APIVersion(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "a", apiVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - kind, err := accessor.Kind(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "b", kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } - rv, err := accessor.ResourceVersion(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "1", rv; e != a { - t.Errorf("expected %v, got %v", e, a) - } - selfLink, err := accessor.SelfLink(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := "some/place/only/we/know", selfLink; e != a { - t.Errorf("expected %v, got %v", e, a) - } - labels, err := accessor.Labels(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := 1, len(labels); e != a { - t.Errorf("expected %v, got %v", e, a) - } - annotations, err := accessor.Annotations(j) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := 1, len(annotations); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - if err := accessor.SetNamespace(j, "baz"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetName(j, "bar"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetGenerateName(j, "generate"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetUID(j, "other"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetAPIVersion(j, "c"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetKind(j, "d"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetResourceVersion(j, "2"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetSelfLink(j, "google.com"); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := accessor.SetLabels(j, map[string]string{}); err != nil { - t.Errorf("unexpected error: %v", err) - } - var nilMap map[string]string - if err := accessor.SetAnnotations(j, nilMap); err != nil { - t.Errorf("unexpected error: %v", err) - } - - // Prove that accessor changes the original object. - if e, a := "baz", j.TypeMeta.Namespace; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "bar", j.TypeMeta.Name; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "generate", j.TypeMeta.GenerateName; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "other", j.TypeMeta.UID; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "c", j.TypeMeta.APIVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "d", j.TypeMeta.Kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "2", j.TypeMeta.ResourceVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "google.com", j.TypeMeta.SelfLink; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := map[string]string{}, j.TypeMeta.Labels; !reflect.DeepEqual(e, a) { - t.Errorf("expected %#v, got %#v", e, a) - } - if e, a := nilMap, j.TypeMeta.Annotations; !reflect.DeepEqual(e, a) { - t.Errorf("expected %#v, got %#v", e, a) - } -} - -func TestGenericObjectMeta(t *testing.T) { - type TypeMeta struct { - Kind string `json:"kind,omitempty"` - APIVersion string `json:"apiVersion,omitempty"` - } - type ObjectMeta struct { - Namespace string `json:"namespace,omitempty"` - Name string `json:"name,omitempty"` - GenerateName string `json:"generateName,omitempty"` - UID string `json:"uid,omitempty"` - CreationTimestamp unversioned.Time `json:"creationTimestamp,omitempty"` - SelfLink string `json:"selfLink,omitempty"` - ResourceVersion string `json:"resourceVersion,omitempty"` - Labels map[string]string `json:"labels,omitempty"` - Annotations map[string]string `json:"annotations,omitempty"` - } - type Object struct { - TypeMeta `json:",inline"` - ObjectMeta `json:"metadata"` - } - j := Object{ - TypeMeta{ - APIVersion: "a", - Kind: "b", - }, - ObjectMeta{ - Namespace: "bar", - Name: "foo", - GenerateName: "prefix", - UID: "uid", - ResourceVersion: "1", - SelfLink: "some/place/only/we/know", - Labels: map[string]string{"foo": "bar"}, - Annotations: map[string]string{"a": "b"}, - }, - } - accessor, err := meta.Accessor(&j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := "bar", accessor.GetNamespace(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "foo", accessor.GetName(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "prefix", accessor.GetGenerateName(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "uid", string(accessor.GetUID()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "1", accessor.GetResourceVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "some/place/only/we/know", accessor.GetSelfLink(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 1, len(accessor.GetLabels()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 1, len(accessor.GetAnnotations()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - typeAccessor, err := meta.TypeAccessor(&j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := "a", typeAccessor.GetAPIVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "b", typeAccessor.GetKind(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - accessor.SetNamespace("baz") - accessor.SetName("bar") - accessor.SetGenerateName("generate") - accessor.SetUID("other") - typeAccessor.SetAPIVersion("c") - typeAccessor.SetKind("d") - accessor.SetResourceVersion("2") - accessor.SetSelfLink("google.com") - accessor.SetLabels(map[string]string{"other": "label"}) - accessor.SetAnnotations(map[string]string{"c": "d"}) - - // Prove that accessor changes the original object. - if e, a := "baz", j.Namespace; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "bar", j.Name; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "generate", j.GenerateName; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "other", j.UID; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "c", j.APIVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "d", j.Kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "2", j.ResourceVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "google.com", j.SelfLink; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := map[string]string{"other": "label"}, j.Labels; !reflect.DeepEqual(e, a) { - t.Errorf("expected %#v, got %#v", e, a) - } - if e, a := map[string]string{"c": "d"}, j.Annotations; !reflect.DeepEqual(e, a) { - t.Errorf("expected %#v, got %#v", e, a) - } -} - -func TestGenericListMeta(t *testing.T) { - type TypeMeta struct { - Kind string `json:"kind,omitempty"` - APIVersion string `json:"apiVersion,omitempty"` - } - type ListMeta struct { - SelfLink string `json:"selfLink,omitempty"` - ResourceVersion string `json:"resourceVersion,omitempty"` - } - type Object struct { - TypeMeta `json:",inline"` - ListMeta `json:"metadata"` - } - j := Object{ - TypeMeta{ - APIVersion: "a", - Kind: "b", - }, - ListMeta{ - ResourceVersion: "1", - SelfLink: "some/place/only/we/know", - }, - } - accessor, err := meta.Accessor(&j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := "", accessor.GetName(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "", string(accessor.GetUID()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "1", accessor.GetResourceVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "some/place/only/we/know", accessor.GetSelfLink(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - typeAccessor, err := meta.TypeAccessor(&j) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := "a", typeAccessor.GetAPIVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "b", typeAccessor.GetKind(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - accessor.SetName("bar") - accessor.SetUID("other") - typeAccessor.SetAPIVersion("c") - typeAccessor.SetKind("d") - accessor.SetResourceVersion("2") - accessor.SetSelfLink("google.com") - - // Prove that accessor changes the original object. - if e, a := "c", j.APIVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "d", j.Kind; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "2", j.ResourceVersion; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "google.com", j.SelfLink; e != a { - t.Errorf("expected %v, got %v", e, a) - } -} - -type MyAPIObject struct { - TypeMeta InternalTypeMeta `json:",inline"` -} - -func (obj *MyAPIObject) GetObjectKind() unversioned.ObjectKind { return obj } -func (obj *MyAPIObject) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { - obj.TypeMeta.APIVersion, obj.TypeMeta.Kind = gvk.ToAPIVersionAndKind() -} -func (obj *MyAPIObject) GroupVersionKind() *unversioned.GroupVersionKind { - return unversioned.FromAPIVersionAndKind(obj.TypeMeta.APIVersion, obj.TypeMeta.Kind) -} - -type MyIncorrectlyMarkedAsAPIObject struct{} - -func (obj *MyIncorrectlyMarkedAsAPIObject) GetObjectKind() unversioned.ObjectKind { - return unversioned.EmptyObjectKind -} - -func TestResourceVersionerOfAPI(t *testing.T) { - type T struct { - runtime.Object - Expected string - } - testCases := map[string]T{ - "empty api object": {&MyAPIObject{}, ""}, - "api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"}, - "pointer to api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"}, - } - versioning := meta.NewAccessor() - for key, testCase := range testCases { - actual, err := versioning.ResourceVersion(testCase.Object) - if err != nil { - t.Errorf("%s: unexpected error %#v", key, err) - } - if actual != testCase.Expected { - t.Errorf("%s: expected %v, got %v", key, testCase.Expected, actual) - } - } - - failingCases := map[string]struct { - runtime.Object - Expected string - }{ - "not a valid object to try": {&MyIncorrectlyMarkedAsAPIObject{}, "1"}, - } - for key, testCase := range failingCases { - _, err := versioning.ResourceVersion(testCase.Object) - if err == nil { - t.Errorf("%s: expected error, got nil", key) - } - } - - setCases := map[string]struct { - runtime.Object - Expected string - }{ - "pointer to api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"}, - } - for key, testCase := range setCases { - if err := versioning.SetResourceVersion(testCase.Object, "5"); err != nil { - t.Errorf("%s: unexpected error %#v", key, err) - } - actual, err := versioning.ResourceVersion(testCase.Object) - if err != nil { - t.Errorf("%s: unexpected error %#v", key, err) - } - if actual != "5" { - t.Errorf("%s: expected %v, got %v", key, "5", actual) - } - } -} - -func TestTypeMetaSelfLinker(t *testing.T) { - table := map[string]struct { - obj runtime.Object - expect string - try string - succeed bool - }{ - "normal": { - obj: &MyAPIObject{TypeMeta: InternalTypeMeta{SelfLink: "foobar"}}, - expect: "foobar", - try: "newbar", - succeed: true, - }, - "fail": { - obj: &MyIncorrectlyMarkedAsAPIObject{}, - succeed: false, - }, - } - - linker := runtime.SelfLinker(meta.NewAccessor()) - for name, item := range table { - got, err := linker.SelfLink(item.obj) - if e, a := item.succeed, err == nil; e != a { - t.Errorf("%v: expected %v, got %v", name, e, a) - } - if e, a := item.expect, got; item.succeed && e != a { - t.Errorf("%v: expected %v, got %v", name, e, a) - } - - err = linker.SetSelfLink(item.obj, item.try) - if e, a := item.succeed, err == nil; e != a { - t.Errorf("%v: expected %v, got %v", name, e, a) - } - if item.succeed { - got, err := linker.SelfLink(item.obj) - if err != nil { - t.Errorf("%v: expected no err, got %v", name, err) - } - if e, a := item.try, got; e != a { - t.Errorf("%v: expected %v, got %v", name, e, a) - } - } - } -} - -// BenchmarkAccessorSetFastPath shows the interface fast path -func BenchmarkAccessorSetFastPath(b *testing.B) { - obj := &api.Pod{ - TypeMeta: unversioned.TypeMeta{APIVersion: "/a", Kind: "b"}, - ObjectMeta: api.ObjectMeta{ - Namespace: "bar", - Name: "foo", - GenerateName: "prefix", - UID: "uid", - ResourceVersion: "1", - SelfLink: "some/place/only/we/know", - Labels: map[string]string{"foo": "bar"}, - Annotations: map[string]string{"x": "y"}, - }, - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - acc, err := meta.Accessor(obj) - if err != nil { - b.Fatal(err) - } - acc.SetNamespace("something") - } - b.StopTimer() -} - -// BenchmarkAccessorSetReflection provides a baseline for accessor performance -func BenchmarkAccessorSetReflection(b *testing.B) { - obj := &InternalObject{ - InternalTypeMeta{ - Namespace: "bar", - Name: "foo", - GenerateName: "prefix", - UID: "uid", - APIVersion: "a", - Kind: "b", - ResourceVersion: "1", - SelfLink: "some/place/only/we/know", - Labels: map[string]string{"foo": "bar"}, - Annotations: map[string]string{"x": "y"}, - }, - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - acc, err := meta.Accessor(obj) - if err != nil { - b.Fatal(err) - } - acc.SetNamespace("something") - } - b.StopTimer() -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go index 4d284e62a..3071d4507 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go @@ -21,6 +21,7 @@ import ( "strings" "k8s.io/kubernetes/pkg/api/unversioned" + utilerrors "k8s.io/kubernetes/pkg/util/errors" ) // MultiRESTMapper is a wrapper for multiple RESTMappers. @@ -50,72 +51,144 @@ func (m MultiRESTMapper) ResourceSingularizer(resource string) (singular string, } func (m MultiRESTMapper) ResourcesFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) { + allGVRs := []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) { - return gvrs, err + if IsNoResourceMatchError(err) { + continue + } + if err != nil { + return nil, err + } + + // walk the existing values to de-dup + for _, curr := range gvrs { + found := false + for _, existing := range allGVRs { + if curr == existing { + found = true + break + } + } + + if !found { + allGVRs = append(allGVRs, curr) + } } } - return nil, &NoResourceMatchError{PartialResource: resource} + + if len(allGVRs) == 0 { + return nil, &NoResourceMatchError{PartialResource: resource} + } + + return allGVRs, nil } -// KindsFor provides the Kind mappings for the REST resources. This implementation supports multiple REST schemas and returns -// the first match. func (m MultiRESTMapper) KindsFor(resource unversioned.GroupVersionResource) (gvk []unversioned.GroupVersionKind, err error) { + allGVKs := []unversioned.GroupVersionKind{} for _, t := range m { gvks, err := t.KindsFor(resource) // ignore "no match" errors, but any other error percolates back up - if !IsNoResourceMatchError(err) { - return gvks, err + if IsNoResourceMatchError(err) { + continue + } + if err != nil { + return nil, err + } + + // walk the existing values to de-dup + for _, curr := range gvks { + found := false + for _, existing := range allGVKs { + if curr == existing { + found = true + break + } + } + + if !found { + allGVKs = append(allGVKs, curr) + } } } - return nil, &NoResourceMatchError{PartialResource: resource} + + if len(allGVKs) == 0 { + return nil, &NoResourceMatchError{PartialResource: resource} + } + + return allGVKs, nil } func (m MultiRESTMapper) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) { - for _, t := range m { - gvr, err := t.ResourceFor(resource) - // ignore "no match" errors, but any other error percolates back up - if !IsNoResourceMatchError(err) { - return gvr, err - } + resources, err := m.ResourcesFor(resource) + if err != nil { + return unversioned.GroupVersionResource{}, err } - return unversioned.GroupVersionResource{}, &NoResourceMatchError{PartialResource: resource} + if len(resources) == 1 { + return resources[0], nil + } + + return unversioned.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: resource, MatchingResources: resources} } -// KindsFor provides the Kind mapping for the REST resources. This implementation supports multiple REST schemas and returns -// the first match. func (m MultiRESTMapper) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) { - for _, t := range m { - gvk, err := t.KindFor(resource) - // ignore "no match" errors, but any other error percolates back up - if !IsNoResourceMatchError(err) { - return gvk, err - } + kinds, err := m.KindsFor(resource) + if err != nil { + return unversioned.GroupVersionKind{}, err } - return unversioned.GroupVersionKind{}, &NoResourceMatchError{PartialResource: resource} + if len(kinds) == 1 { + return kinds[0], nil + } + + return unversioned.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds} } // RESTMapping provides the REST mapping for the resource based on the // kind and version. This implementation supports multiple REST schemas and // return the first match. -func (m MultiRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (mapping *RESTMapping, err error) { +func (m MultiRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (*RESTMapping, error) { + allMappings := []*RESTMapping{} + errors := []error{} + for _, t := range m { - mapping, err = t.RESTMapping(gk, versions...) - if err == nil { - return + currMapping, err := t.RESTMapping(gk, versions...) + // ignore "no match" errors, but any other error percolates back up + if IsNoResourceMatchError(err) { + continue } + if err != nil { + errors = append(errors, err) + continue + } + + allMappings = append(allMappings, currMapping) } - return + + // if we got exactly one mapping, then use it even if other requested failed + if len(allMappings) == 1 { + return allMappings[0], nil + } + if len(errors) > 0 { + return nil, utilerrors.NewAggregate(errors) + } + if len(allMappings) == 0 { + return nil, fmt.Errorf("no match found for %v in %v", gk, versions) + } + + return nil, fmt.Errorf("multiple matches found for %v in %v", gk, versions) } // AliasesForResource finds the first alias response for the provided mappers. -func (m MultiRESTMapper) AliasesForResource(alias string) (aliases []string, ok bool) { +func (m MultiRESTMapper) AliasesForResource(alias string) ([]string, bool) { + allAliases := []string{} + handled := false + for _, t := range m { - if aliases, ok = t.AliasesForResource(alias); ok { - return + if currAliases, currOk := t.AliasesForResource(alias); currOk { + allAliases = append(allAliases, currAliases...) + handled = true } } - return nil, false + return allAliases, handled } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/multirestmapper_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/multirestmapper_test.go deleted file mode 100644 index c4d543115..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/multirestmapper_test.go +++ /dev/null @@ -1,238 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package meta - -import ( - "errors" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" -) - -func TestMultiRESTMapperResourceForErrorHandling(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input unversioned.GroupVersionResource - result unversioned.GroupVersionResource - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: unversioned.GroupVersionResource{}, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: unversioned.GroupVersionResource{}, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{resourceFor: unversioned.GroupVersionResource{Resource: "unused"}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: unversioned.GroupVersionResource{}, - err: errors.New("fail on this"), - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.ResourceFor(tc.input) - if e, a := tc.result, actualResult; e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.err.Error(), actualErr.Error(); e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - } -} - -func TestMultiRESTMapperResourcesForErrorHandling(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input unversioned.GroupVersionResource - result []unversioned.GroupVersionResource - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{resourcesFor: []unversioned.GroupVersionResource{{Resource: "unused"}}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: nil, - err: errors.New("fail on this"), - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.ResourcesFor(tc.input) - if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.err.Error(), actualErr.Error(); e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - } -} - -func TestMultiRESTMapperKindsForErrorHandling(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input unversioned.GroupVersionResource - result []unversioned.GroupVersionKind - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{kindsFor: []unversioned.GroupVersionKind{{Kind: "unused"}}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: nil, - err: errors.New("fail on this"), - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.KindsFor(tc.input) - if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.err.Error(), actualErr.Error(); e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - } -} - -func TestMultiRESTMapperKindForErrorHandling(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input unversioned.GroupVersionResource - result unversioned.GroupVersionKind - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: unversioned.GroupVersionKind{}, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: unversioned.GroupVersionKind{}, - err: &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{kindFor: unversioned.GroupVersionKind{Kind: "unused"}}}, - input: unversioned.GroupVersionResource{Resource: "foo"}, - result: unversioned.GroupVersionKind{}, - err: errors.New("fail on this"), - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.KindFor(tc.input) - if e, a := tc.result, actualResult; e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.err.Error(), actualErr.Error(); e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - } -} - -type fixedRESTMapper struct { - resourcesFor []unversioned.GroupVersionResource - kindsFor []unversioned.GroupVersionKind - resourceFor unversioned.GroupVersionResource - kindFor unversioned.GroupVersionKind - - err error -} - -func (m fixedRESTMapper) ResourceSingularizer(resource string) (singular string, err error) { - return "", m.err -} - -func (m fixedRESTMapper) ResourcesFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) { - return m.resourcesFor, m.err -} - -func (m fixedRESTMapper) KindsFor(resource unversioned.GroupVersionResource) (gvk []unversioned.GroupVersionKind, err error) { - return m.kindsFor, m.err -} - -func (m fixedRESTMapper) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) { - return m.resourceFor, m.err -} - -func (m fixedRESTMapper) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) { - return m.kindFor, m.err -} - -func (m fixedRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (mapping *RESTMapping, err error) { - return nil, m.err -} - -func (m fixedRESTMapper) AliasesForResource(alias string) (aliases []string, ok bool) { - return nil, false -} - -func (m fixedRESTMapper) ResourceIsValid(resource unversioned.GroupVersionResource) bool { - return false -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/priority.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/priority.go new file mode 100644 index 000000000..24f38f78f --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/priority.go @@ -0,0 +1,173 @@ +/* +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. +*/ + +package meta + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api/unversioned" +) + +const ( + AnyGroup = "*" + AnyVersion = "*" + AnyResource = "*" + AnyKind = "*" +) + +// PriorityRESTMapper is a wrapper for automatically choosing a particular Resource or Kind +// when multiple matches are possible +type PriorityRESTMapper struct { + // Delegate is the RESTMapper to use to locate all the Kind and Resource matches + Delegate RESTMapper + + // ResourcePriority is a list of priority patterns to apply to matching resources. + // The list of all matching resources is narrowed based on the patterns until only one remains. + // A pattern with no matches is skipped. A pattern with more than one match uses its + // matches as the list to continue matching against. + ResourcePriority []unversioned.GroupVersionResource + + // KindPriority is a list of priority patterns to apply to matching kinds. + // The list of all matching kinds is narrowed based on the patterns until only one remains. + // A pattern with no matches is skipped. A pattern with more than one match uses its + // matches as the list to continue matching against. + KindPriority []unversioned.GroupVersionKind +} + +func (m PriorityRESTMapper) String() string { + return fmt.Sprintf("PriorityRESTMapper{\n\t%v\n\t%v\n\t%v\n}", m.ResourcePriority, m.KindPriority, m.Delegate) +} + +// ResourceFor finds all resources, then passes them through the ResourcePriority patterns to find a single matching hit. +func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) { + originalGVRs, err := m.Delegate.ResourcesFor(partiallySpecifiedResource) + if err != nil { + return unversioned.GroupVersionResource{}, err + } + if len(originalGVRs) == 1 { + return originalGVRs[0], nil + } + + remainingGVRs := append([]unversioned.GroupVersionResource{}, originalGVRs...) + for _, pattern := range m.ResourcePriority { + matchedGVRs := []unversioned.GroupVersionResource{} + for _, gvr := range remainingGVRs { + if resourceMatches(pattern, gvr) { + matchedGVRs = append(matchedGVRs, gvr) + } + } + + switch len(matchedGVRs) { + case 0: + // if you have no matches, then nothing matched this pattern just move to the next + continue + case 1: + // one match, return + return matchedGVRs[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 + remainingGVRs = matchedGVRs + } + } + + return unversioned.GroupVersionResource{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingResources: originalGVRs} +} + +// KindFor finds all kinds, then passes them through the KindPriority patterns to find a single matching hit. +func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) { + originalGVKs, err := m.Delegate.KindsFor(partiallySpecifiedResource) + if err != nil { + return unversioned.GroupVersionKind{}, err + } + if len(originalGVKs) == 1 { + return originalGVKs[0], nil + } + + remainingGVKs := append([]unversioned.GroupVersionKind{}, originalGVKs...) + for _, pattern := range m.KindPriority { + matchedGVKs := []unversioned.GroupVersionKind{} + for _, gvr := range remainingGVKs { + if kindMatches(pattern, gvr) { + matchedGVKs = append(matchedGVKs, gvr) + } + } + + switch len(matchedGVKs) { + case 0: + // if you have no matches, then nothing matched this pattern just move to the next + continue + case 1: + // one match, return + return matchedGVKs[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 + remainingGVKs = matchedGVKs + } + } + + return unversioned.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingKinds: originalGVKs} +} + +func resourceMatches(pattern unversioned.GroupVersionResource, resource unversioned.GroupVersionResource) bool { + if pattern.Group != AnyGroup && pattern.Group != resource.Group { + return false + } + if pattern.Version != AnyVersion && pattern.Version != resource.Version { + return false + } + if pattern.Resource != AnyResource && pattern.Resource != resource.Resource { + return false + } + + return true +} + +func kindMatches(pattern unversioned.GroupVersionKind, kind unversioned.GroupVersionKind) bool { + if pattern.Group != AnyGroup && pattern.Group != kind.Group { + return false + } + if pattern.Version != AnyVersion && pattern.Version != kind.Version { + return false + } + if pattern.Kind != AnyKind && pattern.Kind != kind.Kind { + return false + } + + return true +} + +func (m PriorityRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (mapping *RESTMapping, err error) { + return m.Delegate.RESTMapping(gk, versions...) +} + +func (m PriorityRESTMapper) AliasesForResource(alias string) (aliases []string, ok bool) { + return m.Delegate.AliasesForResource(alias) +} + +func (m PriorityRESTMapper) ResourceSingularizer(resource string) (singular string, err error) { + return m.Delegate.ResourceSingularizer(resource) +} + +func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) { + return m.Delegate.ResourcesFor(partiallySpecifiedResource) +} + +func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource unversioned.GroupVersionResource) (gvk []unversioned.GroupVersionKind, err error) { + return m.Delegate.KindsFor(partiallySpecifiedResource) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/restmapper.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/restmapper.go index 7b1856bc4..d56b18cea 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/restmapper.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/restmapper.go @@ -24,7 +24,6 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/sets" ) // Implements RESTScope interface @@ -330,23 +329,8 @@ func (m *DefaultRESTMapper) KindFor(resource unversioned.GroupVersionResource) ( if err != nil { return unversioned.GroupVersionKind{}, err } - - // TODO for each group, choose the most preferred (first) version. This keeps us consistent with code today. - // eventually, we'll need a RESTMapper that is aware of what's available server-side and deconflicts that with - // user preferences - oneKindPerGroup := []unversioned.GroupVersionKind{} - groupsAdded := sets.String{} - for _, kind := range kinds { - if groupsAdded.Has(kind.Group) { - continue - } - - oneKindPerGroup = append(oneKindPerGroup, kind) - groupsAdded.Insert(kind.Group) - } - - if len(oneKindPerGroup) == 1 { - return oneKindPerGroup[0], nil + if len(kinds) == 1 { + return kinds[0], nil } return unversioned.GroupVersionKind{}, &AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/restmapper_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/restmapper_test.go deleted file mode 100644 index 8f494d0a6..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta/restmapper_test.go +++ /dev/null @@ -1,550 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package meta - -import ( - "errors" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -type fakeConvertor struct{} - -func (fakeConvertor) Convert(in, out interface{}) error { - return nil -} - -func (fakeConvertor) ConvertToVersion(in runtime.Object, _ string) (runtime.Object, error) { - return in, nil -} - -func (fakeConvertor) ConvertFieldLabel(version, kind, label, value string) (string, string, error) { - return label, value, nil -} - -var validAccessor = resourceAccessor{} -var validConvertor = fakeConvertor{} - -func fakeInterfaces(version unversioned.GroupVersion) (*VersionInterfaces, error) { - return &VersionInterfaces{ObjectConvertor: validConvertor, MetadataAccessor: validAccessor}, nil -} - -var unmatchedErr = errors.New("no version") - -func unmatchedVersionInterfaces(version unversioned.GroupVersion) (*VersionInterfaces, error) { - return nil, unmatchedErr -} - -func TestRESTMapperVersionAndKindForResource(t *testing.T) { - testGroup := "test.group" - testVersion := "test" - testGroupVersion := unversioned.GroupVersion{Group: testGroup, Version: testVersion} - - testCases := []struct { - Resource unversioned.GroupVersionResource - GroupVersionToRegister unversioned.GroupVersion - ExpectedGVK unversioned.GroupVersionKind - Err bool - }{ - {Resource: unversioned.GroupVersionResource{Resource: "internalobjec"}, Err: true}, - {Resource: unversioned.GroupVersionResource{Resource: "internalObjec"}, Err: true}, - - {Resource: unversioned.GroupVersionResource{Resource: "internalobject"}, ExpectedGVK: testGroupVersion.WithKind("InternalObject")}, - {Resource: unversioned.GroupVersionResource{Resource: "internalobjects"}, ExpectedGVK: testGroupVersion.WithKind("InternalObject")}, - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper([]unversioned.GroupVersion{testGroupVersion}, fakeInterfaces) - if len(testCase.ExpectedGVK.Kind) != 0 { - mapper.Add(testCase.ExpectedGVK, RESTScopeNamespace) - } - actualGVK, err := mapper.KindFor(testCase.Resource) - - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err) - continue - } - if err != nil { - continue - } - - if actualGVK != testCase.ExpectedGVK { - t.Errorf("%d: unexpected version and kind: e=%s a=%s", i, testCase.ExpectedGVK, actualGVK) - } - } -} - -func TestRESTMapperGroupForResource(t *testing.T) { - testCases := []struct { - Resource unversioned.GroupVersionResource - GroupVersionKind unversioned.GroupVersionKind - Err bool - }{ - {Resource: unversioned.GroupVersionResource{Resource: "myObject"}, GroupVersionKind: unversioned.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}}, - {Resource: unversioned.GroupVersionResource{Resource: "myobject"}, GroupVersionKind: unversioned.GroupVersionKind{Group: "testapi2", Version: "test", Kind: "MyObject"}}, - {Resource: unversioned.GroupVersionResource{Resource: "myObje"}, Err: true, GroupVersionKind: unversioned.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}}, - {Resource: unversioned.GroupVersionResource{Resource: "myobje"}, Err: true, GroupVersionKind: unversioned.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}}, - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper([]unversioned.GroupVersion{testCase.GroupVersionKind.GroupVersion()}, fakeInterfaces) - mapper.Add(testCase.GroupVersionKind, RESTScopeNamespace) - - actualGVK, err := mapper.KindFor(testCase.Resource) - if testCase.Err { - if err == nil { - t.Errorf("%d: expected error", i) - } - } else if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - } else if actualGVK != testCase.GroupVersionKind { - t.Errorf("%d: expected group %q, got %q", i, testCase.GroupVersionKind, actualGVK) - } - } -} - -func TestRESTMapperKindsFor(t *testing.T) { - testCases := []struct { - Name string - PreferredOrder []unversioned.GroupVersion - KindsToRegister []unversioned.GroupVersionKind - PartialResourceToRequest unversioned.GroupVersionResource - - ExpectedKinds []unversioned.GroupVersionKind - ExpectedKindErr string - }{ - { - Name: "ambiguous groups, with preference order", - PreferredOrder: []unversioned.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PartialResourceToRequest: unversioned.GroupVersionResource{Resource: "my-kinds"}, - - ExpectedKinds: []unversioned.GroupVersionKind{ - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - ExpectedKindErr: " matches multiple kinds ", - }, - - { - Name: "ambiguous groups, with explicit group match", - PreferredOrder: []unversioned.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PartialResourceToRequest: unversioned.GroupVersionResource{Group: "first-group", Resource: "my-kinds"}, - - ExpectedKinds: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - }, - - { - Name: "ambiguous groups, with ambiguous version match", - PreferredOrder: []unversioned.GroupVersion{ - {Group: "first-group", Version: "first-version"}, - {Group: "second-group", Version: "first-version"}, - }, - KindsToRegister: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PartialResourceToRequest: unversioned.GroupVersionResource{Version: "first-version", Resource: "my-kinds"}, - - ExpectedKinds: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - }, - ExpectedKindErr: " matches multiple kinds ", - }, - } - for _, testCase := range testCases { - tcName := testCase.Name - mapper := NewDefaultRESTMapper(testCase.PreferredOrder, fakeInterfaces) - for _, kind := range testCase.KindsToRegister { - mapper.Add(kind, RESTScopeNamespace) - } - - actualKinds, err := mapper.KindsFor(testCase.PartialResourceToRequest) - if err != nil { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } - if !reflect.DeepEqual(testCase.ExpectedKinds, actualKinds) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKinds, actualKinds) - } - - singleKind, err := mapper.KindFor(testCase.PartialResourceToRequest) - if err == nil && len(testCase.ExpectedKindErr) != 0 { - t.Errorf("%s: expected error: %v", tcName, testCase.ExpectedKindErr) - continue - } - if err != nil { - if len(testCase.ExpectedKindErr) == 0 { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } else { - if !strings.Contains(err.Error(), testCase.ExpectedKindErr) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKindErr, err) - continue - } - } - - } else { - if testCase.ExpectedKinds[0] != singleKind { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKinds[0], singleKind) - } - - } - } -} - -func TestRESTMapperResourcesFor(t *testing.T) { - testCases := []struct { - Name string - PreferredOrder []unversioned.GroupVersion - KindsToRegister []unversioned.GroupVersionKind - PluralPartialResourceToRequest unversioned.GroupVersionResource - SingularPartialResourceToRequest unversioned.GroupVersionResource - - ExpectedResources []unversioned.GroupVersionResource - ExpectedResourceErr string - }{ - { - Name: "ambiguous groups, with preference order", - PreferredOrder: []unversioned.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PluralPartialResourceToRequest: unversioned.GroupVersionResource{Resource: "my-kinds"}, - SingularPartialResourceToRequest: unversioned.GroupVersionResource{Resource: "my-kind"}, - - ExpectedResources: []unversioned.GroupVersionResource{ - {Group: "second-group", Version: "first-version", Resource: "my-kinds"}, - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - }, - ExpectedResourceErr: " matches multiple resources ", - }, - - { - Name: "ambiguous groups, with explicit group match", - PreferredOrder: []unversioned.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PluralPartialResourceToRequest: unversioned.GroupVersionResource{Group: "first-group", Resource: "my-kinds"}, - SingularPartialResourceToRequest: unversioned.GroupVersionResource{Group: "first-group", Resource: "my-kind"}, - - ExpectedResources: []unversioned.GroupVersionResource{ - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - }, - }, - - { - Name: "ambiguous groups, with ambiguous version match", - PreferredOrder: []unversioned.GroupVersion{ - {Group: "first-group", Version: "first-version"}, - {Group: "second-group", Version: "first-version"}, - }, - KindsToRegister: []unversioned.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PluralPartialResourceToRequest: unversioned.GroupVersionResource{Version: "first-version", Resource: "my-kinds"}, - SingularPartialResourceToRequest: unversioned.GroupVersionResource{Version: "first-version", Resource: "my-kind"}, - - ExpectedResources: []unversioned.GroupVersionResource{ - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - {Group: "second-group", Version: "first-version", Resource: "my-kinds"}, - }, - ExpectedResourceErr: " matches multiple resources ", - }, - } - for _, testCase := range testCases { - tcName := testCase.Name - - for _, partialResource := range []unversioned.GroupVersionResource{testCase.PluralPartialResourceToRequest, testCase.SingularPartialResourceToRequest} { - mapper := NewDefaultRESTMapper(testCase.PreferredOrder, fakeInterfaces) - for _, kind := range testCase.KindsToRegister { - mapper.Add(kind, RESTScopeNamespace) - } - - actualResources, err := mapper.ResourcesFor(partialResource) - if err != nil { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } - if !reflect.DeepEqual(testCase.ExpectedResources, actualResources) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResources, actualResources) - } - - singleResource, err := mapper.ResourceFor(partialResource) - if err == nil && len(testCase.ExpectedResourceErr) != 0 { - t.Errorf("%s: expected error: %v", tcName, testCase.ExpectedResourceErr) - continue - } - if err != nil { - if len(testCase.ExpectedResourceErr) == 0 { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } else { - if !strings.Contains(err.Error(), testCase.ExpectedResourceErr) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResourceErr, err) - continue - } - } - - } else { - if testCase.ExpectedResources[0] != singleResource { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResources[0], singleResource) - } - - } - } - } -} - -func TestKindToResource(t *testing.T) { - testCases := []struct { - Kind string - Plural, Singular string - }{ - {Kind: "Pod", Plural: "pods", Singular: "pod"}, - - {Kind: "ReplicationController", Plural: "replicationcontrollers", Singular: "replicationcontroller"}, - - // Add "ies" when ending with "y" - {Kind: "ImageRepository", Plural: "imagerepositories", Singular: "imagerepository"}, - // Add "es" when ending with "s" - {Kind: "miss", Plural: "misses", Singular: "miss"}, - // Add "s" otherwise - {Kind: "lowercase", Plural: "lowercases", Singular: "lowercase"}, - } - for i, testCase := range testCases { - version := unversioned.GroupVersion{} - - plural, singular := KindToResource(version.WithKind(testCase.Kind)) - if singular != version.WithResource(testCase.Singular) || plural != version.WithResource(testCase.Plural) { - t.Errorf("%d: unexpected plural and singular: %v %v", i, plural, singular) - } - } -} - -func TestRESTMapperResourceSingularizer(t *testing.T) { - testGroupVersion := unversioned.GroupVersion{Group: "tgroup", Version: "test"} - - testCases := []struct { - Kind string - Plural string - Singular string - }{ - {Kind: "Pod", Plural: "pods", Singular: "pod"}, - {Kind: "ReplicationController", Plural: "replicationcontrollers", Singular: "replicationcontroller"}, - {Kind: "ImageRepository", Plural: "imagerepositories", Singular: "imagerepository"}, - {Kind: "Status", Plural: "statuses", Singular: "status"}, - - {Kind: "lowercase", Plural: "lowercases", Singular: "lowercase"}, - // TODO this test is broken. This updates to reflect actual behavior. Kinds are expected to be singular - // old (incorrect), coment: Don't add extra s if the original object is already plural - {Kind: "lowercases", Plural: "lowercaseses", Singular: "lowercases"}, - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper([]unversioned.GroupVersion{testGroupVersion}, fakeInterfaces) - // create singular/plural mapping - mapper.Add(testGroupVersion.WithKind(testCase.Kind), RESTScopeNamespace) - - singular, err := mapper.ResourceSingularizer(testCase.Plural) - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - } - if singular != testCase.Singular { - t.Errorf("%d: mismatched singular: got %v, expected %v", i, singular, testCase.Singular) - } - } -} - -func TestRESTMapperRESTMapping(t *testing.T) { - testGroup := "tgroup" - testGroupVersion := unversioned.GroupVersion{Group: testGroup, Version: "test"} - internalGroupVersion := unversioned.GroupVersion{Group: testGroup, Version: "test"} - - testCases := []struct { - Kind string - APIGroupVersions []unversioned.GroupVersion - DefaultVersions []unversioned.GroupVersion - - Resource string - ExpectedGroupVersion *unversioned.GroupVersion - Err bool - }{ - {Kind: "Unknown", Err: true}, - {Kind: "InternalObject", Err: true}, - - {DefaultVersions: []unversioned.GroupVersion{testGroupVersion}, Kind: "Unknown", Err: true}, - - {DefaultVersions: []unversioned.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []unversioned.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - {DefaultVersions: []unversioned.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []unversioned.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - - {DefaultVersions: []unversioned.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []unversioned.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - - {DefaultVersions: []unversioned.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []unversioned.GroupVersion{}, Resource: "internalobjects", ExpectedGroupVersion: &unversioned.GroupVersion{Group: testGroup, Version: "test"}}, - - {DefaultVersions: []unversioned.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []unversioned.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - - // TODO: add test for a resource that exists in one version but not another - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper(testCase.DefaultVersions, fakeInterfaces) - mapper.Add(internalGroupVersion.WithKind("InternalObject"), RESTScopeNamespace) - - preferredVersions := []string{} - for _, gv := range testCase.APIGroupVersions { - preferredVersions = append(preferredVersions, gv.Version) - } - gk := unversioned.GroupKind{Group: testGroup, Kind: testCase.Kind} - - mapping, err := mapper.RESTMapping(gk, preferredVersions...) - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err) - } - if hasErr { - continue - } - if mapping.Resource != testCase.Resource { - t.Errorf("%d: unexpected resource: %#v", i, mapping) - } - - if mapping.MetadataAccessor == nil || mapping.ObjectConvertor == nil { - t.Errorf("%d: missing codec and accessor: %#v", i, mapping) - } - - groupVersion := testCase.ExpectedGroupVersion - if groupVersion == nil { - groupVersion = &testCase.APIGroupVersions[0] - } - if mapping.GroupVersionKind.GroupVersion() != *groupVersion { - t.Errorf("%d: unexpected version: %#v", i, mapping) - } - - } -} - -func TestRESTMapperRESTMappingSelectsVersion(t *testing.T) { - expectedGroupVersion1 := unversioned.GroupVersion{Group: "tgroup", Version: "test1"} - expectedGroupVersion2 := unversioned.GroupVersion{Group: "tgroup", Version: "test2"} - expectedGroupVersion3 := unversioned.GroupVersion{Group: "tgroup", Version: "test3"} - internalObjectGK := unversioned.GroupKind{Group: "tgroup", Kind: "InternalObject"} - otherObjectGK := unversioned.GroupKind{Group: "tgroup", Kind: "OtherObject"} - - mapper := NewDefaultRESTMapper([]unversioned.GroupVersion{expectedGroupVersion1, expectedGroupVersion2}, fakeInterfaces) - mapper.Add(expectedGroupVersion1.WithKind("InternalObject"), RESTScopeNamespace) - mapper.Add(expectedGroupVersion2.WithKind("OtherObject"), RESTScopeNamespace) - - // pick default matching object kind based on search order - mapping, err := mapper.RESTMapping(otherObjectGK) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "otherobjects" || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion2 { - t.Errorf("unexpected mapping: %#v", mapping) - } - - mapping, err = mapper.RESTMapping(internalObjectGK) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "internalobjects" || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion1 { - t.Errorf("unexpected mapping: %#v", mapping) - } - - // mismatch of version - mapping, err = mapper.RESTMapping(internalObjectGK, expectedGroupVersion2.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion1.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - - // not in the search versions - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - - // explicit search order - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version, expectedGroupVersion1.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version, expectedGroupVersion2.Version) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "otherobjects" || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion2 { - t.Errorf("unexpected mapping: %#v", mapping) - } -} - -func TestRESTMapperReportsErrorOnBadVersion(t *testing.T) { - expectedGroupVersion1 := unversioned.GroupVersion{Group: "tgroup", Version: "test1"} - expectedGroupVersion2 := unversioned.GroupVersion{Group: "tgroup", Version: "test2"} - internalObjectGK := unversioned.GroupKind{Group: "tgroup", Kind: "InternalObject"} - - mapper := NewDefaultRESTMapper([]unversioned.GroupVersion{expectedGroupVersion1, expectedGroupVersion2}, unmatchedVersionInterfaces) - mapper.Add(expectedGroupVersion1.WithKind("InternalObject"), RESTScopeNamespace) - _, err := mapper.RESTMapping(internalObjectGK, expectedGroupVersion1.Version) - if err == nil { - t.Errorf("unexpected non-error") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta_test.go deleted file mode 100644 index e4a9657a0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/meta_test.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package api_test - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" -) - -var _ meta.Object = &api.ObjectMeta{} - -// TestFillObjectMetaSystemFields validates that system populated fields are set on an object -func TestFillObjectMetaSystemFields(t *testing.T) { - ctx := api.NewDefaultContext() - resource := api.ObjectMeta{} - api.FillObjectMetaSystemFields(ctx, &resource) - if resource.CreationTimestamp.Time.IsZero() { - t.Errorf("resource.CreationTimestamp is zero") - } else if len(resource.UID) == 0 { - t.Errorf("resource.UID missing") - } -} - -// TestHasObjectMetaSystemFieldValues validates that true is returned if and only if all fields are populated -func TestHasObjectMetaSystemFieldValues(t *testing.T) { - ctx := api.NewDefaultContext() - resource := api.ObjectMeta{} - if api.HasObjectMetaSystemFieldValues(&resource) { - t.Errorf("the resource does not have all fields yet populated, but incorrectly reports it does") - } - api.FillObjectMetaSystemFields(ctx, &resource) - if !api.HasObjectMetaSystemFieldValues(&resource) { - t.Errorf("the resource does have all fields populated, but incorrectly reports it does not") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/pod/util.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/pod/util.go index 8e70104aa..6b00c7e7d 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/pod/util.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/pod/util.go @@ -23,6 +23,18 @@ import ( "k8s.io/kubernetes/pkg/util/intstr" ) +const ( + // The annotation value is a string specifying the hostname to be used for the pod e.g 'my-webserver-1' + PodHostnameAnnotation = "pod.beta.kubernetes.io/hostname" + + // The annotation value is a string specifying the subdomain e.g. "my-web-service" + // If specified, on the the pod itself, ".my-web-service..svc." would resolve to + // the pod's IP. + // If there is a headless service named "my-web-service" in the same namespace as the pod, then, + // .my-web-service..svc." would be resolved by the cluster DNS Server. + PodSubdomainAnnotation = "pod.beta.kubernetes.io/subdomain" +) + // FindPort locates the container port for the given pod and portName. If the // targetPort is a number, use that. If the targetPort is a string, look that // string up in all named ports in all containers in the target pod. If no diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/pod/util_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/pod/util_test.go deleted file mode 100644 index 428f2bdcd..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/pod/util_test.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package pod - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/util/intstr" -) - -func TestFindPort(t *testing.T) { - testCases := []struct { - name string - containers []api.Container - port intstr.IntOrString - expected int - pass bool - }{{ - name: "valid int, no ports", - containers: []api.Container{{}}, - port: intstr.FromInt(93), - expected: 93, - pass: true, - }, { - name: "valid int, with ports", - containers: []api.Container{{Ports: []api.ContainerPort{{ - Name: "", - ContainerPort: 11, - Protocol: "TCP", - }, { - Name: "p", - ContainerPort: 22, - Protocol: "TCP", - }}}}, - port: intstr.FromInt(93), - expected: 93, - pass: true, - }, { - name: "valid str, no ports", - containers: []api.Container{{}}, - port: intstr.FromString("p"), - expected: 0, - pass: false, - }, { - name: "valid str, one ctr with ports", - containers: []api.Container{{Ports: []api.ContainerPort{{ - Name: "", - ContainerPort: 11, - Protocol: "UDP", - }, { - Name: "p", - ContainerPort: 22, - Protocol: "TCP", - }, { - Name: "q", - ContainerPort: 33, - Protocol: "TCP", - }}}}, - port: intstr.FromString("q"), - expected: 33, - pass: true, - }, { - name: "valid str, two ctr with ports", - containers: []api.Container{{}, {Ports: []api.ContainerPort{{ - Name: "", - ContainerPort: 11, - Protocol: "UDP", - }, { - Name: "p", - ContainerPort: 22, - Protocol: "TCP", - }, { - Name: "q", - ContainerPort: 33, - Protocol: "TCP", - }}}}, - port: intstr.FromString("q"), - expected: 33, - pass: true, - }} - - for _, tc := range testCases { - port, err := FindPort(&api.Pod{Spec: api.PodSpec{Containers: tc.containers}}, - &api.ServicePort{Protocol: "TCP", TargetPort: tc.port}) - if err != nil && tc.pass { - t.Errorf("unexpected error for %s: %v", tc.name, err) - } - if err == nil && !tc.pass { - t.Errorf("unexpected non-error for %s: %d", tc.name, port) - } - if port != tc.expected { - t.Errorf("wrong result for %s: expected %d, got %d", tc.name, tc.expected, port) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/ref_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/ref_test.go deleted file mode 100644 index 4f716672e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/ref_test.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package api - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -type FakeAPIObject struct{} - -func (obj *FakeAPIObject) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -type ExtensionAPIObject struct { - unversioned.TypeMeta - ObjectMeta -} - -func (obj *ExtensionAPIObject) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } - -func TestGetReference(t *testing.T) { - table := map[string]struct { - obj runtime.Object - ref *ObjectReference - fieldPath string - shouldErr bool - }{ - "pod": { - obj: &Pod{ - ObjectMeta: ObjectMeta{ - Name: "foo", - UID: "bar", - ResourceVersion: "42", - SelfLink: "/api/version1/pods/foo", - }, - }, - fieldPath: ".desiredState.containers[0]", - ref: &ObjectReference{ - Kind: "Pod", - APIVersion: "version1", - Name: "foo", - UID: "bar", - ResourceVersion: "42", - FieldPath: ".desiredState.containers[0]", - }, - }, - "serviceList": { - obj: &ServiceList{ - ListMeta: unversioned.ListMeta{ - ResourceVersion: "42", - SelfLink: "/api/version2/services", - }, - }, - ref: &ObjectReference{ - Kind: "ServiceList", - APIVersion: "version2", - ResourceVersion: "42", - }, - }, - "extensionAPIObject": { - obj: &ExtensionAPIObject{ - TypeMeta: unversioned.TypeMeta{ - Kind: "ExtensionAPIObject", - }, - ObjectMeta: ObjectMeta{ - Name: "foo", - UID: "bar", - ResourceVersion: "42", - SelfLink: "/custom_prefix/version1/extensions/foo", - }, - }, - ref: &ObjectReference{ - Kind: "ExtensionAPIObject", - APIVersion: "version1", - Name: "foo", - UID: "bar", - ResourceVersion: "42", - }, - }, - "badSelfLink": { - obj: &ServiceList{ - ListMeta: unversioned.ListMeta{ - ResourceVersion: "42", - SelfLink: "version2/services", - }, - }, - shouldErr: true, - }, - "error": { - obj: &FakeAPIObject{}, - ref: nil, - shouldErr: true, - }, - "errorNil": { - obj: nil, - ref: nil, - shouldErr: true, - }, - } - - for name, item := range table { - ref, err := GetPartialReference(item.obj, item.fieldPath) - if e, a := item.shouldErr, (err != nil); e != a { - t.Errorf("%v: expected %v, got %v, err %v", name, e, a, err) - continue - } - if e, a := item.ref, ref; !reflect.DeepEqual(e, a) { - t.Errorf("%v: expected %#v, got %#v", name, e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/quantity_example_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/quantity_example_test.go deleted file mode 100644 index 48c3d2555..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/quantity_example_test.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package resource_test - -import ( - "fmt" - - "k8s.io/kubernetes/pkg/api/resource" -) - -func ExampleFormat() { - memorySize := resource.NewQuantity(5*1024*1024*1024, resource.BinarySI) - fmt.Printf("memorySize = %v\n", memorySize) - - diskSize := resource.NewQuantity(5*1000*1000*1000, resource.DecimalSI) - fmt.Printf("diskSize = %v\n", diskSize) - - cores := resource.NewMilliQuantity(5300, resource.DecimalSI) - fmt.Printf("cores = %v\n", cores) - - // Output: - // memorySize = 5Gi - // diskSize = 5G - // cores = 5300m -} - -func ExampleMustParse() { - memorySize := resource.MustParse("5Gi") - fmt.Printf("memorySize = %v (%v)\n", memorySize.Value(), memorySize.Format) - - diskSize := resource.MustParse("5G") - fmt.Printf("diskSize = %v (%v)\n", diskSize.Value(), diskSize.Format) - - cores := resource.MustParse("5300m") - fmt.Printf("milliCores = %v (%v)\n", cores.MilliValue(), cores.Format) - - cores2 := resource.MustParse("5.4") - fmt.Printf("milliCores = %v (%v)\n", cores2.MilliValue(), cores2.Format) - - // Output: - // memorySize = 5368709120 (BinarySI) - // diskSize = 5000000000 (DecimalSI) - // milliCores = 5300 (DecimalSI) - // milliCores = 5400 (DecimalSI) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/quantity_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/quantity_test.go deleted file mode 100644 index bb62251e2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/quantity_test.go +++ /dev/null @@ -1,810 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package resource - -import ( - //"reflect" - "encoding/json" - "testing" - - fuzz "github.com/google/gofuzz" - "github.com/spf13/pflag" - "speter.net/go/exp/math/dec/inf" -) - -var ( - testQuantityFlag = QuantityFlag("quantityFlag", "1M", "dummy flag for testing the quantity flag mechanism") -) - -func dec(i int64, exponent int) *inf.Dec { - // See the below test-- scale is the negative of an exponent. - return inf.NewDec(i, inf.Scale(-exponent)) -} - -func TestDec(t *testing.T) { - table := []struct { - got *inf.Dec - expect string - }{ - {dec(1, 0), "1"}, - {dec(1, 1), "10"}, - {dec(5, 2), "500"}, - {dec(8, 3), "8000"}, - {dec(2, 0), "2"}, - {dec(1, -1), "0.1"}, - {dec(3, -2), "0.03"}, - {dec(4, -3), "0.004"}, - } - - for _, item := range table { - if e, a := item.expect, item.got.String(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - } -} - -// TestQuantityParseZero ensures that when a 0 quantity is passed, its string value is 0 -func TestQuantityParseZero(t *testing.T) { - zero := MustParse("0") - if expected, actual := "0", zero.String(); expected != actual { - t.Errorf("Expected %v, actual %v", expected, actual) - } -} - -// TestQuantityAddZeroPreservesSuffix verifies that a suffix is preserved -// independent of the order of operations when adding a zero and non-zero val -func TestQuantityAddZeroPreservesSuffix(t *testing.T) { - testValues := []string{"100m", "1Gi"} - zero := MustParse("0") - for _, testValue := range testValues { - value := MustParse(testValue) - v1 := *value.Copy() - // ensure non-zero + zero = non-zero (suffix preserved) - err := v1.Add(zero) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - // ensure zero + non-zero = non-zero (suffix preserved) - v2 := *zero.Copy() - err = v2.Add(value) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - // ensure we preserved the input value - if v1.String() != testValue { - t.Errorf("Expected %v, actual %v", testValue, v1.String()) - } - if v2.String() != testValue { - t.Errorf("Expected %v, actual %v", testValue, v2.String()) - } - } -} - -// TestQuantitySubZeroPreservesSuffix verifies that a suffix is preserved -// independent of the order of operations when subtracting a zero and non-zero val -func TestQuantitySubZeroPreservesSuffix(t *testing.T) { - testValues := []string{"100m", "1Gi"} - zero := MustParse("0") - for _, testValue := range testValues { - value := MustParse(testValue) - v1 := *value.Copy() - // ensure non-zero - zero = non-zero (suffix preserved) - err := v1.Sub(zero) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - // ensure we preserved the input value - if v1.String() != testValue { - t.Errorf("Expected %v, actual %v", testValue, v1.String()) - } - - // ensure zero - non-zero = -non-zero (suffix preserved) - v2 := *zero.Copy() - err = v2.Sub(value) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - negVal := *value.Copy() - err = negVal.Neg(negVal) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - if v2.String() != negVal.String() { - t.Errorf("Expected %v, actual %v", negVal.String(), v2.String()) - } - } -} - -// Verifies that you get 0 as canonical value if internal value is 0, and not 0 -func TestQuantityCanocicalizeZero(t *testing.T) { - val := MustParse("1000m") - x := val.Amount - y := dec(1, 0) - z := val.Amount.Sub(x, y) - zero := Quantity{z, DecimalSI} - if expected, actual := "0", zero.String(); expected != actual { - t.Errorf("Expected %v, actual %v", expected, actual) - } -} - -func TestQuantityCmp(t *testing.T) { - table := []struct { - x string - y string - expect int - }{ - {"0", "0", 0}, - {"100m", "50m", 1}, - {"50m", "100m", -1}, - {"10000T", "100Gi", 1}, - } - for _, testCase := range table { - q1 := MustParse(testCase.x) - q2 := MustParse(testCase.y) - if result := q1.Cmp(q2); result != testCase.expect { - t.Errorf("X: %v, Y: %v, Expected: %v, Actual: %v", testCase.x, testCase.y, testCase.expect, result) - } - } - - nils := []struct { - x *inf.Dec - y *inf.Dec - expect int - }{ - {dec(0, 0), dec(0, 0), 0}, - {nil, dec(0, 0), 0}, - {dec(0, 0), nil, 0}, - {nil, nil, 0}, - {nil, dec(10, 0), -1}, - {nil, dec(-10, 0), 1}, - {dec(10, 0), nil, 1}, - {dec(-10, 0), nil, -1}, - } - for _, nilCase := range nils { - q1 := Quantity{nilCase.x, DecimalSI} - q2 := Quantity{nilCase.y, DecimalSI} - if result := q1.Cmp(q2); result != nilCase.expect { - t.Errorf("X: %v, Y: %v, Expected: %v, Actual: %v", nilCase.x, nilCase.y, nilCase.expect, result) - } - } -} - -func TestQuantityParse(t *testing.T) { - table := []struct { - input string - expect Quantity - }{ - {"0", Quantity{dec(0, 0), DecimalSI}}, - {"0n", Quantity{dec(0, 0), DecimalSI}}, - {"0u", Quantity{dec(0, 0), DecimalSI}}, - {"0m", Quantity{dec(0, 0), DecimalSI}}, - {"0Ki", Quantity{dec(0, 0), BinarySI}}, - {"0k", Quantity{dec(0, 0), DecimalSI}}, - {"0Mi", Quantity{dec(0, 0), BinarySI}}, - {"0M", Quantity{dec(0, 0), DecimalSI}}, - {"0Gi", Quantity{dec(0, 0), BinarySI}}, - {"0G", Quantity{dec(0, 0), DecimalSI}}, - {"0Ti", Quantity{dec(0, 0), BinarySI}}, - {"0T", Quantity{dec(0, 0), DecimalSI}}, - - // Binary suffixes - {"1Ki", Quantity{dec(1024, 0), BinarySI}}, - {"8Ki", Quantity{dec(8*1024, 0), BinarySI}}, - {"7Mi", Quantity{dec(7*1024*1024, 0), BinarySI}}, - {"6Gi", Quantity{dec(6*1024*1024*1024, 0), BinarySI}}, - {"5Ti", Quantity{dec(5*1024*1024*1024*1024, 0), BinarySI}}, - {"4Pi", Quantity{dec(4*1024*1024*1024*1024*1024, 0), BinarySI}}, - {"3Ei", Quantity{dec(3*1024*1024*1024*1024*1024*1024, 0), BinarySI}}, - - {"10Ti", Quantity{dec(10*1024*1024*1024*1024, 0), BinarySI}}, - {"100Ti", Quantity{dec(100*1024*1024*1024*1024, 0), BinarySI}}, - - // Decimal suffixes - {"5n", Quantity{dec(5, -9), DecimalSI}}, - {"4u", Quantity{dec(4, -6), DecimalSI}}, - {"3m", Quantity{dec(3, -3), DecimalSI}}, - {"9", Quantity{dec(9, 0), DecimalSI}}, - {"8k", Quantity{dec(8, 3), DecimalSI}}, - {"7M", Quantity{dec(7, 6), DecimalSI}}, - {"6G", Quantity{dec(6, 9), DecimalSI}}, - {"5T", Quantity{dec(5, 12), DecimalSI}}, - {"40T", Quantity{dec(4, 13), DecimalSI}}, - {"300T", Quantity{dec(3, 14), DecimalSI}}, - {"2P", Quantity{dec(2, 15), DecimalSI}}, - {"1E", Quantity{dec(1, 18), DecimalSI}}, - - // Decimal exponents - {"1E-3", Quantity{dec(1, -3), DecimalExponent}}, - {"1e3", Quantity{dec(1, 3), DecimalExponent}}, - {"1E6", Quantity{dec(1, 6), DecimalExponent}}, - {"1e9", Quantity{dec(1, 9), DecimalExponent}}, - {"1E12", Quantity{dec(1, 12), DecimalExponent}}, - {"1e15", Quantity{dec(1, 15), DecimalExponent}}, - {"1E18", Quantity{dec(1, 18), DecimalExponent}}, - - // Nonstandard but still parsable - {"1e14", Quantity{dec(1, 14), DecimalExponent}}, - {"1e13", Quantity{dec(1, 13), DecimalExponent}}, - {"1e3", Quantity{dec(1, 3), DecimalExponent}}, - {"100.035k", Quantity{dec(100035, 0), DecimalSI}}, - - // Things that look like floating point - {"0.001", Quantity{dec(1, -3), DecimalSI}}, - {"0.0005k", Quantity{dec(5, -1), DecimalSI}}, - {"0.005", Quantity{dec(5, -3), DecimalSI}}, - {"0.05", Quantity{dec(5, -2), DecimalSI}}, - {"0.5", Quantity{dec(5, -1), DecimalSI}}, - {"0.00050k", Quantity{dec(5, -1), DecimalSI}}, - {"0.00500", Quantity{dec(5, -3), DecimalSI}}, - {"0.05000", Quantity{dec(5, -2), DecimalSI}}, - {"0.50000", Quantity{dec(5, -1), DecimalSI}}, - {"0.5e0", Quantity{dec(5, -1), DecimalExponent}}, - {"0.5e-1", Quantity{dec(5, -2), DecimalExponent}}, - {"0.5e-2", Quantity{dec(5, -3), DecimalExponent}}, - {"0.5e0", Quantity{dec(5, -1), DecimalExponent}}, - {"10.035M", Quantity{dec(10035, 3), DecimalSI}}, - - {"1.2e3", Quantity{dec(12, 2), DecimalExponent}}, - {"1.3E+6", Quantity{dec(13, 5), DecimalExponent}}, - {"1.40e9", Quantity{dec(14, 8), DecimalExponent}}, - {"1.53E12", Quantity{dec(153, 10), DecimalExponent}}, - {"1.6e15", Quantity{dec(16, 14), DecimalExponent}}, - {"1.7E18", Quantity{dec(17, 17), DecimalExponent}}, - - {"9.01", Quantity{dec(901, -2), DecimalSI}}, - {"8.1k", Quantity{dec(81, 2), DecimalSI}}, - {"7.123456M", Quantity{dec(7123456, 0), DecimalSI}}, - {"6.987654321G", Quantity{dec(6987654321, 0), DecimalSI}}, - {"5.444T", Quantity{dec(5444, 9), DecimalSI}}, - {"40.1T", Quantity{dec(401, 11), DecimalSI}}, - {"300.2T", Quantity{dec(3002, 11), DecimalSI}}, - {"2.5P", Quantity{dec(25, 14), DecimalSI}}, - {"1.01E", Quantity{dec(101, 16), DecimalSI}}, - - // Things that saturate/round - {"3.001n", Quantity{dec(4, -9), DecimalSI}}, - {"1.1E-9", Quantity{dec(2, -9), DecimalExponent}}, - {"0.0000000001", Quantity{dec(1, -9), DecimalSI}}, - {"0.0000000005", Quantity{dec(1, -9), DecimalSI}}, - {"0.00000000050", Quantity{dec(1, -9), DecimalSI}}, - {"0.5e-9", Quantity{dec(1, -9), DecimalExponent}}, - {"0.9n", Quantity{dec(1, -9), DecimalSI}}, - {"0.00000012345", Quantity{dec(124, -9), DecimalSI}}, - {"0.00000012354", Quantity{dec(124, -9), DecimalSI}}, - {"9Ei", Quantity{maxAllowed, BinarySI}}, - {"9223372036854775807Ki", Quantity{maxAllowed, BinarySI}}, - {"12E", Quantity{maxAllowed, DecimalSI}}, - - // We'll accept fractional binary stuff, too. - {"100.035Ki", Quantity{dec(10243584, -2), BinarySI}}, - {"0.5Mi", Quantity{dec(.5*1024*1024, 0), BinarySI}}, - {"0.05Gi", Quantity{dec(536870912, -1), BinarySI}}, - {"0.025Ti", Quantity{dec(274877906944, -1), BinarySI}}, - - // Things written by trolls - {"0.000000000001Ki", Quantity{dec(2, -9), DecimalSI}}, // rounds up, changes format - {".001", Quantity{dec(1, -3), DecimalSI}}, - {".0001k", Quantity{dec(100, -3), DecimalSI}}, - {"1.", Quantity{dec(1, 0), DecimalSI}}, - {"1.G", Quantity{dec(1, 9), DecimalSI}}, - } - - for _, item := range table { - got, err := ParseQuantity(item.input) - if err != nil { - t.Errorf("%v: unexpected error: %v", item.input, err) - continue - } - if e, a := item.expect.Amount, got.Amount; e.Cmp(a) != 0 { - t.Errorf("%v: expected %v, got %v", item.input, e, a) - } - if e, a := item.expect.Format, got.Format; e != a { - t.Errorf("%v: expected %#v, got %#v", item.input, e, a) - } - } - - // Try the negative version of everything - desired := &inf.Dec{} - for _, item := range table { - got, err := ParseQuantity("-" + item.input) - if err != nil { - t.Errorf("-%v: unexpected error: %v", item.input, err) - continue - } - desired.Neg(item.expect.Amount) - if e, a := desired, got.Amount; e.Cmp(a) != 0 { - t.Errorf("%v: expected %v, got %v", item.input, e, a) - } - if e, a := item.expect.Format, got.Format; e != a { - t.Errorf("%v: expected %#v, got %#v", item.input, e, a) - } - } - - // Try everything with an explicit + - for _, item := range table { - got, err := ParseQuantity("+" + item.input) - if err != nil { - t.Errorf("-%v: unexpected error: %v", item.input, err) - continue - } - if e, a := item.expect.Amount, got.Amount; e.Cmp(a) != 0 { - t.Errorf("%v: expected %v, got %v", item.input, e, a) - } - if e, a := item.expect.Format, got.Format; e != a { - t.Errorf("%v: expected %#v, got %#v", item.input, e, a) - } - } - - invalid := []string{ - "1.1.M", - "1+1.0M", - "0.1mi", - "0.1am", - "aoeu", - ".5i", - "1i", - "-3.01i", - } - for _, item := range invalid { - _, err := ParseQuantity(item) - if err == nil { - t.Errorf("%v parsed unexpectedly", item) - } - } -} - -func TestQuantityString(t *testing.T) { - table := []struct { - in Quantity - expect string - }{ - {Quantity{dec(1024*1024*1024, 0), BinarySI}, "1Gi"}, - {Quantity{dec(300*1024*1024, 0), BinarySI}, "300Mi"}, - {Quantity{dec(6*1024, 0), BinarySI}, "6Ki"}, - {Quantity{dec(1001*1024*1024*1024, 0), BinarySI}, "1001Gi"}, - {Quantity{dec(1024*1024*1024*1024, 0), BinarySI}, "1Ti"}, - {Quantity{dec(5, 0), BinarySI}, "5"}, - {Quantity{dec(500, -3), BinarySI}, "500m"}, - {Quantity{dec(1, 9), DecimalSI}, "1G"}, - {Quantity{dec(1000, 6), DecimalSI}, "1G"}, - {Quantity{dec(1000000, 3), DecimalSI}, "1G"}, - {Quantity{dec(1000000000, 0), DecimalSI}, "1G"}, - {Quantity{dec(1, -3), DecimalSI}, "1m"}, - {Quantity{dec(80, -3), DecimalSI}, "80m"}, - {Quantity{dec(1080, -3), DecimalSI}, "1080m"}, - {Quantity{dec(108, -2), DecimalSI}, "1080m"}, - {Quantity{dec(10800, -4), DecimalSI}, "1080m"}, - {Quantity{dec(300, 6), DecimalSI}, "300M"}, - {Quantity{dec(1, 12), DecimalSI}, "1T"}, - {Quantity{dec(1234567, 6), DecimalSI}, "1234567M"}, - {Quantity{dec(1234567, -3), BinarySI}, "1234567m"}, - {Quantity{dec(3, 3), DecimalSI}, "3k"}, - {Quantity{dec(1025, 0), BinarySI}, "1025"}, - {Quantity{dec(0, 0), DecimalSI}, "0"}, - {Quantity{dec(0, 0), BinarySI}, "0"}, - {Quantity{dec(1, 9), DecimalExponent}, "1e9"}, - {Quantity{dec(1, -3), DecimalExponent}, "1e-3"}, - {Quantity{dec(1, -9), DecimalExponent}, "1e-9"}, - {Quantity{dec(80, -3), DecimalExponent}, "80e-3"}, - {Quantity{dec(300, 6), DecimalExponent}, "300e6"}, - {Quantity{dec(1, 12), DecimalExponent}, "1e12"}, - {Quantity{dec(1, 3), DecimalExponent}, "1e3"}, - {Quantity{dec(3, 3), DecimalExponent}, "3e3"}, - {Quantity{dec(3, 3), DecimalSI}, "3k"}, - {Quantity{dec(0, 0), DecimalExponent}, "0"}, - {Quantity{dec(1, -9), DecimalSI}, "1n"}, - {Quantity{dec(80, -9), DecimalSI}, "80n"}, - {Quantity{dec(1080, -9), DecimalSI}, "1080n"}, - {Quantity{dec(108, -8), DecimalSI}, "1080n"}, - {Quantity{dec(10800, -10), DecimalSI}, "1080n"}, - {Quantity{dec(1, -6), DecimalSI}, "1u"}, - {Quantity{dec(80, -6), DecimalSI}, "80u"}, - {Quantity{dec(1080, -6), DecimalSI}, "1080u"}, - } - for _, item := range table { - got := item.in.String() - if e, a := item.expect, got; e != a { - t.Errorf("%#v: expected %v, got %v", item.in, e, a) - } - } - desired := &inf.Dec{} // Avoid modifying the values in the table. - for _, item := range table { - if item.in.Amount.Cmp(decZero) == 0 { - // Don't expect it to print "-0" ever - continue - } - q := item.in - q.Amount = desired.Neg(q.Amount) - if e, a := "-"+item.expect, q.String(); e != a { - t.Errorf("%#v: expected %v, got %v", item.in, e, a) - } - } -} - -func TestQuantityParseEmit(t *testing.T) { - table := []struct { - in string - expect string - }{ - {"1Ki", "1Ki"}, - {"1Mi", "1Mi"}, - {"1Gi", "1Gi"}, - {"1024Mi", "1Gi"}, - {"1000M", "1G"}, - {".001Ki", "1024m"}, - {".000001Ki", "1024u"}, - {".000000001Ki", "1024n"}, - {".000000000001Ki", "2n"}, - } - - for _, item := range table { - q, err := ParseQuantity(item.in) - if err != nil { - t.Errorf("Couldn't parse %v", item.in) - continue - } - if e, a := item.expect, q.String(); e != a { - t.Errorf("%#v: expected %v, got %v", item.in, e, a) - } - } - for _, item := range table { - q, err := ParseQuantity("-" + item.in) - if err != nil { - t.Errorf("Couldn't parse %v", item.in) - continue - } - if q.Amount.Cmp(decZero) == 0 { - continue - } - if e, a := "-"+item.expect, q.String(); e != a { - t.Errorf("%#v: expected %v, got %v", item.in, e, a) - } - } -} - -var fuzzer = fuzz.New().Funcs( - func(q *Quantity, c fuzz.Continue) { - q.Amount = &inf.Dec{} - if c.RandBool() { - q.Format = BinarySI - if c.RandBool() { - q.Amount.SetScale(0) - q.Amount.SetUnscaled(c.Int63()) - return - } - // Be sure to test cases like 1Mi - q.Amount.SetScale(0) - q.Amount.SetUnscaled(c.Int63n(1024) << uint(10*c.Intn(5))) - return - } - if c.RandBool() { - q.Format = DecimalSI - } else { - q.Format = DecimalExponent - } - if c.RandBool() { - q.Amount.SetScale(inf.Scale(c.Intn(4))) - q.Amount.SetUnscaled(c.Int63()) - return - } - // Be sure to test cases like 1M - q.Amount.SetScale(inf.Scale(3 - c.Intn(15))) - q.Amount.SetUnscaled(c.Int63n(1000)) - }, -) - -func TestJSON(t *testing.T) { - for i := 0; i < 500; i++ { - q := &Quantity{} - fuzzer.Fuzz(q) - b, err := json.Marshal(q) - if err != nil { - t.Errorf("error encoding %v", q) - } - q2 := &Quantity{} - err = json.Unmarshal(b, q2) - if err != nil { - t.Errorf("%v: error decoding %v", q, string(b)) - } - if q2.Amount.Cmp(q.Amount) != 0 { - t.Errorf("Expected equal: %v, %v (json was '%v')", q, q2, string(b)) - } - } -} - -func TestMilliNewSet(t *testing.T) { - table := []struct { - value int64 - format Format - expect string - exact bool - }{ - {1, DecimalSI, "1m", true}, - {1000, DecimalSI, "1", true}, - {1234000, DecimalSI, "1234", true}, - {1024, BinarySI, "1024m", false}, // Format changes - {1000000, "invalidFormatDefaultsToExponent", "1e3", true}, - {1024 * 1024, BinarySI, "1048576m", false}, // Format changes - } - - for _, item := range table { - q := NewMilliQuantity(item.value, item.format) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Expected %v, got %v; %#v", e, a, q) - } - if !item.exact { - continue - } - q2, err := ParseQuantity(q.String()) - if err != nil { - t.Errorf("Round trip failed on %v", q) - } - if e, a := item.value, q2.MilliValue(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } - - for _, item := range table { - q := NewQuantity(0, item.format) - q.SetMilli(item.value) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Set: Expected %v, got %v; %#v", e, a, q) - } - } -} - -func TestNewSet(t *testing.T) { - table := []struct { - value int64 - format Format - expect string - }{ - {1, DecimalSI, "1"}, - {1000, DecimalSI, "1k"}, - {1234000, DecimalSI, "1234k"}, - {1024, BinarySI, "1Ki"}, - {1000000, "invalidFormatDefaultsToExponent", "1e6"}, - {1024 * 1024, BinarySI, "1Mi"}, - } - - for _, item := range table { - q := NewQuantity(item.value, item.format) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Expected %v, got %v; %#v", e, a, q) - } - q2, err := ParseQuantity(q.String()) - if err != nil { - t.Errorf("Round trip failed on %v", q) - } - if e, a := item.value, q2.Value(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } - - for _, item := range table { - q := NewQuantity(0, item.format) - q.Set(item.value) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Set: Expected %v, got %v; %#v", e, a, q) - } - } -} - -func TestNewScaledSet(t *testing.T) { - table := []struct { - value int64 - scale Scale - expect string - }{ - {1, Nano, "1n"}, - {1000, Nano, "1u"}, - {1, Micro, "1u"}, - {1000, Micro, "1m"}, - {1, Milli, "1m"}, - {1000, Milli, "1"}, - {1, 0, "1"}, - {0, Nano, "0"}, - {0, Micro, "0"}, - {0, Milli, "0"}, - {0, 0, "0"}, - } - - for _, item := range table { - q := NewScaledQuantity(item.value, item.scale) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Expected %v, got %v; %#v", e, a, q) - } - q2, err := ParseQuantity(q.String()) - if err != nil { - t.Errorf("Round trip failed on %v", q) - } - if e, a := item.value, q2.ScaledValue(item.scale); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - q3 := NewQuantity(0, DecimalSI) - q3.SetScaled(item.value, item.scale) - if q.Cmp(*q3) != 0 { - t.Errorf("Expected %v and %v to be equal", q, q3) - } - } -} - -func TestScaledValue(t *testing.T) { - table := []struct { - fromScale Scale - toScale Scale - expected int64 - }{ - {Nano, Nano, 1}, - {Nano, Micro, 1}, - {Nano, Milli, 1}, - {Nano, 0, 1}, - {Micro, Nano, 1000}, - {Micro, Micro, 1}, - {Micro, Milli, 1}, - {Micro, 0, 1}, - {Milli, Nano, 1000 * 1000}, - {Milli, Micro, 1000}, - {Milli, Milli, 1}, - {Milli, 0, 1}, - {0, Nano, 1000 * 1000 * 1000}, - {0, Micro, 1000 * 1000}, - {0, Milli, 1000}, - {0, 0, 1}, - } - - for _, item := range table { - q := NewScaledQuantity(1, item.fromScale) - if e, a := item.expected, q.ScaledValue(item.toScale); e != a { - t.Errorf("%v to %v: Expected %v, got %v", item.fromScale, item.toScale, e, a) - } - } -} - -func TestUninitializedNoCrash(t *testing.T) { - var q Quantity - - q.Value() - q.MilliValue() - q.Copy() - _ = q.String() - q.MarshalJSON() -} - -func TestCopy(t *testing.T) { - q := NewQuantity(5, DecimalSI) - c := q.Copy() - c.Set(6) - if q.Value() == 6 { - t.Errorf("Copy didn't") - } -} - -func TestQFlagSet(t *testing.T) { - qf := qFlag{&Quantity{}} - qf.Set("1Ki") - if e, a := "1Ki", qf.String(); e != a { - t.Errorf("Unexpected result %v != %v", e, a) - } -} - -func TestQFlagIsPFlag(t *testing.T) { - var pfv pflag.Value = qFlag{} - if e, a := "quantity", pfv.Type(); e != a { - t.Errorf("Unexpected result %v != %v", e, a) - } -} - -func TestSub(t *testing.T) { - tests := []struct { - a Quantity - b Quantity - expected Quantity - }{ - {Quantity{dec(10, 0), DecimalSI}, Quantity{dec(1, 1), DecimalSI}, Quantity{dec(0, 0), DecimalSI}}, - {Quantity{dec(10, 0), DecimalSI}, Quantity{dec(1, 0), BinarySI}, Quantity{dec(9, 0), DecimalSI}}, - {Quantity{dec(10, 0), BinarySI}, Quantity{dec(1, 0), DecimalSI}, Quantity{dec(9, 0), BinarySI}}, - {Quantity{nil, DecimalSI}, Quantity{dec(50, 0), DecimalSI}, Quantity{dec(-50, 0), DecimalSI}}, - {Quantity{dec(50, 0), DecimalSI}, Quantity{nil, DecimalSI}, Quantity{dec(50, 0), DecimalSI}}, - {Quantity{nil, DecimalSI}, Quantity{nil, DecimalSI}, Quantity{dec(0, 0), DecimalSI}}, - } - - for i, test := range tests { - test.a.Sub(test.b) - if test.a.Cmp(test.expected) != 0 { - t.Errorf("[%d] Expected %q, got %q", i, test.expected.String(), test.a.String()) - } - } -} - -func TestNeg(t *testing.T) { - tests := []struct { - a Quantity - b Quantity - expected Quantity - }{ - { - a: Quantity{dec(0, 0), DecimalSI}, - b: Quantity{dec(10, 0), DecimalSI}, - expected: Quantity{dec(-10, 0), DecimalSI}, - }, - { - a: Quantity{dec(0, 0), DecimalSI}, - b: Quantity{dec(-10, 0), DecimalSI}, - expected: Quantity{dec(10, 0), DecimalSI}, - }, - { - a: Quantity{dec(0, 0), DecimalSI}, - b: Quantity{dec(10, 0), BinarySI}, - expected: Quantity{dec(-10, 0), BinarySI}, - }, - { - a: Quantity{dec(0, 0), DecimalSI}, - b: Quantity{dec(0, 0), BinarySI}, - expected: Quantity{dec(0, 0), BinarySI}, - }, - { - a: Quantity{}, - b: Quantity{dec(10, 0), BinarySI}, - expected: Quantity{dec(-10, 0), BinarySI}, - }, - { - a: Quantity{dec(10, 0), BinarySI}, - b: Quantity{}, - expected: Quantity{}, - }, - { - a: Quantity{dec(10, 0), BinarySI}, - b: Quantity{Format: DecimalSI}, - expected: Quantity{dec(0, 0), DecimalSI}, - }, - } - - for i, test := range tests { - test.a.Neg(test.b) - // ensure value is same - if test.a.Cmp(test.expected) != 0 { - t.Errorf("[%d] Expected %q, got %q", i, test.expected.String(), test.a.String()) - } - // ensure format is updated - if test.a.Format != test.expected.Format { - t.Errorf("[%d] Expected format %v, got format %v", i, test.expected.Format, test.a.Format) - } - } -} - -func TestAdd(t *testing.T) { - tests := []struct { - a Quantity - b Quantity - expected Quantity - }{ - {Quantity{dec(10, 0), DecimalSI}, Quantity{dec(1, 1), DecimalSI}, Quantity{dec(20, 0), DecimalSI}}, - {Quantity{dec(10, 0), DecimalSI}, Quantity{dec(1, 0), BinarySI}, Quantity{dec(11, 0), DecimalSI}}, - {Quantity{dec(10, 0), BinarySI}, Quantity{dec(1, 0), DecimalSI}, Quantity{dec(11, 0), BinarySI}}, - {Quantity{nil, DecimalSI}, Quantity{dec(50, 0), DecimalSI}, Quantity{dec(50, 0), DecimalSI}}, - {Quantity{dec(50, 0), DecimalSI}, Quantity{nil, DecimalSI}, Quantity{dec(50, 0), DecimalSI}}, - {Quantity{nil, DecimalSI}, Quantity{nil, DecimalSI}, Quantity{dec(0, 0), DecimalSI}}, - } - - for i, test := range tests { - test.a.Add(test.b) - if test.a.Cmp(test.expected) != 0 { - t.Errorf("[%d] Expected %q, got %q", i, test.expected.String(), test.a.String()) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/scale_int_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/scale_int_test.go deleted file mode 100644 index 1b4390e55..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource/scale_int_test.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package resource - -import ( - "math" - "math/big" - "testing" -) - -func TestScaledValueInternal(t *testing.T) { - tests := []struct { - unscaled *big.Int - scale int - newScale int - - want int64 - }{ - // remain scale - {big.NewInt(1000), 0, 0, 1000}, - - // scale down - {big.NewInt(1000), 0, -3, 1}, - {big.NewInt(1000), 3, 0, 1}, - {big.NewInt(0), 3, 0, 0}, - - // always round up - {big.NewInt(999), 3, 0, 1}, - {big.NewInt(500), 3, 0, 1}, - {big.NewInt(499), 3, 0, 1}, - {big.NewInt(1), 3, 0, 1}, - // large scaled value does not lose precision - {big.NewInt(0).Sub(maxInt64, bigOne), 1, 0, (math.MaxInt64-1)/10 + 1}, - // large intermidiate result. - {big.NewInt(1).Exp(big.NewInt(10), big.NewInt(100), nil), 100, 0, 1}, - - // scale up - {big.NewInt(0), 0, 3, 0}, - {big.NewInt(1), 0, 3, 1000}, - {big.NewInt(1), -3, 0, 1000}, - {big.NewInt(1000), -3, 2, 100000000}, - {big.NewInt(0).Div(big.NewInt(math.MaxInt64), bigThousand), 0, 3, - (math.MaxInt64 / 1000) * 1000}, - } - - for i, tt := range tests { - old := (&big.Int{}).Set(tt.unscaled) - got := scaledValue(tt.unscaled, tt.scale, tt.newScale) - if got != tt.want { - t.Errorf("#%d: got = %v, want %v", i, got, tt.want) - } - if tt.unscaled.Cmp(old) != 0 { - t.Errorf("#%d: unscaled = %v, want %v", i, tt.unscaled, old) - } - } -} - -func BenchmarkScaledValueSmall(b *testing.B) { - s := big.NewInt(1000) - for i := 0; i < b.N; i++ { - scaledValue(s, 3, 0) - } -} - -func BenchmarkScaledValueLarge(b *testing.B) { - s := big.NewInt(math.MaxInt64) - s.Mul(s, big.NewInt(1000)) - for i := 0; i < b.N; i++ { - scaledValue(s, 10, 0) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource_helpers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource_helpers_test.go deleted file mode 100644 index 12c0ce7db..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/resource_helpers_test.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package api - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api/resource" -) - -func TestResourceHelpers(t *testing.T) { - cpuLimit := resource.MustParse("10") - memoryLimit := resource.MustParse("10G") - resourceSpec := ResourceRequirements{ - Limits: ResourceList{ - "cpu": cpuLimit, - "memory": memoryLimit, - "kube.io/storage": memoryLimit, - }, - } - if res := resourceSpec.Limits.Cpu(); *res != cpuLimit { - t.Errorf("expected cpulimit %v, got %v", cpuLimit, res) - } - if res := resourceSpec.Limits.Memory(); *res != memoryLimit { - t.Errorf("expected memorylimit %v, got %v", memoryLimit, res) - } - resourceSpec = ResourceRequirements{ - Limits: ResourceList{ - "memory": memoryLimit, - "kube.io/storage": memoryLimit, - }, - } - if res := resourceSpec.Limits.Cpu(); res.Value() != 0 { - t.Errorf("expected cpulimit %v, got %v", 0, res) - } - if res := resourceSpec.Limits.Memory(); *res != memoryLimit { - t.Errorf("expected memorylimit %v, got %v", memoryLimit, res) - } -} - -func TestDefaultResourceHelpers(t *testing.T) { - resourceList := ResourceList{} - if resourceList.Cpu().Format != resource.DecimalSI { - t.Errorf("expected %v, actual %v", resource.DecimalSI, resourceList.Cpu().Format) - } - if resourceList.Memory().Format != resource.BinarySI { - t.Errorf("expected %v, actual %v", resource.BinarySI, resourceList.Memory().Format) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/create.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/create.go deleted file mode 100644 index 4e3a8938b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/create.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package rest - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -// RESTCreateStrategy defines the minimum validation, accepted input, and -// name generation behavior to create an object that follows Kubernetes -// API conventions. -type RESTCreateStrategy interface { - runtime.ObjectTyper - // The name generate is used when the standard GenerateName field is set. - // The NameGenerator will be invoked prior to validation. - api.NameGenerator - - // NamespaceScoped returns true if the object must be within a namespace. - NamespaceScoped() bool - // PrepareForCreate is invoked on create before validation to normalize - // the object. For example: remove fields that are not to be persisted, - // sort order-insensitive list fields, etc. This should not remove fields - // whose presence would be considered a validation error. - PrepareForCreate(obj runtime.Object) - // Validate is invoked after default fields in the object have been filled in before - // the object is persisted. This method should not mutate the object. - Validate(ctx api.Context, obj runtime.Object) field.ErrorList - // Canonicalize is invoked after validation has succeeded but before the - // object has been persisted. This method may mutate the object. - Canonicalize(obj runtime.Object) -} - -// BeforeCreate ensures that common operations for all resources are performed on creation. It only returns -// errors that can be converted to api.Status. It invokes PrepareForCreate, then GenerateName, then Validate. -// It returns nil if the object should be created. -func BeforeCreate(strategy RESTCreateStrategy, ctx api.Context, obj runtime.Object) error { - objectMeta, kind, kerr := objectMetaAndKind(strategy, obj) - if kerr != nil { - return kerr - } - - if strategy.NamespaceScoped() { - if !api.ValidNamespace(ctx, objectMeta) { - return errors.NewBadRequest("the namespace of the provided object does not match the namespace sent on the request") - } - } else { - objectMeta.Namespace = api.NamespaceNone - } - objectMeta.DeletionTimestamp = nil - objectMeta.DeletionGracePeriodSeconds = nil - strategy.PrepareForCreate(obj) - api.FillObjectMetaSystemFields(ctx, objectMeta) - api.GenerateName(strategy, objectMeta) - - if errs := strategy.Validate(ctx, obj); len(errs) > 0 { - return errors.NewInvalid(kind.GroupKind(), objectMeta.Name, errs) - } - - // Custom validation (including name validation) passed - // Now run common validation on object meta - // Do this *after* custom validation so that specific error messages are shown whenever possible - if errs := validation.ValidateObjectMeta(objectMeta, strategy.NamespaceScoped(), validation.ValidatePathSegmentName, field.NewPath("metadata")); len(errs) > 0 { - return errors.NewInvalid(kind.GroupKind(), objectMeta.Name, errs) - } - - strategy.Canonicalize(obj) - - return nil -} - -// CheckGeneratedNameError checks whether an error that occurred creating a resource is due -// to generation being unable to pick a valid name. -func CheckGeneratedNameError(strategy RESTCreateStrategy, err error, obj runtime.Object) error { - if !errors.IsAlreadyExists(err) { - return err - } - - objectMeta, kind, kerr := objectMetaAndKind(strategy, obj) - if kerr != nil { - return kerr - } - - if len(objectMeta.GenerateName) == 0 { - return err - } - - return errors.NewServerTimeoutForKind(kind.GroupKind(), "POST", 0) -} - -// objectMetaAndKind retrieves kind and ObjectMeta from a runtime object, or returns an error. -func objectMetaAndKind(typer runtime.ObjectTyper, obj runtime.Object) (*api.ObjectMeta, unversioned.GroupVersionKind, error) { - objectMeta, err := api.ObjectMetaFor(obj) - if err != nil { - return nil, unversioned.GroupVersionKind{}, errors.NewInternalError(err) - } - kind, err := typer.ObjectKind(obj) - if err != nil { - return nil, unversioned.GroupVersionKind{}, errors.NewInternalError(err) - } - return objectMeta, kind, nil -} - -// NamespaceScopedStrategy has a method to tell if the object must be in a namespace. -type NamespaceScopedStrategy interface { - // NamespaceScoped returns if the object must be in a namespace. - NamespaceScoped() bool -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/delete.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/delete.go deleted file mode 100644 index c05f3446d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/delete.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package rest - -import ( - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -// RESTDeleteStrategy defines deletion behavior on an object that follows Kubernetes -// API conventions. -type RESTDeleteStrategy interface { - runtime.ObjectTyper - - // CheckGracefulDelete should return true if the object can be gracefully deleted and set - // any default values on the DeleteOptions. - CheckGracefulDelete(obj runtime.Object, options *api.DeleteOptions) bool -} - -// BeforeDelete tests whether the object can be gracefully deleted. If graceful is set the object -// 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. -func BeforeDelete(strategy RESTDeleteStrategy, ctx api.Context, obj runtime.Object, options *api.DeleteOptions) (graceful, gracefulPending bool, err error) { - if strategy == nil { - return false, false, nil - } - objectMeta, _, kerr := objectMetaAndKind(strategy, obj) - if kerr != nil { - return false, false, kerr - } - - // if the object is already being deleted - 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, - // so we force deletion immediately - if objectMeta.DeletionGracePeriodSeconds == nil { - return false, false, nil - } - // only a shorter grace period may be provided by a user - if options.GracePeriodSeconds != nil { - period := int64(*options.GracePeriodSeconds) - if period > *objectMeta.DeletionGracePeriodSeconds { - return false, true, nil - } - now := unversioned.NewTime(unversioned.Now().Add(time.Second * time.Duration(*options.GracePeriodSeconds))) - objectMeta.DeletionTimestamp = &now - objectMeta.DeletionGracePeriodSeconds = &period - options.GracePeriodSeconds = &period - return true, false, nil - } - // graceful deletion is pending, do nothing - options.GracePeriodSeconds = objectMeta.DeletionGracePeriodSeconds - return false, true, nil - } - - if !strategy.CheckGracefulDelete(obj, options) { - return false, false, nil - } - now := unversioned.NewTime(unversioned.Now().Add(time.Second * time.Duration(*options.GracePeriodSeconds))) - objectMeta.DeletionTimestamp = &now - objectMeta.DeletionGracePeriodSeconds = options.GracePeriodSeconds - return true, false, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/doc.go deleted file mode 100644 index 8fed0e9f4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package rest defines common logic around changes to Kubernetes resources. -package rest diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/export.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/export.go deleted file mode 100644 index e12f65de3..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/export.go +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package rest - -import ( - "k8s.io/kubernetes/pkg/runtime" -) - -// RESTExportStrategy is the interface that defines how to export a Kubernetes object -type RESTExportStrategy interface { - // Export strips fields that can not be set by the user. If 'exact' is false - // fields specific to the cluster are also stripped - Export(obj runtime.Object, exact bool) error -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/rest.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/rest.go deleted file mode 100644 index d07023dad..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/rest.go +++ /dev/null @@ -1,293 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package rest - -import ( - "io" - "net/http" - "net/url" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/watch" -) - -//TODO: -// Storage interfaces need to be separated into two groups; those that operate -// on collections and those that operate on individually named items. -// Collection interfaces: -// (Method: Current -> Proposed) -// GET: Lister -> CollectionGetter -// WATCH: Watcher -> CollectionWatcher -// CREATE: Creater -> CollectionCreater -// DELETE: (n/a) -> CollectionDeleter -// UPDATE: (n/a) -> CollectionUpdater -// -// Single item interfaces: -// (Method: Current -> Proposed) -// GET: Getter -> NamedGetter -// WATCH: (n/a) -> NamedWatcher -// CREATE: (n/a) -> NamedCreater -// DELETE: Deleter -> NamedDeleter -// UPDATE: Update -> NamedUpdater - -// Storage is a generic interface for RESTful storage services. -// Resources which are exported to the RESTful API of apiserver need to implement this interface. It is expected -// that objects may implement any of the below interfaces. -type Storage interface { - // New returns an empty object that can be used with Create and Update after request data has been put into it. - // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) - New() runtime.Object -} - -// KindProvider specifies a different kind for its API than for its internal storage. This is necessary for external -// objects that are not compiled into the api server. For such objects, there is no in-memory representation for -// the object, so they must be represented as generic objects (e.g. RawJSON), but when we present the object as part of -// API discovery we want to present the specific kind, not the generic internal representation. -type KindProvider interface { - Kind() string -} - -// Lister is an object that can retrieve resources that match the provided field and label criteria. -type Lister interface { - // NewList returns an empty object that can be used with the List call. - // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) - NewList() runtime.Object - // List selects resources in the storage which match to the selector. 'options' can be nil. - List(ctx api.Context, options *api.ListOptions) (runtime.Object, error) -} - -// Exporter is an object that knows how to strip a RESTful resource for export -type Exporter interface { - // Export an object. Fields that are not user specified (e.g. Status, ObjectMeta.ResourceVersion) are stripped out - // Returns the stripped object. If 'exact' is true, fields that are specific to the cluster (e.g. namespace) are - // retained, otherwise they are stripped also. - Export(ctx api.Context, name string, opts unversioned.ExportOptions) (runtime.Object, error) -} - -// Getter is an object that can retrieve a named RESTful resource. -type Getter interface { - // Get finds a resource in the storage by name and returns it. - // Although it can return an arbitrary error value, IsNotFound(err) is true for the - // returned error value err when the specified resource is not found. - Get(ctx api.Context, name string) (runtime.Object, error) -} - -// GetterWithOptions is an object that retrieve a named RESTful resource and takes -// additional options on the get request. It allows a caller to also receive the -// subpath of the GET request. -type GetterWithOptions interface { - // Get finds a resource in the storage by name and returns it. - // Although it can return an arbitrary error value, IsNotFound(err) is true for the - // returned error value err when the specified resource is not found. - // The options object passed to it is of the same type returned by the NewGetOptions - // method. - Get(ctx api.Context, name string, options runtime.Object) (runtime.Object, error) - - // NewGetOptions returns an empty options object that will be used to pass - // options to the Get method. It may return a bool and a string, if true, the - // value of the request path below the object will be included as the named - // string in the serialization of the runtime object. E.g., returning "path" - // will convert the trailing request scheme value to "path" in the map[string][]string - // passed to the converter. - NewGetOptions() (runtime.Object, bool, string) -} - -// Deleter is an object that can delete a named RESTful resource. -type Deleter interface { - // Delete finds a resource in the storage and deletes it. - // Although it can return an arbitrary error value, IsNotFound(err) is true for the - // returned error value err when the specified resource is not found. - // Delete *may* return the object that was deleted, or a status object indicating additional - // information about deletion. - Delete(ctx api.Context, name string) (runtime.Object, error) -} - -// GracefulDeleter knows how to pass deletion options to allow delayed deletion of a -// RESTful object. -type GracefulDeleter interface { - // Delete finds a resource in the storage and deletes it. - // If options are provided, the resource will attempt to honor them or return an invalid - // request error. - // Although it can return an arbitrary error value, IsNotFound(err) is true for the - // returned error value err when the specified resource is not found. - // Delete *may* return the object that was deleted, or a status object indicating additional - // information about deletion. - Delete(ctx api.Context, name string, options *api.DeleteOptions) (runtime.Object, error) -} - -// GracefulDeleteAdapter adapts the Deleter interface to GracefulDeleter -type GracefulDeleteAdapter struct { - Deleter -} - -// Delete implements RESTGracefulDeleter in terms of Deleter -func (w GracefulDeleteAdapter) Delete(ctx api.Context, name string, options *api.DeleteOptions) (runtime.Object, error) { - return w.Deleter.Delete(ctx, name) -} - -// CollectionDeleter is an object that can delete a collection -// of RESTful resources. -type CollectionDeleter interface { - // DeleteCollection selects all resources in the storage matching given 'listOptions' - // and deletes them. If 'options' are provided, the resource will attempt to honor - // them or return an invalid request error. - // DeleteCollection may not be atomic - i.e. it may delete some objects and still - // return an error after it. On success, returns a list of deleted objects. - DeleteCollection(ctx api.Context, options *api.DeleteOptions, listOptions *api.ListOptions) (runtime.Object, error) -} - -// Creater is an object that can create an instance of a RESTful object. -type Creater interface { - // New returns an empty object that can be used with Create after request data has been put into it. - // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) - New() runtime.Object - - // Create creates a new version of a resource. - Create(ctx api.Context, obj runtime.Object) (runtime.Object, error) -} - -// NamedCreater is an object that can create an instance of a RESTful object using a name parameter. -type NamedCreater interface { - // New returns an empty object that can be used with Create after request data has been put into it. - // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) - New() runtime.Object - - // Create creates a new version of a resource. It expects a name parameter from the path. - // This is needed for create operations on subresources which include the name of the parent - // resource in the path. - Create(ctx api.Context, name string, obj runtime.Object) (runtime.Object, error) -} - -// Updater is an object that can update an instance of a RESTful object. -type Updater interface { - // New returns an empty object that can be used with Update after request data has been put into it. - // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) - New() runtime.Object - - // Update finds a resource in the storage and updates it. Some implementations - // may allow updates creates the object - they should set the created boolean - // to true. - Update(ctx api.Context, obj runtime.Object) (runtime.Object, bool, error) -} - -// CreaterUpdater is a storage object that must support both create and update. -// Go prevents embedded interfaces that implement the same method. -type CreaterUpdater interface { - Creater - Update(ctx api.Context, obj runtime.Object) (runtime.Object, bool, error) -} - -// CreaterUpdater must satisfy the Updater interface. -var _ Updater = CreaterUpdater(nil) - -// Patcher is a storage object that supports both get and update. -type Patcher interface { - Getter - Updater -} - -// Watcher should be implemented by all Storage objects that -// want to offer the ability to watch for changes through the watch api. -type Watcher interface { - // 'label' selects on labels; 'field' selects on the object's fields. Not all fields - // are supported; an error should be returned if 'field' tries to select on a field that - // isn't supported. 'resourceVersion' allows for continuing/starting a watch at a - // particular version. - Watch(ctx api.Context, options *api.ListOptions) (watch.Interface, error) -} - -// StandardStorage is an interface covering the common verbs. Provided for testing whether a -// resource satisfies the normal storage methods. Use Storage when passing opaque storage objects. -type StandardStorage interface { - Getter - Lister - CreaterUpdater - GracefulDeleter - CollectionDeleter - Watcher -} - -// Redirector know how to return a remote resource's location. -type Redirector interface { - // ResourceLocation should return the remote location of the given resource, and an optional transport to use to request it, or an error. - ResourceLocation(ctx api.Context, id string) (remoteLocation *url.URL, transport http.RoundTripper, err error) -} - -// Responder abstracts the normal response behavior for a REST method and is passed to callers that -// may wish to handle the response directly in some cases, but delegate to the normal error or object -// behavior in other cases. -type Responder interface { - // Object writes the provided object to the response. Invoking this method multiple times is undefined. - Object(statusCode int, obj runtime.Object) - // Error writes the provided error to the response. This method may only be invoked once. - Error(err error) -} - -// Connecter is a storage object that responds to a connection request. -type Connecter interface { - // Connect returns an http.Handler that will handle the request/response for a given API invocation. - // The provided responder may be used for common API responses. The responder will write both status - // code and body, so the ServeHTTP method should exit after invoking the responder. The Handler will - // be used for a single API request and then discarded. The Responder is guaranteed to write to the - // same http.ResponseWriter passed to ServeHTTP. - Connect(ctx api.Context, id string, options runtime.Object, r Responder) (http.Handler, error) - - // NewConnectOptions returns an empty options object that will be used to pass - // options to the Connect method. If nil, then a nil options object is passed to - // Connect. It may return a bool and a string. If true, the value of the request - // path below the object will be included as the named string in the serialization - // of the runtime object. - NewConnectOptions() (runtime.Object, bool, string) - - // ConnectMethods returns the list of HTTP methods handled by Connect - ConnectMethods() []string -} - -// ResourceStreamer is an interface implemented by objects that prefer to be streamed from the server -// instead of decoded directly. -type ResourceStreamer interface { - // InputStream should return an io.ReadCloser if the provided object supports streaming. The desired - // api version and a accept header (may be empty) are passed to the call. If no error occurs, - // the caller may return a flag indicating whether the result should be flushed as writes occur - // and a content type string that indicates the type of the stream. - // If a null stream is returned, a StatusNoContent response wil be generated. - InputStream(apiVersion, acceptHeader string) (stream io.ReadCloser, flush bool, mimeType string, err error) -} - -// StorageMetadata is an optional interface that callers can implement to provide additional -// information about their Storage objects. -type StorageMetadata interface { - // ProducesMIMETypes returns a list of the MIME types the specified HTTP verb (GET, POST, DELETE, - // PATCH) can respond with. - ProducesMIMETypes(verb string) []string -} - -// ConnectRequest is an object passed to admission control for Connect operations -type ConnectRequest struct { - // Name is the name of the object on which the connect request was made - Name string - - // Options is the options object passed to the connect request. See the NewConnectOptions method on Connecter - Options runtime.Object - - // ResourcePath is the path for the resource in the REST server (ie. "pods/proxy") - ResourcePath string -} - -func (obj *ConnectRequest) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/resttest/resttest.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/resttest/resttest.go deleted file mode 100644 index fbf0bf87d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/resttest/resttest.go +++ /dev/null @@ -1,1005 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package resttest - -import ( - "fmt" - "reflect" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/rest" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/conversion" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/wait" -) - -type Tester struct { - *testing.T - storage rest.Storage - clusterScope bool - createOnUpdate bool - generatesName bool - returnDeletedObject bool -} - -func New(t *testing.T, storage rest.Storage) *Tester { - return &Tester{ - T: t, - storage: storage, - } -} - -func (t *Tester) ClusterScope() *Tester { - t.clusterScope = true - return t -} - -func (t *Tester) AllowCreateOnUpdate() *Tester { - t.createOnUpdate = true - return t -} - -func (t *Tester) GeneratesName() *Tester { - t.generatesName = true - return t -} - -func (t *Tester) ReturnDeletedObject() *Tester { - t.returnDeletedObject = true - return t -} - -// TestNamespace returns the namespace that will be used when creating contexts. -// Returns NamespaceNone for cluster-scoped objects. -func (t *Tester) TestNamespace() string { - if t.clusterScope { - return api.NamespaceNone - } - return "test" -} - -// TestContext returns a namespaced context that will be used when making storage calls. -// Namespace is determined by TestNamespace() -func (t *Tester) TestContext() api.Context { - if t.clusterScope { - return api.NewContext() - } - return api.WithNamespace(api.NewContext(), t.TestNamespace()) -} - -func (t *Tester) getObjectMetaOrFail(obj runtime.Object) *api.ObjectMeta { - meta, err := api.ObjectMetaFor(obj) - if err != nil { - t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, obj) - } - return meta -} - -func (t *Tester) setObjectMeta(obj runtime.Object, name string) { - meta := t.getObjectMetaOrFail(obj) - meta.Name = name - if t.clusterScope { - meta.Namespace = api.NamespaceNone - } else { - meta.Namespace = api.NamespaceValue(t.TestContext()) - } - meta.GenerateName = "" -} - -func copyOrDie(obj runtime.Object) runtime.Object { - out, err := api.Scheme.Copy(obj) - if err != nil { - panic(err) - } - return out -} - -type AssignFunc func([]runtime.Object) []runtime.Object -type EmitFunc func(runtime.Object, string) error -type GetFunc func(api.Context, runtime.Object) (runtime.Object, error) -type InitWatchFunc func() -type InjectErrFunc func(err error) -type IsErrorFunc func(err error) bool -type SetFunc func(api.Context, runtime.Object) error -type SetRVFunc func(uint64) -type UpdateFunc func(runtime.Object) runtime.Object - -// Test creating an object. -func (t *Tester) TestCreate(valid runtime.Object, setFn SetFunc, getFn GetFunc, invalid ...runtime.Object) { - t.testCreateHasMetadata(copyOrDie(valid)) - if !t.generatesName { - t.testCreateGeneratesName(copyOrDie(valid)) - } - t.testCreateEquals(copyOrDie(valid), getFn) - t.testCreateAlreadyExisting(copyOrDie(valid), setFn) - if t.clusterScope { - t.testCreateDiscardsObjectNamespace(copyOrDie(valid)) - t.testCreateIgnoresContextNamespace(copyOrDie(valid)) - t.testCreateIgnoresMismatchedNamespace(copyOrDie(valid)) - } else { - t.testCreateRejectsMismatchedNamespace(copyOrDie(valid)) - } - t.testCreateInvokesValidation(invalid...) - t.testCreateValidatesNames(copyOrDie(valid)) -} - -// Test updating an object. -func (t *Tester) TestUpdate(valid runtime.Object, setFn SetFunc, getFn GetFunc, updateFn UpdateFunc, invalidUpdateFn ...UpdateFunc) { - t.testUpdateEquals(copyOrDie(valid), setFn, getFn, updateFn) - t.testUpdateFailsOnVersionTooOld(copyOrDie(valid), setFn, getFn) - t.testUpdateOnNotFound(copyOrDie(valid)) - if !t.clusterScope { - t.testUpdateRejectsMismatchedNamespace(copyOrDie(valid), setFn) - } - t.testUpdateInvokesValidation(copyOrDie(valid), setFn, invalidUpdateFn...) -} - -// Test deleting an object. -func (t *Tester) TestDelete(valid runtime.Object, setFn SetFunc, getFn GetFunc, isNotFoundFn IsErrorFunc) { - t.testDeleteNonExist(copyOrDie(valid)) - t.testDeleteNoGraceful(copyOrDie(valid), setFn, getFn, isNotFoundFn) -} - -// Test gracefully deleting an object. -func (t *Tester) TestDeleteGraceful(valid runtime.Object, setFn SetFunc, getFn GetFunc, expectedGrace int64) { - t.testDeleteGracefulHasDefault(copyOrDie(valid), setFn, getFn, expectedGrace) - t.testDeleteGracefulWithValue(copyOrDie(valid), setFn, getFn, expectedGrace) - t.testDeleteGracefulUsesZeroOnNil(copyOrDie(valid), setFn, expectedGrace) - t.testDeleteGracefulExtend(copyOrDie(valid), setFn, getFn, expectedGrace) - t.testDeleteGracefulImmediate(copyOrDie(valid), setFn, getFn, expectedGrace) -} - -// Test getting object. -func (t *Tester) TestGet(valid runtime.Object) { - t.testGetFound(copyOrDie(valid)) - t.testGetNotFound(copyOrDie(valid)) - t.testGetMimatchedNamespace(copyOrDie(valid)) - if !t.clusterScope { - t.testGetDifferentNamespace(copyOrDie(valid)) - } -} - -// Test listing objects. -func (t *Tester) TestList(valid runtime.Object, assignFn AssignFunc) { - t.testListNotFound(assignFn) - t.testListFound(copyOrDie(valid), assignFn) - t.testListMatchLabels(copyOrDie(valid), assignFn) -} - -// Test watching objects. -func (t *Tester) TestWatch( - valid runtime.Object, emitFn EmitFunc, - labelsPass, labelsFail []labels.Set, fieldsPass, fieldsFail []fields.Set, actions []string) { - t.testWatchLabels(copyOrDie(valid), emitFn, labelsPass, labelsFail, actions) - t.testWatchFields(copyOrDie(valid), emitFn, fieldsPass, fieldsFail, actions) -} - -// ============================================================================= -// Creation tests. - -func (t *Tester) testCreateAlreadyExisting(obj runtime.Object, setFn SetFunc) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo1") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - - _, err := t.storage.(rest.Creater).Create(ctx, foo) - if !errors.IsAlreadyExists(err) { - t.Errorf("expected already exists err, got %v", err) - } -} - -func (t *Tester) testCreateEquals(obj runtime.Object, getFn GetFunc) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo2") - - created, err := t.storage.(rest.Creater).Create(ctx, foo) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - got, err := getFn(ctx, foo) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - // Set resource version which might be unset in created object. - createdMeta := t.getObjectMetaOrFail(created) - gotMeta := t.getObjectMetaOrFail(got) - createdMeta.ResourceVersion = gotMeta.ResourceVersion - - if e, a := created, got; !api.Semantic.DeepEqual(e, a) { - t.Errorf("unexpected obj: %#v, expected %#v", e, a) - } -} - -func (t *Tester) testCreateDiscardsObjectNamespace(valid runtime.Object) { - objectMeta := t.getObjectMetaOrFail(valid) - - // Ignore non-empty namespace in object meta - objectMeta.Namespace = "not-default" - - // Ideally, we'd get an error back here, but at least verify the namespace wasn't persisted - created, err := t.storage.(rest.Creater).Create(t.TestContext(), copyOrDie(valid)) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - createdObjectMeta := t.getObjectMetaOrFail(created) - if createdObjectMeta.Namespace != api.NamespaceNone { - t.Errorf("Expected empty namespace on created object, got '%v'", createdObjectMeta.Namespace) - } -} - -func (t *Tester) testCreateGeneratesName(valid runtime.Object) { - objectMeta := t.getObjectMetaOrFail(valid) - objectMeta.Name = "" - objectMeta.GenerateName = "test-" - - _, err := t.storage.(rest.Creater).Create(t.TestContext(), valid) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if objectMeta.Name == "test-" || !strings.HasPrefix(objectMeta.Name, "test-") { - t.Errorf("unexpected name: %#v", valid) - } -} - -func (t *Tester) testCreateHasMetadata(valid runtime.Object) { - objectMeta := t.getObjectMetaOrFail(valid) - objectMeta.Name = "" - objectMeta.GenerateName = "test-" - objectMeta.Namespace = t.TestNamespace() - - obj, err := t.storage.(rest.Creater).Create(t.TestContext(), valid) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if obj == nil { - t.Fatalf("Unexpected object from result: %#v", obj) - } - if !api.HasObjectMetaSystemFieldValues(objectMeta) { - t.Errorf("storage did not populate object meta field values") - } -} - -func (t *Tester) testCreateIgnoresContextNamespace(valid runtime.Object) { - // Ignore non-empty namespace in context - ctx := api.WithNamespace(api.NewContext(), "not-default2") - - // Ideally, we'd get an error back here, but at least verify the namespace wasn't persisted - created, err := t.storage.(rest.Creater).Create(ctx, copyOrDie(valid)) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - createdObjectMeta := t.getObjectMetaOrFail(created) - if createdObjectMeta.Namespace != api.NamespaceNone { - t.Errorf("Expected empty namespace on created object, got '%v'", createdObjectMeta.Namespace) - } -} - -func (t *Tester) testCreateIgnoresMismatchedNamespace(valid runtime.Object) { - objectMeta := t.getObjectMetaOrFail(valid) - - // Ignore non-empty namespace in object meta - objectMeta.Namespace = "not-default" - ctx := api.WithNamespace(api.NewContext(), "not-default2") - - // Ideally, we'd get an error back here, but at least verify the namespace wasn't persisted - created, err := t.storage.(rest.Creater).Create(ctx, copyOrDie(valid)) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - createdObjectMeta := t.getObjectMetaOrFail(created) - if createdObjectMeta.Namespace != api.NamespaceNone { - t.Errorf("Expected empty namespace on created object, got '%v'", createdObjectMeta.Namespace) - } -} - -func (t *Tester) testCreateValidatesNames(valid runtime.Object) { - for _, invalidName := range validation.NameMayNotBe { - objCopy := copyOrDie(valid) - objCopyMeta := t.getObjectMetaOrFail(objCopy) - objCopyMeta.Name = invalidName - - ctx := t.TestContext() - _, err := t.storage.(rest.Creater).Create(ctx, objCopy) - if !errors.IsInvalid(err) { - t.Errorf("%s: Expected to get an invalid resource error, got %v", invalidName, err) - } - } - - for _, invalidSuffix := range validation.NameMayNotContain { - objCopy := copyOrDie(valid) - objCopyMeta := t.getObjectMetaOrFail(objCopy) - objCopyMeta.Name += invalidSuffix - - ctx := t.TestContext() - _, err := t.storage.(rest.Creater).Create(ctx, objCopy) - if !errors.IsInvalid(err) { - t.Errorf("%s: Expected to get an invalid resource error, got %v", invalidSuffix, err) - } - } -} - -func (t *Tester) testCreateInvokesValidation(invalid ...runtime.Object) { - for i, obj := range invalid { - ctx := t.TestContext() - _, err := t.storage.(rest.Creater).Create(ctx, obj) - if !errors.IsInvalid(err) { - t.Errorf("%d: Expected to get an invalid resource error, got %v", i, err) - } - } -} - -func (t *Tester) testCreateRejectsMismatchedNamespace(valid runtime.Object) { - objectMeta := t.getObjectMetaOrFail(valid) - objectMeta.Namespace = "not-default" - - _, err := t.storage.(rest.Creater).Create(t.TestContext(), valid) - if err == nil { - t.Errorf("Expected an error, but we didn't get one") - } else if !strings.Contains(err.Error(), "does not match the namespace sent on the request") { - t.Errorf("Expected 'does not match the namespace sent on the request' error, got '%v'", err.Error()) - } -} - -func (t *Tester) testCreateResetsUserData(valid runtime.Object) { - objectMeta := t.getObjectMetaOrFail(valid) - now := unversioned.Now() - objectMeta.UID = "bad-uid" - objectMeta.CreationTimestamp = now - - obj, err := t.storage.(rest.Creater).Create(t.TestContext(), valid) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if obj == nil { - t.Fatalf("Unexpected object from result: %#v", obj) - } - if objectMeta.UID == "bad-uid" || objectMeta.CreationTimestamp == now { - t.Errorf("ObjectMeta did not reset basic fields: %#v", objectMeta) - } -} - -// ============================================================================= -// Update tests. - -func (t *Tester) testUpdateEquals(obj runtime.Object, setFn SetFunc, getFn GetFunc, updateFn UpdateFunc) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo2") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - - toUpdate, err := getFn(ctx, foo) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - toUpdate = updateFn(toUpdate) - updated, created, err := t.storage.(rest.Updater).Update(ctx, toUpdate) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if created { - t.Errorf("unexpected creation") - } - got, err := getFn(ctx, foo) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - // Set resource version which might be unset in created object. - updatedMeta := t.getObjectMetaOrFail(updated) - gotMeta := t.getObjectMetaOrFail(got) - updatedMeta.ResourceVersion = gotMeta.ResourceVersion - - if e, a := updated, got; !api.Semantic.DeepEqual(e, a) { - t.Errorf("unexpected obj: %#v, expected %#v", e, a) - } -} - -func (t *Tester) testUpdateFailsOnVersionTooOld(obj runtime.Object, setFn SetFunc, getFn GetFunc) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo3") - - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - - storedFoo, err := getFn(ctx, foo) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - older := copyOrDie(storedFoo) - olderMeta := t.getObjectMetaOrFail(older) - olderMeta.ResourceVersion = "1" - - _, _, err = t.storage.(rest.Updater).Update(t.TestContext(), older) - if err == nil { - t.Errorf("Expected an error, but we didn't get one") - } else if !errors.IsConflict(err) { - t.Errorf("Expected Conflict error, got '%v'", err) - } -} - -func (t *Tester) testUpdateInvokesValidation(obj runtime.Object, setFn SetFunc, invalidUpdateFn ...UpdateFunc) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo4") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - - for _, update := range invalidUpdateFn { - toUpdate := update(copyOrDie(foo)) - got, created, err := t.storage.(rest.Updater).Update(t.TestContext(), toUpdate) - if got != nil || created { - t.Errorf("expected nil object and no creation for object: %v", toUpdate) - } - if !errors.IsInvalid(err) && !errors.IsBadRequest(err) { - t.Errorf("expected invalid or bad request error, got %v", err) - } - } -} - -func (t *Tester) testUpdateOnNotFound(obj runtime.Object) { - t.setObjectMeta(obj, "foo") - _, created, err := t.storage.(rest.Updater).Update(t.TestContext(), obj) - if t.createOnUpdate { - if err != nil { - t.Errorf("creation allowed on updated, but got an error: %v", err) - } - if !created { - t.Errorf("creation allowed on update, but object not created") - } - } else { - if err == nil { - t.Errorf("Expected an error, but we didn't get one") - } else if !errors.IsNotFound(err) { - t.Errorf("Expected NotFound error, got '%v'", err) - } - } -} - -func (t *Tester) testUpdateRejectsMismatchedNamespace(obj runtime.Object, setFn SetFunc) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo1") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - - objectMeta := t.getObjectMetaOrFail(obj) - objectMeta.Name = "foo1" - objectMeta.Namespace = "not-default" - - obj, updated, err := t.storage.(rest.Updater).Update(t.TestContext(), obj) - if obj != nil || updated { - t.Errorf("expected nil object and not updated") - } - if err == nil { - t.Errorf("expected an error, but didn't get one") - } else if !strings.Contains(err.Error(), "does not match the namespace sent on the request") { - t.Errorf("expected 'does not match the namespace sent on the request' error, got '%v'", err.Error()) - } -} - -// ============================================================================= -// Deletion tests. - -func (t *Tester) testDeleteNoGraceful(obj runtime.Object, setFn SetFunc, getFn GetFunc, isNotFoundFn IsErrorFunc) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo1") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - objectMeta := t.getObjectMetaOrFail(foo) - obj, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(10)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !t.returnDeletedObject { - if status, ok := obj.(*unversioned.Status); !ok { - t.Errorf("expected status of delete, got %v", status) - } else if status.Status != unversioned.StatusSuccess { - t.Errorf("expected success, got: %v", status.Status) - } - } - - _, err = getFn(ctx, foo) - if err == nil || !isNotFoundFn(err) { - t.Errorf("unexpected error: %v", err) - } -} - -func (t *Tester) testDeleteNonExist(obj runtime.Object) { - objectMeta := t.getObjectMetaOrFail(obj) - - _, err := t.storage.(rest.GracefulDeleter).Delete(t.TestContext(), objectMeta.Name, nil) - if err == nil || !errors.IsNotFound(err) { - t.Errorf("unexpected error: %v", err) - } - -} - -// ============================================================================= -// Graceful Deletion tests. - -func (t *Tester) testDeleteGracefulHasDefault(obj runtime.Object, setFn SetFunc, getFn GetFunc, expectedGrace int64) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo1") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - objectMeta := t.getObjectMetaOrFail(foo) - _, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, &api.DeleteOptions{}) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if _, err := getFn(ctx, foo); err != nil { - t.Fatalf("did not gracefully delete resource", err) - } - - object, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name) - if err != nil { - t.Fatalf("unexpected error, object should exist: %v", err) - } - objectMeta = t.getObjectMetaOrFail(object) - if objectMeta.DeletionTimestamp == nil || objectMeta.DeletionGracePeriodSeconds == nil || *objectMeta.DeletionGracePeriodSeconds != expectedGrace { - t.Errorf("unexpected deleted meta: %#v", objectMeta) - } -} - -func (t *Tester) testDeleteGracefulWithValue(obj runtime.Object, setFn SetFunc, getFn GetFunc, expectedGrace int64) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo2") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - objectMeta := t.getObjectMetaOrFail(foo) - _, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(expectedGrace+2)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if _, err := getFn(ctx, foo); err != nil { - t.Fatalf("did not gracefully delete resource", err) - } - - object, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name) - if err != nil { - t.Errorf("unexpected error, object should exist: %v", err) - } - objectMeta = t.getObjectMetaOrFail(object) - if objectMeta.DeletionTimestamp == nil || objectMeta.DeletionGracePeriodSeconds == nil || *objectMeta.DeletionGracePeriodSeconds != expectedGrace+2 { - t.Errorf("unexpected deleted meta: %#v", objectMeta) - } -} - -func (t *Tester) testDeleteGracefulExtend(obj runtime.Object, setFn SetFunc, getFn GetFunc, expectedGrace int64) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo3") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - objectMeta := t.getObjectMetaOrFail(foo) - _, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(expectedGrace)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if _, err := getFn(ctx, foo); err != nil { - t.Fatalf("did not gracefully delete resource", err) - } - - // second delete duration is ignored - _, err = t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(expectedGrace+2)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - object, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name) - if err != nil { - t.Errorf("unexpected error, object should exist: %v", err) - } - objectMeta = t.getObjectMetaOrFail(object) - if objectMeta.DeletionTimestamp == nil || objectMeta.DeletionGracePeriodSeconds == nil || *objectMeta.DeletionGracePeriodSeconds != expectedGrace { - t.Errorf("unexpected deleted meta: %#v", objectMeta) - } -} - -func (t *Tester) testDeleteGracefulImmediate(obj runtime.Object, setFn SetFunc, getFn GetFunc, expectedGrace int64) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo4") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - objectMeta := t.getObjectMetaOrFail(foo) - _, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(expectedGrace)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if _, err := getFn(ctx, foo); err != nil { - t.Fatalf("did not gracefully delete resource", err) - } - - // second delete is immediate, resource is deleted - out, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(0)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - _, err = t.storage.(rest.Getter).Get(ctx, objectMeta.Name) - if !errors.IsNotFound(err) { - t.Errorf("unexpected error, object should be deleted immediately: %v", err) - } - objectMeta = t.getObjectMetaOrFail(out) - // the second delete shouldn't update the object, so the objectMeta.DeletionGracePeriodSeconds should eqaul to the value set in the first delete. - if objectMeta.DeletionTimestamp == nil || objectMeta.DeletionGracePeriodSeconds == nil || *objectMeta.DeletionGracePeriodSeconds != expectedGrace { - t.Errorf("unexpected deleted meta: %#v", objectMeta) - } -} - -func (t *Tester) testDeleteGracefulUsesZeroOnNil(obj runtime.Object, setFn SetFunc, expectedGrace int64) { - ctx := t.TestContext() - - foo := copyOrDie(obj) - t.setObjectMeta(foo, "foo5") - if err := setFn(ctx, foo); err != nil { - t.Errorf("unexpected error: %v", err) - } - objectMeta := t.getObjectMetaOrFail(foo) - _, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, nil) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if _, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name); !errors.IsNotFound(err) { - t.Errorf("unexpected error, object should not exist: %v", err) - } -} - -// ============================================================================= -// Get tests. - -// testGetDifferentNamespace ensures same-name objects in different namespaces do not clash -func (t *Tester) testGetDifferentNamespace(obj runtime.Object) { - if t.clusterScope { - t.Fatalf("the test does not work in in cluster-scope") - } - - objMeta := t.getObjectMetaOrFail(obj) - objMeta.Name = "foo5" - - ctx1 := api.WithNamespace(api.NewContext(), "bar3") - objMeta.Namespace = api.NamespaceValue(ctx1) - _, err := t.storage.(rest.Creater).Create(ctx1, obj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - ctx2 := api.WithNamespace(api.NewContext(), "bar4") - objMeta.Namespace = api.NamespaceValue(ctx2) - _, err = t.storage.(rest.Creater).Create(ctx2, obj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - got1, err := t.storage.(rest.Getter).Get(ctx1, objMeta.Name) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - got1Meta := t.getObjectMetaOrFail(got1) - if got1Meta.Name != objMeta.Name { - t.Errorf("unexpected name of object: %#v, expected: %s", got1, objMeta.Name) - } - if got1Meta.Namespace != api.NamespaceValue(ctx1) { - t.Errorf("unexpected namespace of object: %#v, expected: %s", got1, api.NamespaceValue(ctx1)) - } - - got2, err := t.storage.(rest.Getter).Get(ctx2, objMeta.Name) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - got2Meta := t.getObjectMetaOrFail(got2) - if got2Meta.Name != objMeta.Name { - t.Errorf("unexpected name of object: %#v, expected: %s", got2, objMeta.Name) - } - if got2Meta.Namespace != api.NamespaceValue(ctx2) { - t.Errorf("unexpected namespace of object: %#v, expected: %s", got2, api.NamespaceValue(ctx2)) - } -} - -func (t *Tester) testGetFound(obj runtime.Object) { - ctx := t.TestContext() - t.setObjectMeta(obj, "foo1") - - existing, err := t.storage.(rest.Creater).Create(ctx, obj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - existingMeta := t.getObjectMetaOrFail(existing) - - got, err := t.storage.(rest.Getter).Get(ctx, "foo1") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - gotMeta := t.getObjectMetaOrFail(got) - gotMeta.ResourceVersion = existingMeta.ResourceVersion - if e, a := existing, got; !api.Semantic.DeepEqual(e, a) { - t.Errorf("unexpected obj: %#v, expected %#v", e, a) - } -} - -func (t *Tester) testGetMimatchedNamespace(obj runtime.Object) { - ctx1 := api.WithNamespace(api.NewContext(), "bar1") - ctx2 := api.WithNamespace(api.NewContext(), "bar2") - objMeta := t.getObjectMetaOrFail(obj) - objMeta.Name = "foo4" - objMeta.Namespace = api.NamespaceValue(ctx1) - _, err := t.storage.(rest.Creater).Create(ctx1, obj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - _, err = t.storage.(rest.Getter).Get(ctx2, "foo4") - if t.clusterScope { - if err != nil { - t.Errorf("unexpected error: %v", err) - } - } else { - if !errors.IsNotFound(err) { - t.Errorf("unexpected error returned: %#v", err) - } - } -} - -func (t *Tester) testGetNotFound(obj runtime.Object) { - ctx := t.TestContext() - t.setObjectMeta(obj, "foo2") - _, err := t.storage.(rest.Creater).Create(ctx, obj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - _, err = t.storage.(rest.Getter).Get(ctx, "foo3") - if !errors.IsNotFound(err) { - t.Errorf("unexpected error returned: %#v", err) - } -} - -// ============================================================================= -// List tests. - -func listToItems(listObj runtime.Object) ([]runtime.Object, error) { - v, err := conversion.EnforcePtr(listObj) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - items := v.FieldByName("Items") - if !items.IsValid() { - return nil, fmt.Errorf("unexpected Items field in %v", listObj) - } - if items.Type().Kind() != reflect.Slice { - return nil, fmt.Errorf("unexpected Items field type: %v", items.Type().Kind()) - } - result := make([]runtime.Object, items.Len()) - for i := 0; i < items.Len(); i++ { - result[i] = items.Index(i).Addr().Interface().(runtime.Object) - } - return result, nil -} - -func (t *Tester) testListFound(obj runtime.Object, assignFn AssignFunc) { - ctx := t.TestContext() - - foo1 := copyOrDie(obj) - t.setObjectMeta(foo1, "foo1") - foo2 := copyOrDie(obj) - t.setObjectMeta(foo2, "foo2") - - existing := assignFn([]runtime.Object{foo1, foo2}) - - listObj, err := t.storage.(rest.Lister).List(ctx, nil) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - items, err := listToItems(listObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(items) != len(existing) { - t.Errorf("unexpected number of items: %v", len(items)) - } - if !api.Semantic.DeepEqual(existing, items) { - t.Errorf("expected: %#v, got: %#v", existing, items) - } -} - -func (t *Tester) testListMatchLabels(obj runtime.Object, assignFn AssignFunc) { - ctx := t.TestContext() - testLabels := map[string]string{"key": "value"} - - foo3 := copyOrDie(obj) - t.setObjectMeta(foo3, "foo3") - foo4 := copyOrDie(obj) - foo4Meta := t.getObjectMetaOrFail(foo4) - foo4Meta.Name = "foo4" - foo4Meta.Namespace = api.NamespaceValue(ctx) - foo4Meta.Labels = testLabels - - objs := ([]runtime.Object{foo3, foo4}) - - assignFn(objs) - filtered := []runtime.Object{objs[1]} - - selector := labels.SelectorFromSet(labels.Set(testLabels)) - options := &api.ListOptions{LabelSelector: selector} - listObj, err := t.storage.(rest.Lister).List(ctx, options) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - items, err := listToItems(listObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(items) != len(filtered) { - t.Errorf("unexpected number of items: %v", len(items)) - } - if !api.Semantic.DeepEqual(filtered, items) { - t.Errorf("expected: %#v, got: %#v", filtered, items) - } -} - -func (t *Tester) testListNotFound(assignFn AssignFunc) { - ctx := t.TestContext() - _ = assignFn([]runtime.Object{}) - - listObj, err := t.storage.(rest.Lister).List(ctx, nil) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - items, err := listToItems(listObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(items) != 0 { - t.Errorf("unexpected items: %#v", items) - } -} - -// ============================================================================= -// Watching tests. - -func (t *Tester) testWatchFields(obj runtime.Object, emitFn EmitFunc, fieldsPass, fieldsFail []fields.Set, actions []string) { - ctx := t.TestContext() - - for _, field := range fieldsPass { - for _, action := range actions { - options := &api.ListOptions{FieldSelector: field.AsSelector(), ResourceVersion: "1"} - watcher, err := t.storage.(rest.Watcher).Watch(ctx, options) - if err != nil { - t.Errorf("unexpected error: %v, %v", err, action) - } - - if err := emitFn(obj, action); err != nil { - t.Errorf("unexpected error: %v", err) - } - - select { - case _, ok := <-watcher.ResultChan(): - if !ok { - t.Errorf("watch channel should be open") - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("unexpected timeout from result channel") - } - watcher.Stop() - } - } - - for _, field := range fieldsFail { - for _, action := range actions { - options := &api.ListOptions{FieldSelector: field.AsSelector(), ResourceVersion: "1"} - watcher, err := t.storage.(rest.Watcher).Watch(ctx, options) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := emitFn(obj, action); err != nil { - t.Errorf("unexpected error: %v", err) - } - - select { - case <-watcher.ResultChan(): - t.Errorf("unexpected result from result channel") - case <-time.After(time.Millisecond * 500): - // expected case - } - watcher.Stop() - } - } -} - -func (t *Tester) testWatchLabels(obj runtime.Object, emitFn EmitFunc, labelsPass, labelsFail []labels.Set, actions []string) { - ctx := t.TestContext() - - for _, label := range labelsPass { - for _, action := range actions { - options := &api.ListOptions{LabelSelector: label.AsSelector(), ResourceVersion: "1"} - watcher, err := t.storage.(rest.Watcher).Watch(ctx, options) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := emitFn(obj, action); err != nil { - t.Errorf("unexpected error: %v", err) - } - - select { - case _, ok := <-watcher.ResultChan(): - if !ok { - t.Errorf("watch channel should be open") - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("unexpected timeout from result channel") - } - watcher.Stop() - } - } - - for _, label := range labelsFail { - for _, action := range actions { - options := &api.ListOptions{LabelSelector: label.AsSelector(), ResourceVersion: "1"} - watcher, err := t.storage.(rest.Watcher).Watch(ctx, options) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := emitFn(obj, action); err != nil { - t.Errorf("unexpected error: %v", err) - } - - select { - case <-watcher.ResultChan(): - t.Errorf("unexpected result from result channel") - case <-time.After(time.Millisecond * 500): - // expected case - } - watcher.Stop() - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/types.go deleted file mode 100644 index 0e7f048ba..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/types.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package rest - -import ( - "k8s.io/kubernetes/pkg/runtime" -) - -// ObjectFunc is a function to act on a given object. An error may be returned -// if the hook cannot be completed. An ObjectFunc may transform the provided -// object. -type ObjectFunc func(obj runtime.Object) error - -// AllFuncs returns an ObjectFunc that attempts to run all of the provided functions -// in order, returning early if there are any errors. -func AllFuncs(fns ...ObjectFunc) ObjectFunc { - return func(obj runtime.Object) error { - for _, fn := range fns { - if fn == nil { - continue - } - if err := fn(obj); err != nil { - return err - } - } - return nil - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/update.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/update.go deleted file mode 100644 index 80ad14f86..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/rest/update.go +++ /dev/null @@ -1,105 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package rest - -import ( - "fmt" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -// RESTUpdateStrategy defines the minimum validation, accepted input, and -// name generation behavior to update an object that follows Kubernetes -// API conventions. A resource may have many UpdateStrategies, depending on -// the call pattern in use. -type RESTUpdateStrategy interface { - runtime.ObjectTyper - // NamespaceScoped returns true if the object must be within a namespace. - NamespaceScoped() bool - // AllowCreateOnUpdate returns true if the object can be created by a PUT. - AllowCreateOnUpdate() bool - // PrepareForUpdate is invoked on update before validation to normalize - // the object. For example: remove fields that are not to be persisted, - // sort order-insensitive list fields, etc. This should not remove fields - // whose presence would be considered a validation error. - PrepareForUpdate(obj, old runtime.Object) - // ValidateUpdate is invoked after default fields in the object have been - // filled in before the object is persisted. This method should not mutate - // the object. - ValidateUpdate(ctx api.Context, obj, old runtime.Object) field.ErrorList - // Canonicalize is invoked after validation has succeeded but before the - // object has been persisted. This method may mutate the object. - Canonicalize(obj runtime.Object) - // AllowUnconditionalUpdate returns true if the object can be updated - // unconditionally (irrespective of the latest resource version), when - // there is no resource version specified in the object. - AllowUnconditionalUpdate() bool -} - -// TODO: add other common fields that require global validation. -func validateCommonFields(obj, old runtime.Object) (field.ErrorList, error) { - allErrs := field.ErrorList{} - objectMeta, err := api.ObjectMetaFor(obj) - if err != nil { - return nil, fmt.Errorf("failed to get new object metadata: %v", err) - } - oldObjectMeta, err := api.ObjectMetaFor(old) - if err != nil { - return nil, fmt.Errorf("failed to get old object metadata: %v", err) - } - allErrs = append(allErrs, validation.ValidateObjectMetaUpdate(objectMeta, oldObjectMeta, field.NewPath("metadata"))...) - - return allErrs, nil -} - -// BeforeUpdate ensures that common operations for all resources are performed on update. It only returns -// errors that can be converted to api.Status. It will invoke update validation with the provided existing -// and updated objects. -func BeforeUpdate(strategy RESTUpdateStrategy, ctx api.Context, obj, old runtime.Object) error { - objectMeta, kind, kerr := objectMetaAndKind(strategy, obj) - if kerr != nil { - return kerr - } - if strategy.NamespaceScoped() { - if !api.ValidNamespace(ctx, objectMeta) { - return errors.NewBadRequest("the namespace of the provided object does not match the namespace sent on the request") - } - } else { - objectMeta.Namespace = api.NamespaceNone - } - - strategy.PrepareForUpdate(obj, old) - - // Ensure some common fields, like UID, are validated for all resources. - errs, err := validateCommonFields(obj, old) - if err != nil { - return errors.NewInternalError(err) - } - - errs = append(errs, strategy.ValidateUpdate(ctx, obj, old)...) - if len(errs) > 0 { - return errors.NewInvalid(kind.GroupKind(), objectMeta.Name, errs) - } - - strategy.Canonicalize(obj) - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/serialization_proto_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/serialization_proto_test.go deleted file mode 100644 index d74c1865d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/serialization_proto_test.go +++ /dev/null @@ -1,95 +0,0 @@ -// +build proto - -/* -Copyright 2015 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. -*/ - -package api_test - -import ( - "encoding/hex" - "math/rand" - "testing" - - "github.com/gogo/protobuf/proto" - "k8s.io/kubernetes/pkg/api" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/api/v1" - _ "k8s.io/kubernetes/pkg/apis/extensions" - _ "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/runtime/protobuf" - "k8s.io/kubernetes/pkg/util" -) - -func init() { - codecsToTest = append(codecsToTest, func(version string, item runtime.Object) (runtime.Codec, error) { - return protobuf.NewCodec(version, api.Scheme, api.Scheme, api.Scheme), nil - }) -} - -func TestProtobufRoundTrip(t *testing.T) { - obj := &v1.Pod{} - apitesting.FuzzerFor(t, "v1", rand.NewSource(benchmarkSeed)).Fuzz(obj) - data, err := obj.Marshal() - if err != nil { - t.Fatal(err) - } - out := &v1.Pod{} - if err := out.Unmarshal(data); err != nil { - t.Fatal(err) - } - if !api.Semantic.Equalities.DeepEqual(out, obj) { - t.Logf("marshal\n%s", hex.Dump(data)) - t.Fatalf("Unmarshal is unequal\n%s", util.ObjectGoPrintSideBySide(out, obj)) - } -} - -func BenchmarkEncodeProtobufGeneratedMarshal(b *testing.B) { - items := benchmarkItems() - width := len(items) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := items[i%width].Marshal(); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -// BenchmarkDecodeJSON provides a baseline for regular JSON decode performance -func BenchmarkDecodeIntoProtobuf(b *testing.B) { - items := benchmarkItems() - width := len(items) - encoded := make([][]byte, width) - for i := range items { - data, err := (&items[i]).Marshal() - if err != nil { - b.Fatal(err) - } - encoded[i] = data - validate := &v1.Pod{} - if err := proto.Unmarshal(data, validate); err != nil { - b.Fatalf("Failed to unmarshal %d: %v\n%#v", i, err, items[i]) - } - } - - for i := 0; i < b.N; i++ { - obj := v1.Pod{} - if err := proto.Unmarshal(encoded[i%width], &obj); err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/serialization_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/serialization_test.go deleted file mode 100644 index 7b1f17f81..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/serialization_test.go +++ /dev/null @@ -1,417 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package api_test - -import ( - "encoding/json" - "math/rand" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" - flag "github.com/spf13/pflag" - "github.com/ugorji/go/codec" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/sets" -) - -var fuzzIters = flag.Int("fuzz-iters", 20, "How many fuzzing iterations to do.") - -var codecsToTest = []func(version unversioned.GroupVersion, item runtime.Object) (runtime.Codec, error){ - func(version unversioned.GroupVersion, item runtime.Object) (runtime.Codec, error) { - return testapi.GetCodecForObject(item) - }, -} - -func fuzzInternalObject(t *testing.T, forVersion unversioned.GroupVersion, item runtime.Object, seed int64) runtime.Object { - apitesting.FuzzerFor(t, forVersion, rand.NewSource(seed)).Fuzz(item) - - j, err := meta.TypeAccessor(item) - if err != nil { - t.Fatalf("Unexpected error %v for %#v", err, item) - } - j.SetKind("") - j.SetAPIVersion("") - - return item -} - -func roundTrip(t *testing.T, codec runtime.Codec, item runtime.Object) { - //t.Logf("codec: %#v", codec) - - printer := spew.ConfigState{DisableMethods: true} - - name := reflect.TypeOf(item).Elem().Name() - data, err := runtime.Encode(codec, item) - if err != nil { - t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", item)) - return - } - - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Errorf("0: %v: %v\nCodec: %v\nData: %s\nSource: %#v", name, err, codec, string(data), printer.Sprintf("%#v", item)) - return - } - if !api.Semantic.DeepEqual(item, obj2) { - t.Errorf("\n1: %v: diff: %v\nCodec: %v\nSource:\n\n%#v\n\nEncoded:\n\n%s\n\nFinal:\n\n%#v", name, util.ObjectGoPrintDiff(item, obj2), codec, printer.Sprintf("%#v", item), string(data), printer.Sprintf("%#v", obj2)) - return - } - - obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object) - if err := runtime.DecodeInto(codec, data, obj3); err != nil { - t.Errorf("2: %v: %v", name, err) - return - } - if !api.Semantic.DeepEqual(item, obj3) { - t.Errorf("3: %v: diff: %v\nCodec: %v", name, util.ObjectDiff(item, obj3), codec) - return - } -} - -// roundTripSame verifies the same source object is tested in all API versions. -func roundTripSame(t *testing.T, group testapi.TestGroup, item runtime.Object, except ...string) { - set := sets.NewString(except...) - seed := rand.Int63() - fuzzInternalObject(t, group.InternalGroupVersion(), item, seed) - - version := *group.GroupVersion() - codecs := []runtime.Codec{} - for _, fn := range codecsToTest { - codec, err := fn(version, item) - if err != nil { - t.Errorf("unable to get codec: %v", err) - return - } - codecs = append(codecs, codec) - } - - if !set.Has(version.String()) { - fuzzInternalObject(t, version, item, seed) - for _, codec := range codecs { - roundTrip(t, codec, item) - } - } -} - -// For debugging problems -func TestSpecificKind(t *testing.T) { - // api.Scheme.Log(t) - // defer api.Scheme.Log(nil) - - kind := "DaemonSet" - for i := 0; i < *fuzzIters; i++ { - doRoundTripTest(testapi.Groups["extensions"], kind, t) - if t.Failed() { - break - } - } -} - -func TestList(t *testing.T) { - // api.Scheme.Log(t) - // defer api.Scheme.Log(nil) - - kind := "List" - item, err := api.Scheme.New(api.SchemeGroupVersion.WithKind(kind)) - if err != nil { - t.Errorf("Couldn't make a %v? %v", kind, err) - return - } - roundTripSame(t, testapi.Default, item) -} - -var nonRoundTrippableTypes = sets.NewString("ExportOptions") - -var nonInternalRoundTrippableTypes = sets.NewString("List", "ListOptions", "ExportOptions") -var nonRoundTrippableTypesByVersion = map[string][]string{} - -func TestRoundTripTypes(t *testing.T) { - // api.Scheme.Log(t) - // defer api.Scheme.Log(nil) - - for groupKey, group := range testapi.Groups { - for kind := range api.Scheme.KnownTypes(group.InternalGroupVersion()) { - t.Logf("working on %v in %v", kind, groupKey) - if nonRoundTrippableTypes.Has(kind) { - continue - } - // Try a few times, since runTest uses random values. - for i := 0; i < *fuzzIters; i++ { - doRoundTripTest(group, kind, t) - if t.Failed() { - break - } - } - } - } -} - -func doRoundTripTest(group testapi.TestGroup, kind string, t *testing.T) { - item, err := api.Scheme.New(group.InternalGroupVersion().WithKind(kind)) - if err != nil { - t.Fatalf("Couldn't make a %v? %v", kind, err) - } - if _, err := meta.TypeAccessor(item); err != nil { - t.Fatalf("%q is not a TypeMeta and cannot be tested - add it to nonRoundTrippableTypes: %v", kind, err) - } - if api.Scheme.Recognizes(group.GroupVersion().WithKind(kind)) { - roundTripSame(t, group, item, nonRoundTrippableTypesByVersion[kind]...) - } - if !nonInternalRoundTrippableTypes.Has(kind) && api.Scheme.Recognizes(group.GroupVersion().WithKind(kind)) { - roundTrip(t, group.Codec(), fuzzInternalObject(t, group.InternalGroupVersion(), item, rand.Int63())) - } -} - -func TestEncode_Ptr(t *testing.T) { - grace := int64(30) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"name": "foo"}, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - - TerminationGracePeriodSeconds: &grace, - - SecurityContext: &api.PodSecurityContext{}, - }, - } - obj := runtime.Object(pod) - data, err := runtime.Encode(testapi.Default.Codec(), obj) - obj2, err2 := runtime.Decode(testapi.Default.Codec(), data) - if err != nil || err2 != nil { - t.Fatalf("Failure: '%v' '%v'", err, err2) - } - if _, ok := obj2.(*api.Pod); !ok { - t.Fatalf("Got wrong type") - } - if !api.Semantic.DeepEqual(obj2, pod) { - t.Errorf("\nExpected:\n\n %#v,\n\nGot:\n\n %#vDiff: %v\n\n", pod, obj2, util.ObjectDiff(obj2, pod)) - - } -} - -func TestBadJSONRejection(t *testing.T) { - badJSONMissingKind := []byte(`{ }`) - if _, err := runtime.Decode(testapi.Default.Codec(), badJSONMissingKind); err == nil { - t.Errorf("Did not reject despite lack of kind field: %s", badJSONMissingKind) - } - badJSONUnknownType := []byte(`{"kind": "bar"}`) - if _, err1 := runtime.Decode(testapi.Default.Codec(), badJSONUnknownType); err1 == nil { - t.Errorf("Did not reject despite use of unknown type: %s", badJSONUnknownType) - } - /*badJSONKindMismatch := []byte(`{"kind": "Pod"}`) - if err2 := DecodeInto(badJSONKindMismatch, &Minion{}); err2 == nil { - t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch) - }*/ -} - -func TestUnversionedTypes(t *testing.T) { - testcases := []runtime.Object{ - &unversioned.Status{Status: "Failure", Message: "something went wrong"}, - &unversioned.APIVersions{Versions: []string{"A", "B", "C"}}, - &unversioned.APIGroupList{Groups: []unversioned.APIGroup{{Name: "mygroup"}}}, - &unversioned.APIGroup{Name: "mygroup"}, - &unversioned.APIResourceList{GroupVersion: "mygroup/myversion"}, - } - - for _, obj := range testcases { - // Make sure the unversioned codec can encode - unversionedJSON, err := runtime.Encode(testapi.Default.Codec(), obj) - if err != nil { - t.Errorf("%v: unexpected error: %v", obj, err) - continue - } - - // Make sure the versioned codec under test can decode - versionDecodedObject, err := runtime.Decode(testapi.Default.Codec(), unversionedJSON) - if err != nil { - t.Errorf("%v: unexpected error: %v", obj, err) - continue - } - // Make sure it decodes correctly - if !reflect.DeepEqual(obj, versionDecodedObject) { - t.Errorf("%v: expected %#v, got %#v", obj, obj, versionDecodedObject) - continue - } - } -} - -const benchmarkSeed = 100 - -func benchmarkItems() []v1.Pod { - apiObjectFuzzer := apitesting.FuzzerFor(nil, api.SchemeGroupVersion, rand.NewSource(benchmarkSeed)) - items := make([]v1.Pod, 2) - for i := range items { - apiObjectFuzzer.Fuzz(&items[i]) - } - return items -} - -// BenchmarkEncodeCodec measures the cost of performing a codec encode, which includes -// reflection (to clear APIVersion and Kind) -func BenchmarkEncodeCodec(b *testing.B) { - items := benchmarkItems() - width := len(items) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := runtime.Encode(testapi.Default.Codec(), &items[i%width]); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -// BenchmarkEncodeJSONMarshal provides a baseline for regular JSON encode performance -func BenchmarkEncodeJSONMarshal(b *testing.B) { - items := benchmarkItems() - width := len(items) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := json.Marshal(&items[i%width]); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -func BenchmarkDecodeCodec(b *testing.B) { - codec := testapi.Default.Codec() - items := benchmarkItems() - width := len(items) - encoded := make([][]byte, width) - for i := range items { - data, err := runtime.Encode(codec, &items[i]) - if err != nil { - b.Fatal(err) - } - encoded[i] = data - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := runtime.Decode(codec, encoded[i%width]); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -func BenchmarkDecodeIntoExternalCodec(b *testing.B) { - codec := testapi.Default.Codec() - items := benchmarkItems() - width := len(items) - encoded := make([][]byte, width) - for i := range items { - data, err := runtime.Encode(codec, &items[i]) - if err != nil { - b.Fatal(err) - } - encoded[i] = data - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - obj := v1.Pod{} - if err := runtime.DecodeInto(codec, encoded[i%width], &obj); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -func BenchmarkDecodeIntoInternalCodec(b *testing.B) { - codec := testapi.Default.Codec() - items := benchmarkItems() - width := len(items) - encoded := make([][]byte, width) - for i := range items { - data, err := runtime.Encode(codec, &items[i]) - if err != nil { - b.Fatal(err) - } - encoded[i] = data - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - obj := api.Pod{} - if err := runtime.DecodeInto(codec, encoded[i%width], &obj); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -// BenchmarkDecodeJSON provides a baseline for regular JSON decode performance -func BenchmarkDecodeIntoJSON(b *testing.B) { - codec := testapi.Default.Codec() - items := benchmarkItems() - width := len(items) - encoded := make([][]byte, width) - for i := range items { - data, err := runtime.Encode(codec, &items[i]) - if err != nil { - b.Fatal(err) - } - encoded[i] = data - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - obj := v1.Pod{} - if err := json.Unmarshal(encoded[i%width], &obj); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -// BenchmarkDecodeJSON provides a baseline for codecgen JSON decode performance -func BenchmarkDecodeIntoJSONCodecGen(b *testing.B) { - kcodec := testapi.Default.Codec() - items := benchmarkItems() - width := len(items) - encoded := make([][]byte, width) - for i := range items { - data, err := runtime.Encode(kcodec, &items[i]) - if err != nil { - b.Fatal(err) - } - encoded[i] = data - } - handler := &codec.JsonHandle{} - - b.ResetTimer() - for i := 0; i < b.N; i++ { - obj := v1.Pod{} - if err := codec.NewDecoderBytes(encoded[i%width], handler).Decode(&obj); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flock/flock_other.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/service/annotations.go similarity index 51% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flock/flock_other.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/service/annotations.go index b80981882..9d57fa4c2 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flock/flock_other.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/service/annotations.go @@ -1,5 +1,3 @@ -// +build !linux,!darwin,!freebsd,!openbsd,!netbsd,!dragonfly - /* Copyright 2016 The Kubernetes Authors All rights reserved. @@ -16,9 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. */ -package flock +package service -// Acquire is not implemented on non-unix systems. -func Acquire(path string) error { - return nil -} +const ( + // AnnotationLoadBalancerSourceRangesKey is the key of the annotation on a service to set allowed ingress ranges on their LoadBalancers + // + // It should be a comma-separated list of CIDRs, e.g. `0.0.0.0/0` to + // allow full access (the default) or `18.0.0.0/8,56.0.0.0/8` to allow + // access only from the CIDRs currently allocated to MIT & the USPS. + // + // Not all cloud providers support this annotation, though AWS & GCE do. + AnnotationLoadBalancerSourceRangesKey = "service.beta.kubernetes.io/load-balancer-source-ranges" +) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/service/util.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/service/util.go new file mode 100644 index 000000000..a77e5b9c7 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/service/util.go @@ -0,0 +1,54 @@ +/* +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. +*/ + +package service + +import ( + "fmt" + "strings" + + netsets "k8s.io/kubernetes/pkg/util/net/sets" +) + +const ( + defaultLoadBalancerSourceRanges = "0.0.0.0/0" +) + +// IsAllowAll checks whether the netsets.IPNet allows traffic from 0.0.0.0/0 +func IsAllowAll(ipnets netsets.IPNet) bool { + for _, s := range ipnets.StringSlice() { + if s == "0.0.0.0/0" { + return true + } + } + return false +} + +// GetLoadBalancerSourceRanges verifies and parses the AnnotationLoadBalancerSourceRangesKey annotation from a service, +// extracting the source ranges to allow, and if not present returns a default (allow-all) value. +func GetLoadBalancerSourceRanges(annotations map[string]string) (netsets.IPNet, error) { + val := annotations[AnnotationLoadBalancerSourceRangesKey] + val = strings.TrimSpace(val) + if val == "" { + val = defaultLoadBalancerSourceRanges + } + specs := strings.Split(val, ",") + ipnets, err := netsets.ParseIPNets(specs...) + if err != nil { + return nil, fmt.Errorf("Service annotation %s:%s is not valid. Expecting a comma-separated list of source IP ranges. For example, 10.0.0.0/24,192.168.2.0/24", AnnotationLoadBalancerSourceRangesKey, val) + } + return ipnets, nil +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi.go index f6f75e879..d5d5452ad 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi.go @@ -20,6 +20,7 @@ package testapi import ( "fmt" "os" + "reflect" "strings" "k8s.io/kubernetes/pkg/api" @@ -27,11 +28,13 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/autoscaling" + "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/runtime" _ "k8s.io/kubernetes/pkg/api/install" _ "k8s.io/kubernetes/pkg/apis/autoscaling/install" + _ "k8s.io/kubernetes/pkg/apis/batch/install" _ "k8s.io/kubernetes/pkg/apis/componentconfig/install" _ "k8s.io/kubernetes/pkg/apis/extensions/install" _ "k8s.io/kubernetes/pkg/apis/metrics/install" @@ -41,12 +44,14 @@ var ( Groups = make(map[string]TestGroup) Default TestGroup Autoscaling TestGroup + Batch TestGroup Extensions TestGroup ) type TestGroup struct { externalGroupVersion unversioned.GroupVersion internalGroupVersion unversioned.GroupVersion + internalTypes map[string]reflect.Type } func init() { @@ -59,9 +64,11 @@ func init() { panic(fmt.Sprintf("Error parsing groupversion %v: %v", gvString, err)) } + internalGroupVersion := unversioned.GroupVersion{Group: groupVersion.Group, Version: runtime.APIVersionInternal} Groups[groupVersion.Group] = TestGroup{ externalGroupVersion: groupVersion, - internalGroupVersion: unversioned.GroupVersion{Group: groupVersion.Group, Version: runtime.APIVersionInternal}, + internalGroupVersion: internalGroupVersion, + internalTypes: api.Scheme.KnownTypes(internalGroupVersion), } } } @@ -70,23 +77,55 @@ func init() { Groups[api.GroupName] = TestGroup{ externalGroupVersion: unversioned.GroupVersion{Group: api.GroupName, Version: registered.GroupOrDie(api.GroupName).GroupVersion.Version}, internalGroupVersion: api.SchemeGroupVersion, - } - } - if _, ok := Groups[autoscaling.GroupName]; !ok { - Groups[autoscaling.GroupName] = TestGroup{ - externalGroupVersion: unversioned.GroupVersion{Group: autoscaling.GroupName, Version: registered.GroupOrDie(autoscaling.GroupName).GroupVersion.Version}, - internalGroupVersion: extensions.SchemeGroupVersion, + internalTypes: api.Scheme.KnownTypes(api.SchemeGroupVersion), } } if _, ok := Groups[extensions.GroupName]; !ok { Groups[extensions.GroupName] = TestGroup{ externalGroupVersion: unversioned.GroupVersion{Group: extensions.GroupName, Version: registered.GroupOrDie(extensions.GroupName).GroupVersion.Version}, internalGroupVersion: extensions.SchemeGroupVersion, + internalTypes: api.Scheme.KnownTypes(extensions.SchemeGroupVersion), + } + } + if _, ok := Groups[autoscaling.GroupName]; !ok { + internalTypes := make(map[string]reflect.Type) + for k, t := range api.Scheme.KnownTypes(extensions.SchemeGroupVersion) { + if k == "Scale" { + continue + } + internalTypes[k] = t + } + Groups[autoscaling.GroupName] = TestGroup{ + externalGroupVersion: unversioned.GroupVersion{Group: autoscaling.GroupName, Version: registered.GroupOrDie(autoscaling.GroupName).GroupVersion.Version}, + internalGroupVersion: extensions.SchemeGroupVersion, + internalTypes: internalTypes, + } + } + if _, ok := Groups[autoscaling.GroupName+"IntraGroup"]; !ok { + internalTypes := make(map[string]reflect.Type) + for k, t := range api.Scheme.KnownTypes(extensions.SchemeGroupVersion) { + if k == "Scale" { + internalTypes[k] = t + break + } + } + Groups[autoscaling.GroupName] = TestGroup{ + externalGroupVersion: unversioned.GroupVersion{Group: autoscaling.GroupName, Version: registered.GroupOrDie(autoscaling.GroupName).GroupVersion.Version}, + internalGroupVersion: autoscaling.SchemeGroupVersion, + internalTypes: internalTypes, + } + } + if _, ok := Groups[batch.GroupName]; !ok { + Groups[batch.GroupName] = TestGroup{ + externalGroupVersion: unversioned.GroupVersion{Group: batch.GroupName, Version: registered.GroupOrDie(batch.GroupName).GroupVersion.Version}, + internalGroupVersion: extensions.SchemeGroupVersion, + internalTypes: api.Scheme.KnownTypes(extensions.SchemeGroupVersion), } } Default = Groups[api.GroupName] Autoscaling = Groups[autoscaling.GroupName] + Batch = Groups[batch.GroupName] Extensions = Groups[extensions.GroupName] } @@ -105,6 +144,11 @@ func (g TestGroup) InternalGroupVersion() unversioned.GroupVersion { return g.internalGroupVersion } +// InternalTypes returns a map of internal API types' kind names to their Go types. +func (g TestGroup) InternalTypes() map[string]reflect.Type { + return g.internalTypes +} + // Codec returns the codec for the API version to test against, as set by the // KUBE_TEST_API env var. func (g TestGroup) Codec() runtime.Codec { @@ -218,6 +262,6 @@ func GetCodecForObject(obj runtime.Object) (runtime.Codec, error) { return nil, fmt.Errorf("unexpected kind: %v", kind) } -func NewTestGroup(external, internal unversioned.GroupVersion) TestGroup { - return TestGroup{external, internal} +func NewTestGroup(external, internal unversioned.GroupVersion, internalTypes map[string]reflect.Type) TestGroup { + return TestGroup{external, internal, internalTypes} } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi_test.go deleted file mode 100644 index 7d9ad0ec0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testapi/testapi_test.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testapi - -import ( - "encoding/json" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -// TODO these tests don't add much value for testing things that have groups - -func TestResourcePathWithPrefix(t *testing.T) { - testCases := []struct { - prefix string - resource string - namespace string - name string - expected string - }{ - {"prefix", "resource", "mynamespace", "myresource", "/api/" + Default.GroupVersion().Version + "/prefix/namespaces/mynamespace/resource/myresource"}, - {"prefix", "resource", "", "myresource", "/api/" + Default.GroupVersion().Version + "/prefix/resource/myresource"}, - {"prefix", "resource", "mynamespace", "", "/api/" + Default.GroupVersion().Version + "/prefix/namespaces/mynamespace/resource"}, - {"prefix", "resource", "", "", "/api/" + Default.GroupVersion().Version + "/prefix/resource"}, - {"", "resource", "mynamespace", "myresource", "/api/" + Default.GroupVersion().Version + "/namespaces/mynamespace/resource/myresource"}, - } - for _, item := range testCases { - if actual := Default.ResourcePathWithPrefix(item.prefix, item.resource, item.namespace, item.name); actual != item.expected { - t.Errorf("Expected: %s, got: %s for prefix: %s, resource: %s, namespace: %s and name: %s", item.expected, actual, item.prefix, item.resource, item.namespace, item.name) - } - } -} - -func TestResourcePath(t *testing.T) { - testCases := []struct { - resource string - namespace string - name string - expected string - }{ - {"resource", "mynamespace", "myresource", "/api/" + Default.GroupVersion().Version + "/namespaces/mynamespace/resource/myresource"}, - {"resource", "", "myresource", "/api/" + Default.GroupVersion().Version + "/resource/myresource"}, - {"resource", "mynamespace", "", "/api/" + Default.GroupVersion().Version + "/namespaces/mynamespace/resource"}, - {"resource", "", "", "/api/" + Default.GroupVersion().Version + "/resource"}, - } - for _, item := range testCases { - if actual := Default.ResourcePath(item.resource, item.namespace, item.name); actual != item.expected { - t.Errorf("Expected: %s, got: %s for resource: %s, namespace: %s and name: %s", item.expected, actual, item.resource, item.namespace, item.name) - } - } -} - -var status = &unversioned.Status{ - Status: unversioned.StatusFailure, - Code: 200, - Reason: unversioned.StatusReasonUnknown, - Message: "", -} - -func TestV1EncodeDecodeStatus(t *testing.T) { - v1Codec := Default.Codec() - - encoded, err := runtime.Encode(v1Codec, status) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - typeMeta := unversioned.TypeMeta{} - if err := json.Unmarshal(encoded, &typeMeta); err != nil { - t.Errorf("unexpected error: %v", err) - } - if typeMeta.Kind != "Status" { - t.Errorf("Kind is not set to \"Status\". Got %v", string(encoded)) - } - if typeMeta.APIVersion != "v1" { - t.Errorf("APIVersion is not set to \"v1\". Got %v", string(encoded)) - } - decoded, err := runtime.Decode(v1Codec, encoded) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !reflect.DeepEqual(status, decoded) { - t.Errorf("expected: %#v, got: %#v", status, decoded) - } -} - -func testEncodeDecodeStatus(t *testing.T, codec runtime.Codec) { - encoded, err := runtime.Encode(codec, status) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - typeMeta := unversioned.TypeMeta{} - if err := json.Unmarshal(encoded, &typeMeta); err != nil { - t.Errorf("unexpected error: %v", err) - } - if typeMeta.Kind != "Status" { - t.Errorf("Kind is not set to \"Status\". Got %s", encoded) - } - if typeMeta.APIVersion != "v1" { - t.Errorf("APIVersion is not set to \"\". Got %s", encoded) - } - decoded, err := runtime.Decode(codec, encoded) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !reflect.DeepEqual(status, decoded) { - t.Errorf("expected: %v, got: %v", status, decoded) - } -} - -func TestAutoscalingEncodeDecodeStatus(t *testing.T) { - testEncodeDecodeStatus(t, Autoscaling.Codec()) -} - -func TestExperimentalEncodeDecodeStatus(t *testing.T) { - testEncodeDecodeStatus(t, Extensions.Codec()) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/compat/compatibility_tester.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/compat/compatibility_tester.go deleted file mode 100644 index 82f165a33..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/compat/compatibility_tester.go +++ /dev/null @@ -1,144 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package compat - -import ( - "encoding/json" - "fmt" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/kubectl" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -// Based on: https://github.com/openshift/origin/blob/master/pkg/api/compatibility_test.go -// -// TestCompatibility reencodes the input using the codec for the given -// version and checks for the presence of the expected keys and absent -// keys in the resulting JSON. -func TestCompatibility( - t *testing.T, - version unversioned.GroupVersion, - input []byte, - validator func(obj runtime.Object) field.ErrorList, - expectedKeys map[string]string, - absentKeys []string, -) { - - // Decode - codec := api.Codecs.LegacyCodec(version) - obj, err := runtime.Decode(codec, input) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // Validate - errs := validator(obj) - if len(errs) != 0 { - t.Fatalf("Unexpected validation errors: %v", errs) - } - - // Encode - output, err := runtime.Encode(codec, obj) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // Validate old and new fields are encoded - generic := map[string]interface{}{} - if err := json.Unmarshal(output, &generic); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - hasError := false - for k, expectedValue := range expectedKeys { - keys := strings.Split(k, ".") - if actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok { - t.Errorf("Unexpected error for %s: %v", k, err) - hasError = true - } else if !reflect.DeepEqual(expectedValue, fmt.Sprintf("%v", actualValue)) { - hasError = true - t.Errorf("Unexpected value for %v: expected %v, got %v", k, expectedValue, actualValue) - } - } - - for _, absentKey := range absentKeys { - keys := strings.Split(absentKey, ".") - actualValue, ok, err := getJSONValue(generic, keys...) - if err == nil || ok { - t.Errorf("Unexpected value found for for key %s: %v", absentKey, actualValue) - hasError = true - } - } - - if hasError { - printer := new(kubectl.JSONPrinter) - printer.PrintObj(obj, os.Stdout) - t.Logf("2: Encoded value: %#v", string(output)) - } -} - -func getJSONValue(data map[string]interface{}, keys ...string) (interface{}, bool, error) { - // No keys, current value is it - if len(keys) == 0 { - return data, true, nil - } - - // Get the key (and optional index) - key := keys[0] - index := -1 - if matches := regexp.MustCompile(`^(.*)\[(\d+)\]$`).FindStringSubmatch(key); len(matches) > 0 { - key = matches[1] - index, _ = strconv.Atoi(matches[2]) - } - - // Look up the value - value, ok := data[key] - if !ok { - return nil, false, fmt.Errorf("No key %s found", key) - } - - // Get the indexed value if an index is specified - if index >= 0 { - valueSlice, ok := value.([]interface{}) - if !ok { - return nil, false, fmt.Errorf("Key %s did not hold a slice", key) - } - if index >= len(valueSlice) { - return nil, false, fmt.Errorf("Index %d out of bounds for slice at key: %v", index, key) - } - value = valueSlice[index] - } - - if len(keys) == 1 { - return value, true, nil - } - - childData, ok := value.(map[string]interface{}) - if !ok { - return nil, false, fmt.Errorf("Key %s did not hold a map", keys[0]) - } - return getJSONValue(childData, keys[1:]...) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/conversion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/conversion.go deleted file mode 100644 index 6f91427e7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/conversion.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testing - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/labels" -) - -// TestSelectableFieldLabelConversions verifies that given resource have field -// label conversion defined for each its selectable field. -// fields contains selectable fields of the resource. -// labelMap maps deprecated labels to their canonical names. -func TestSelectableFieldLabelConversionsOfKind(t *testing.T, apiVersion string, kind string, fields labels.Set, labelMap map[string]string) { - badFieldLabels := []string{ - "name", - ".name", - "bad", - "metadata", - "foo.bar", - } - - value := "value" - - if len(fields) == 0 { - t.Logf("no selectable fields for kind %q, skipping", kind) - } - for label := range fields { - if label == "name" { - t.Logf("FIXME: \"name\" is deprecated by \"metadata.name\", it should be removed from selectable fields of kind=%s", kind) - continue - } - newLabel, newValue, err := api.Scheme.ConvertFieldLabel(apiVersion, kind, label, value) - if err != nil { - t.Errorf("kind=%s label=%s: got unexpected error: %v", kind, label, err) - } else { - expectedLabel := label - if l, exists := labelMap[label]; exists { - expectedLabel = l - } - if newLabel != expectedLabel { - t.Errorf("kind=%s label=%s: got unexpected label name (%q != %q)", kind, label, newLabel, expectedLabel) - } - if newValue != value { - t.Errorf("kind=%s label=%s: got unexpected new value (%q != %q)", kind, label, newValue, value) - } - } - } - - for _, label := range badFieldLabels { - _, _, err := api.Scheme.ConvertFieldLabel(apiVersion, kind, label, "value") - if err == nil { - t.Errorf("kind=%s label=%s: got unexpected non-error", kind, label) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/fuzzer.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/fuzzer.go deleted file mode 100644 index 092802d11..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/fuzzer.go +++ /dev/null @@ -1,413 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testing - -import ( - "fmt" - "math/rand" - "reflect" - "strconv" - "testing" - - docker "github.com/fsouza/go-dockerclient" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/types" - "k8s.io/kubernetes/pkg/util/intstr" - - "github.com/google/gofuzz" -) - -// FuzzerFor can randomly populate api objects that are destined for version. -func FuzzerFor(t *testing.T, version unversioned.GroupVersion, src rand.Source) *fuzz.Fuzzer { - f := fuzz.New().NilChance(.5).NumElements(1, 1) - if src != nil { - f.RandSource(src) - } - f.Funcs( - func(j *int, c fuzz.Continue) { - *j = int(c.Int31()) - }, - func(j **int, c fuzz.Continue) { - if c.RandBool() { - i := int(c.Int31()) - *j = &i - } else { - *j = nil - } - }, - func(q *resource.Quantity, c fuzz.Continue) { - *q = *resource.NewQuantity(c.Int63n(1000), resource.DecimalExponent) - }, - func(j *runtime.TypeMeta, c fuzz.Continue) { - // We have to customize the randomization of TypeMetas because their - // APIVersion and Kind must remain blank in memory. - j.APIVersion = "" - j.Kind = "" - }, - func(j *unversioned.TypeMeta, c fuzz.Continue) { - // We have to customize the randomization of TypeMetas because their - // APIVersion and Kind must remain blank in memory. - j.APIVersion = "" - j.Kind = "" - }, - func(j *api.ObjectMeta, c fuzz.Continue) { - j.Name = c.RandString() - j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10) - j.SelfLink = c.RandString() - j.UID = types.UID(c.RandString()) - j.GenerateName = c.RandString() - - var sec, nsec int64 - c.Fuzz(&sec) - c.Fuzz(&nsec) - j.CreationTimestamp = unversioned.Unix(sec, nsec).Rfc3339Copy() - }, - func(j *api.ObjectReference, c fuzz.Continue) { - // We have to customize the randomization of TypeMetas because their - // APIVersion and Kind must remain blank in memory. - j.APIVersion = c.RandString() - j.Kind = c.RandString() - j.Namespace = c.RandString() - j.Name = c.RandString() - j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10) - j.FieldPath = c.RandString() - }, - func(j *unversioned.ListMeta, c fuzz.Continue) { - j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10) - j.SelfLink = c.RandString() - }, - func(j *api.ListOptions, c fuzz.Continue) { - label, _ := labels.Parse("a=b") - j.LabelSelector = label - field, _ := fields.ParseSelector("a=b") - j.FieldSelector = field - }, - func(j *api.PodExecOptions, c fuzz.Continue) { - j.Stdout = true - j.Stderr = true - }, - func(j *api.PodAttachOptions, c fuzz.Continue) { - j.Stdout = true - j.Stderr = true - }, - func(s *api.PodSpec, c fuzz.Continue) { - c.FuzzNoCustom(s) - // has a default value - ttl := int64(30) - if c.RandBool() { - ttl = int64(c.Uint32()) - } - s.TerminationGracePeriodSeconds = &ttl - - c.Fuzz(s.SecurityContext) - - if s.SecurityContext == nil { - s.SecurityContext = new(api.PodSecurityContext) - } - }, - func(j *api.PodPhase, c fuzz.Continue) { - statuses := []api.PodPhase{api.PodPending, api.PodRunning, api.PodFailed, api.PodUnknown} - *j = statuses[c.Rand.Intn(len(statuses))] - }, - func(j *api.Binding, c fuzz.Continue) { - c.Fuzz(&j.ObjectMeta) - j.Target.Name = c.RandString() - }, - func(j *api.ReplicationControllerSpec, c fuzz.Continue) { - c.FuzzNoCustom(j) // fuzz self without calling this function again - //j.TemplateRef = nil // this is required for round trip - }, - func(j *extensions.DeploymentStrategy, c fuzz.Continue) { - c.FuzzNoCustom(j) // fuzz self without calling this function again - // Ensure that strategyType is one of valid values. - strategyTypes := []extensions.DeploymentStrategyType{extensions.RecreateDeploymentStrategyType, extensions.RollingUpdateDeploymentStrategyType} - j.Type = strategyTypes[c.Rand.Intn(len(strategyTypes))] - if j.Type != extensions.RollingUpdateDeploymentStrategyType { - j.RollingUpdate = nil - } else { - rollingUpdate := extensions.RollingUpdateDeployment{} - if c.RandBool() { - rollingUpdate.MaxUnavailable = intstr.FromInt(int(c.RandUint64())) - rollingUpdate.MaxSurge = intstr.FromInt(int(c.RandUint64())) - } else { - rollingUpdate.MaxSurge = intstr.FromString(fmt.Sprintf("%d%%", c.RandUint64())) - } - j.RollingUpdate = &rollingUpdate - } - }, - func(j *extensions.JobSpec, c fuzz.Continue) { - c.FuzzNoCustom(j) // fuzz self without calling this function again - completions := int(c.Rand.Int31()) - parallelism := int(c.Rand.Int31()) - j.Completions = &completions - j.Parallelism = ¶llelism - }, - func(j *api.List, c fuzz.Continue) { - c.FuzzNoCustom(j) // fuzz self without calling this function again - // TODO: uncomment when round trip starts from a versioned object - if false { //j.Items == nil { - j.Items = []runtime.Object{} - } - }, - func(j *runtime.Object, c fuzz.Continue) { - // TODO: uncomment when round trip starts from a versioned object - if true { //c.RandBool() { - *j = &runtime.Unknown{ - // We do not set TypeMeta here because it is not carried through a round trip - RawJSON: []byte(`{"apiVersion":"unknown.group/unknown","kind":"Something","someKey":"someValue"}`), - } - } else { - types := []runtime.Object{&api.Pod{}, &api.ReplicationController{}} - t := types[c.Rand.Intn(len(types))] - c.Fuzz(t) - *j = t - } - }, - func(pb map[docker.Port][]docker.PortBinding, c fuzz.Continue) { - // This is necessary because keys with nil values get omitted. - // TODO: Is this a bug? - pb[docker.Port(c.RandString())] = []docker.PortBinding{ - {c.RandString(), c.RandString()}, - {c.RandString(), c.RandString()}, - } - }, - func(pm map[string]docker.PortMapping, c fuzz.Continue) { - // This is necessary because keys with nil values get omitted. - // TODO: Is this a bug? - pm[c.RandString()] = docker.PortMapping{ - c.RandString(): c.RandString(), - } - }, - func(q *api.ResourceRequirements, c fuzz.Continue) { - randomQuantity := func() resource.Quantity { - var q resource.Quantity - c.Fuzz(&q) - return q - } - q.Limits = make(api.ResourceList) - q.Requests = make(api.ResourceList) - cpuLimit := randomQuantity() - q.Limits[api.ResourceCPU] = *cpuLimit.Copy() - q.Requests[api.ResourceCPU] = *cpuLimit.Copy() - memoryLimit := randomQuantity() - q.Limits[api.ResourceMemory] = *memoryLimit.Copy() - q.Requests[api.ResourceMemory] = *memoryLimit.Copy() - storageLimit := randomQuantity() - q.Limits[api.ResourceStorage] = *storageLimit.Copy() - q.Requests[api.ResourceStorage] = *storageLimit.Copy() - }, - func(q *api.LimitRangeItem, c fuzz.Continue) { - var cpuLimit resource.Quantity - c.Fuzz(&cpuLimit) - - q.Type = api.LimitTypeContainer - q.Default = make(api.ResourceList) - q.Default[api.ResourceCPU] = *(cpuLimit.Copy()) - - q.DefaultRequest = make(api.ResourceList) - q.DefaultRequest[api.ResourceCPU] = *(cpuLimit.Copy()) - - q.Max = make(api.ResourceList) - q.Max[api.ResourceCPU] = *(cpuLimit.Copy()) - - q.Min = make(api.ResourceList) - q.Min[api.ResourceCPU] = *(cpuLimit.Copy()) - - q.MaxLimitRequestRatio = make(api.ResourceList) - q.MaxLimitRequestRatio[api.ResourceCPU] = resource.MustParse("10") - }, - func(p *api.PullPolicy, c fuzz.Continue) { - policies := []api.PullPolicy{api.PullAlways, api.PullNever, api.PullIfNotPresent} - *p = policies[c.Rand.Intn(len(policies))] - }, - func(rp *api.RestartPolicy, c fuzz.Continue) { - policies := []api.RestartPolicy{api.RestartPolicyAlways, api.RestartPolicyNever, api.RestartPolicyOnFailure} - *rp = policies[c.Rand.Intn(len(policies))] - }, - // Only api.DownwardAPIVolumeFile needs to have a specific func since FieldRef has to be - // defaulted to a version otherwise roundtrip will fail - // For the remaining volume plugins the default fuzzer is enough. - func(m *api.DownwardAPIVolumeFile, c fuzz.Continue) { - m.Path = c.RandString() - versions := []string{"v1"} - m.FieldRef.APIVersion = versions[c.Rand.Intn(len(versions))] - m.FieldRef.FieldPath = c.RandString() - }, - func(vs *api.VolumeSource, c fuzz.Continue) { - // Exactly one of the fields must be set. - v := reflect.ValueOf(vs).Elem() - i := int(c.RandUint64() % uint64(v.NumField())) - t := v.Field(i).Addr() - for v.Field(i).IsNil() { - c.Fuzz(t.Interface()) - } - }, - func(i *api.ISCSIVolumeSource, c fuzz.Continue) { - i.ISCSIInterface = c.RandString() - if i.ISCSIInterface == "" { - i.ISCSIInterface = "default" - } - }, - func(d *api.DNSPolicy, c fuzz.Continue) { - policies := []api.DNSPolicy{api.DNSClusterFirst, api.DNSDefault} - *d = policies[c.Rand.Intn(len(policies))] - }, - func(p *api.Protocol, c fuzz.Continue) { - protocols := []api.Protocol{api.ProtocolTCP, api.ProtocolUDP} - *p = protocols[c.Rand.Intn(len(protocols))] - }, - func(p *api.ServiceAffinity, c fuzz.Continue) { - types := []api.ServiceAffinity{api.ServiceAffinityClientIP, api.ServiceAffinityNone} - *p = types[c.Rand.Intn(len(types))] - }, - func(p *api.ServiceType, c fuzz.Continue) { - types := []api.ServiceType{api.ServiceTypeClusterIP, api.ServiceTypeNodePort, api.ServiceTypeLoadBalancer} - *p = types[c.Rand.Intn(len(types))] - }, - func(ct *api.Container, c fuzz.Continue) { - c.FuzzNoCustom(ct) // fuzz self without calling this function again - ct.TerminationMessagePath = "/" + ct.TerminationMessagePath // Must be non-empty - }, - func(p *api.Probe, c fuzz.Continue) { - c.FuzzNoCustom(p) - // These fields have default values. - intFieldsWithDefaults := [...]string{"TimeoutSeconds", "PeriodSeconds", "SuccessThreshold", "FailureThreshold"} - v := reflect.ValueOf(p).Elem() - for _, field := range intFieldsWithDefaults { - f := v.FieldByName(field) - if f.Int() == 0 { - f.SetInt(1) - } - } - }, - func(ev *api.EnvVar, c fuzz.Continue) { - ev.Name = c.RandString() - if c.RandBool() { - ev.Value = c.RandString() - } else { - ev.ValueFrom = &api.EnvVarSource{} - ev.ValueFrom.FieldRef = &api.ObjectFieldSelector{} - - var versions []unversioned.GroupVersion - for _, testGroup := range testapi.Groups { - versions = append(versions, *testGroup.GroupVersion()) - } - - ev.ValueFrom.FieldRef.APIVersion = versions[c.Rand.Intn(len(versions))].String() - ev.ValueFrom.FieldRef.FieldPath = c.RandString() - } - }, - func(sc *api.SecurityContext, c fuzz.Continue) { - c.FuzzNoCustom(sc) // fuzz self without calling this function again - if c.RandBool() { - priv := c.RandBool() - sc.Privileged = &priv - } - - if c.RandBool() { - sc.Capabilities = &api.Capabilities{ - Add: make([]api.Capability, 0), - Drop: make([]api.Capability, 0), - } - c.Fuzz(&sc.Capabilities.Add) - c.Fuzz(&sc.Capabilities.Drop) - } - }, - func(s *api.Secret, c fuzz.Continue) { - c.FuzzNoCustom(s) // fuzz self without calling this function again - s.Type = api.SecretTypeOpaque - }, - func(pv *api.PersistentVolume, c fuzz.Continue) { - c.FuzzNoCustom(pv) // fuzz self without calling this function again - types := []api.PersistentVolumePhase{api.VolumeAvailable, api.VolumePending, api.VolumeBound, api.VolumeReleased, api.VolumeFailed} - pv.Status.Phase = types[c.Rand.Intn(len(types))] - pv.Status.Message = c.RandString() - reclamationPolicies := []api.PersistentVolumeReclaimPolicy{api.PersistentVolumeReclaimRecycle, api.PersistentVolumeReclaimRetain} - pv.Spec.PersistentVolumeReclaimPolicy = reclamationPolicies[c.Rand.Intn(len(reclamationPolicies))] - }, - func(pvc *api.PersistentVolumeClaim, c fuzz.Continue) { - c.FuzzNoCustom(pvc) // fuzz self without calling this function again - types := []api.PersistentVolumeClaimPhase{api.ClaimBound, api.ClaimPending} - pvc.Status.Phase = types[c.Rand.Intn(len(types))] - }, - func(s *api.NamespaceSpec, c fuzz.Continue) { - s.Finalizers = []api.FinalizerName{api.FinalizerKubernetes} - }, - func(s *api.NamespaceStatus, c fuzz.Continue) { - s.Phase = api.NamespaceActive - }, - func(http *api.HTTPGetAction, c fuzz.Continue) { - c.FuzzNoCustom(http) // fuzz self without calling this function again - http.Path = "/" + http.Path // can't be blank - http.Scheme = "x" + http.Scheme // can't be blank - }, - func(ss *api.ServiceSpec, c fuzz.Continue) { - c.FuzzNoCustom(ss) // fuzz self without calling this function again - if len(ss.Ports) == 0 { - // There must be at least 1 port. - ss.Ports = append(ss.Ports, api.ServicePort{}) - c.Fuzz(&ss.Ports[0]) - } - for i := range ss.Ports { - switch ss.Ports[i].TargetPort.Type { - case intstr.Int: - ss.Ports[i].TargetPort.IntVal = 1 + ss.Ports[i].TargetPort.IntVal%65535 // non-zero - case intstr.String: - ss.Ports[i].TargetPort.StrVal = "x" + ss.Ports[i].TargetPort.StrVal // non-empty - } - } - }, - func(n *api.Node, c fuzz.Continue) { - c.FuzzNoCustom(n) - n.Spec.ExternalID = "external" - }, - func(s *api.NodeStatus, c fuzz.Continue) { - c.FuzzNoCustom(s) - s.Allocatable = s.Capacity - }, - func(s *extensions.APIVersion, c fuzz.Continue) { - // We can't use c.RandString() here because it may generate empty - // string, which will cause tests failure. - s.APIGroup = "something" - }, - func(s *extensions.HorizontalPodAutoscalerSpec, c fuzz.Continue) { - c.FuzzNoCustom(s) // fuzz self without calling this function again - minReplicas := int(c.Rand.Int31()) - s.MinReplicas = &minReplicas - s.CPUUtilization = &extensions.CPUTargetUtilization{TargetPercentage: int(int32(c.RandUint64()))} - }, - func(s *extensions.SubresourceReference, c fuzz.Continue) { - c.FuzzNoCustom(s) // fuzz self without calling this function again - s.Subresource = "scale" - }, - func(psp *extensions.PodSecurityPolicySpec, c fuzz.Continue) { - c.FuzzNoCustom(psp) // fuzz self without calling this function again - userTypes := []extensions.RunAsUserStrategy{extensions.RunAsUserStrategyMustRunAsNonRoot, extensions.RunAsUserStrategyMustRunAs, extensions.RunAsUserStrategyRunAsAny} - psp.RunAsUser.Type = userTypes[c.Rand.Intn(len(userTypes))] - seLinuxTypes := []extensions.SELinuxContextStrategy{extensions.SELinuxStrategyRunAsAny, extensions.SELinuxStrategyMustRunAs} - psp.SELinuxContext.Type = seLinuxTypes[c.Rand.Intn(len(seLinuxTypes))] - }, - ) - return f -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/pod_specs.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/pod_specs.go deleted file mode 100644 index 2020b3f7f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/testing/pod_specs.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testing - -import ( - "k8s.io/kubernetes/pkg/api" -) - -// DeepEqualSafePodSpec returns a PodSpec which is ready to be used with api.Semantic.DeepEqual -func DeepEqualSafePodSpec() api.PodSpec { - grace := int64(30) - return api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - TerminationGracePeriodSeconds: &grace, - SecurityContext: &api.PodSecurityContext{}, - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.generated.go index 1d5f537f8..b4ccb56cc 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.generated.go @@ -26953,13 +26953,14 @@ func (x *ReplicationControllerStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [2]bool + var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[1] = x.ObservedGeneration != 0 + yyq2[1] = x.FullyLabeledReplicas != 0 + yyq2[2] = x.ObservedGeneration != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(2) + r.EncodeArrayStart(3) } else { yynn2 = 1 for _, b := range yyq2 { @@ -26996,7 +26997,7 @@ func (x *ReplicationControllerStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym7 if false { } else { - r.EncodeInt(int64(x.ObservedGeneration)) + r.EncodeInt(int64(x.FullyLabeledReplicas)) } } else { r.EncodeInt(0) @@ -27004,11 +27005,36 @@ func (x *ReplicationControllerStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + r.EncodeString(codecSelferC_UTF81234, string("fullyLabeledReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { + } else { + r.EncodeInt(int64(x.FullyLabeledReplicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeInt(int64(x.ObservedGeneration)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { } else { r.EncodeInt(int64(x.ObservedGeneration)) } @@ -27081,6 +27107,12 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromMap(l int, d *codec1978 } else { x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) } + case "fullyLabeledReplicas": + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int(r.DecodeInt(codecSelferBitsize1234)) + } case "observedGeneration": if r.TryDecodeAsNil() { x.ObservedGeneration = 0 @@ -27098,16 +27130,16 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromArray(l int, d *codec19 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 + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -27117,13 +27149,29 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromArray(l int, d *codec19 } else { x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int(r.DecodeInt(codecSelferBitsize1234)) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -27134,17 +27182,17 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromArray(l int, d *codec19 x.ObservedGeneration = int64(r.DecodeInt(64)) } for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj6-1, "") + z.DecStructFieldNotFound(yyj7-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -44187,6 +44235,32 @@ func (x *LimitRangeList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } +func (x ResourceQuotaScope) 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 *ResourceQuotaScope) 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 *ResourceQuotaSpec) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -44201,13 +44275,14 @@ func (x *ResourceQuotaSpec) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [1]bool + var yyq2 [2]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[0] = len(x.Hard) != 0 + yyq2[1] = len(x.Scopes) != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(1) + r.EncodeArrayStart(2) } else { yynn2 = 0 for _, b := range yyq2 { @@ -44241,6 +44316,39 @@ func (x *ResourceQuotaSpec) CodecEncodeSelf(e *codec1978.Encoder) { } } } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.Scopes == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + h.encSliceResourceQuotaScope(([]ResourceQuotaScope)(x.Scopes), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("scopes")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Scopes == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + h.encSliceResourceQuotaScope(([]ResourceQuotaScope)(x.Scopes), e) + } + } + } + } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { @@ -44309,6 +44417,18 @@ func (x *ResourceQuotaSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) yyv4 := &x.Hard yyv4.CodecDecodeSelf(d) } + case "scopes": + if r.TryDecodeAsNil() { + x.Scopes = nil + } else { + yyv5 := &x.Scopes + yym6 := z.DecBinary() + _ = yym6 + if false { + } else { + h.decSliceResourceQuotaScope((*[]ResourceQuotaScope)(yyv5), d) + } + } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 @@ -44320,16 +44440,16 @@ func (x *ResourceQuotaSpec) 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 + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb5 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb5 { + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -44337,21 +44457,43 @@ func (x *ResourceQuotaSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder if r.TryDecodeAsNil() { x.Hard = nil } else { - yyv6 := &x.Hard - yyv6.CodecDecodeSelf(d) + yyv8 := &x.Hard + yyv8.CodecDecodeSelf(d) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Scopes = nil + } else { + yyv9 := &x.Scopes + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + h.decSliceResourceQuotaScope((*[]ResourceQuotaScope)(yyv9), d) + } } for { - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb5 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb5 { + if yyb7 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj5-1, "") + z.DecStructFieldNotFound(yyj7-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -51295,7 +51437,7 @@ func (x codecSelfer1234) decSliceReplicationController(v *[]ReplicationControlle yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 232) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 240) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] @@ -53768,6 +53910,116 @@ func (x codecSelfer1234) decSliceLimitRange(v *[]LimitRange, d *codec1978.Decode } } +func (x codecSelfer1234) encSliceResourceQuotaScope(v []ResourceQuotaScope, 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) + yyv1.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceResourceQuotaScope(v *[]ResourceQuotaScope, 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 = []ResourceQuotaScope{} + 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) { + + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]ResourceQuotaScope, yyrl1) + } + } else { + yyv1 = make([]ResourceQuotaScope, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = "" + } else { + yyv1[yyj1] = ResourceQuotaScope(r.DecodeString()) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, "") + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = "" + } else { + yyv1[yyj1] = ResourceQuotaScope(r.DecodeString()) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, "") // var yyz1 ResourceQuotaScope + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = "" + } else { + yyv1[yyj1] = ResourceQuotaScope(r.DecodeString()) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []ResourceQuotaScope{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + func (x codecSelfer1234) encSliceResourceQuota(v []ResourceQuota, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -53807,7 +54059,7 @@ func (x codecSelfer1234) decSliceResourceQuota(v *[]ResourceQuota, d *codec1978. yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 216) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 240) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.go index 1312ef086..a82aa45c0 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/types.go @@ -98,7 +98,7 @@ type ObjectMeta struct { ResourceVersion string `json:"resourceVersion,omitempty"` // A sequence number representing a specific generation of the desired state. - // Currently only implemented by replication controllers. + // Populated by the system. Read-only. Generation int64 `json:"generation,omitempty"` // CreationTimestamp is a timestamp representing the server time when this object was @@ -441,10 +441,10 @@ const ( // Represents a Persistent Disk resource in Google Compute Engine. // -// A GCE PD must exist and be formatted 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. -// GCE PDs support ownership management and SELinux relabeling. +// A 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. type GCEPersistentDiskVolumeSource struct { // Unique name of the PD resource. Used to identify the disk in GCE PDName string `json:"pdName"` @@ -523,10 +523,10 @@ type FlexVolumeSource struct { // Represents a Persistent Disk resource in AWS. // -// An AWS EBS disk must exist and be formatted before mounting to a container. -// The disk must also be in the same AWS zone as the kubelet. -// A AWS EBS disk can only be mounted as read/write once. -// AWS EBS volumes support ownership management and SELinux relabeling. +// An AWS EBS disk must exist before mounting to a container. The disk +// must also be in the same AWS zone as the kubelet. A AWS EBS disk +// can only be mounted as read/write once. AWS EBS volumes support +// ownership management and SELinux relabeling. type AWSElasticBlockStoreVolumeSource struct { // Unique id of the persistent disk resource. Used to identify the disk in AWS VolumeID string `json:"volumeID"` @@ -623,10 +623,10 @@ type RBDVolumeSource struct { ReadOnly bool `json:"readOnly,omitempty"` } -// Represents a cinder volume resource in Openstack. -// A Cinder volume must exist and be formatted 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. +// 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. type CinderVolumeSource struct { // Unique id of the volume used to identify the cinder volume VolumeID string `json:"volumeID"` @@ -742,7 +742,7 @@ type VolumeMount struct { Name string `json:"name"` // Optional: Defaults to false (read-write). ReadOnly bool `json:"readOnly,omitempty"` - // Required. + // Required. Must not contain ':'. MountPath string `json:"mountPath"` } @@ -1380,6 +1380,9 @@ type ReplicationControllerStatus struct { // Replicas is the number of actual replicas. Replicas int `json:"replicas"` + // The number of pods that have labels matching the labels of the pod template of the replication controller. + FullyLabeledReplicas int `json:"fullyLabeledReplicas,omitempty"` + // ObservedGeneration is the most recent generation observed by the controller. ObservedGeneration int64 `json:"observedGeneration,omitempty"` } @@ -1526,8 +1529,10 @@ type ServicePort struct { // Optional: The target port on pods selected by this service. 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 default value - // is the sames as the Port field (an identity map). + // 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. TargetPort intstr.IntOrString `json:"targetPort"` // The port on each node on which this service is exposed. @@ -2185,14 +2190,41 @@ const ( ResourceQuotas ResourceName = "resourcequotas" // ResourceSecrets, number ResourceSecrets ResourceName = "secrets" + // ResourceConfigMaps, number + ResourceConfigMaps ResourceName = "configmaps" // ResourcePersistentVolumeClaims, number ResourcePersistentVolumeClaims ResourceName = "persistentvolumeclaims" + // CPU request, in cores. (500m = .5 cores) + ResourceRequestsCPU ResourceName = "requests.cpu" + // Memory request, in bytes. (500Gi = 500GiB = 500 * 1024 * 1024 * 1024) + ResourceRequestsMemory ResourceName = "requests.memory" + // CPU limit, in cores. (500m = .5 cores) + ResourceLimitsCPU ResourceName = "limits.cpu" + // Memory limit, in bytes. (500Gi = 500GiB = 500 * 1024 * 1024 * 1024) + ResourceLimitsMemory ResourceName = "limits.memory" +) + +// A ResourceQuotaScope defines a filter that must match each object tracked by a quota +type ResourceQuotaScope string + +const ( + // Match all pod objects where spec.activeDeadlineSeconds + ResourceQuotaScopeTerminating ResourceQuotaScope = "Terminating" + // Match all pod objects where !spec.activeDeadlineSeconds + ResourceQuotaScopeNotTerminating ResourceQuotaScope = "NotTerminating" + // Match all pod objects that have best effort quality of service + ResourceQuotaScopeBestEffort ResourceQuotaScope = "BestEffort" + // Match all pod objects that do not have best effort quality of service + ResourceQuotaScopeNotBestEffort ResourceQuotaScope = "NotBestEffort" ) // 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 Hard ResourceList `json:"hard,omitempty"` + // A collection of filters that must match each object tracked by a quota. + // If not specified, the quota matches all objects. + Scopes []ResourceQuotaScope `json:"scopes,omitempty"` } // ResourceQuotaStatus defines the enforced hard limits and observed use diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/duration_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/duration_test.go deleted file mode 100644 index 6650ca9aa..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/duration_test.go +++ /dev/null @@ -1,153 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "encoding/json" - "testing" - "time" - - "github.com/ghodss/yaml" -) - -type DurationHolder struct { - D Duration `json:"d"` -} - -func TestDurationMarshalYAML(t *testing.T) { - cases := []struct { - input Duration - result string - }{ - {Duration{5 * time.Second}, "d: 5s\n"}, - {Duration{2 * time.Minute}, "d: 2m0s\n"}, - {Duration{time.Hour + 3*time.Millisecond}, "d: 1h0m0.003s\n"}, - } - - for _, c := range cases { - input := DurationHolder{c.input} - result, err := yaml.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: %q: %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: %q: expected %q, got %q", input, c.result, string(result)) - } - } -} - -func TestDurationUnmarshalYAML(t *testing.T) { - cases := []struct { - input string - result Duration - }{ - {"d: 0s\n", Duration{}}, - {"d: 5s\n", Duration{5 * time.Second}}, - {"d: 2m0s\n", Duration{2 * time.Minute}}, - {"d: 1h0m0.003s\n", Duration{time.Hour + 3*time.Millisecond}}, - - // Units with zero values can optionally be dropped - {"d: 2m\n", Duration{2 * time.Minute}}, - {"d: 1h0.003s\n", Duration{time.Hour + 3*time.Millisecond}}, - } - - for _, c := range cases { - var result DurationHolder - if err := yaml.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input %q: %v", c.input, err) - } - if result.D != c.result { - t.Errorf("Failed to unmarshal input %q: expected %q, got %q", c.input, c.result, result) - } - } -} - -func TestDurationMarshalJSON(t *testing.T) { - cases := []struct { - input Duration - result string - }{ - {Duration{5 * time.Second}, `{"d":"5s"}`}, - {Duration{2 * time.Minute}, `{"d":"2m0s"}`}, - {Duration{time.Hour + 3*time.Millisecond}, `{"d":"1h0m0.003s"}`}, - } - - for _, c := range cases { - input := DurationHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: %q: %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: %q: expected %q, got %q", input, c.result, string(result)) - } - } -} - -func TestDurationUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result Duration - }{ - {`{"d":"0s"}`, Duration{}}, - {`{"d":"5s"}`, Duration{5 * time.Second}}, - {`{"d":"2m0s"}`, Duration{2 * time.Minute}}, - {`{"d":"1h0m0.003s"}`, Duration{time.Hour + 3*time.Millisecond}}, - - // Units with zero values can optionally be dropped - {`{"d":"2m"}`, Duration{2 * time.Minute}}, - {`{"d":"1h0.003s"}`, Duration{time.Hour + 3*time.Millisecond}}, - } - - for _, c := range cases { - var result DurationHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input %q: %v", c.input, err) - } - if result.D != c.result { - t.Errorf("Failed to unmarshal input %q: expected %q, got %q", c.input, c.result, result) - } - } -} - -func TestDurationMarshalJSONUnmarshalYAML(t *testing.T) { - cases := []struct { - input Duration - }{ - {Duration{}}, - {Duration{5 * time.Second}}, - {Duration{2 * time.Minute}}, - {Duration{time.Hour + 3*time.Millisecond}}, - } - - for i, c := range cases { - input := DurationHolder{c.input} - jsonMarshalled, err := json.Marshal(&input) - if err != nil { - t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err) - } - - var result DurationHolder - if err := yaml.Unmarshal(jsonMarshalled, &result); err != nil { - t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err) - } - - if input.D != result.D { - t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/group_version.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/group_version.go index dc1dc9672..5d350432c 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/group_version.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/group_version.go @@ -22,6 +22,21 @@ import ( "strings" ) +// ParseResourceArg takes the common style of string which may be either `resource.group.com` or `resource.version.group.com` +// and parses it out into both possibilities. This code takes no responsibility for knowing which representation was intended +// but with a knowledge of all GroupVersions, calling code can take a very good guess. If there are only two segments, then +// `*GroupVersionResource` is nil. +// `resource.group.com` -> `group=com, version=group, resource=resource` and `group=group.com, resource=resource` +func ParseResourceArg(arg string) (*GroupVersionResource, GroupResource) { + var gvr *GroupVersionResource + s := strings.SplitN(arg, ".", 3) + if len(s) == 3 { + gvr = &GroupVersionResource{Group: s[2], Version: s[1], Resource: s[0]} + } + + return gvr, ParseGroupResource(arg) +} + // GroupResource specifies a Group and a Resource, but does not force a version. This is useful for identifying // concepts during lookup stages without having partially valid types // @@ -46,6 +61,17 @@ func (gr *GroupResource) String() string { return gr.Resource + "." + gr.Group } +// ParseGroupResource turns "resource.group" string into a GroupResource struct. Empty strings are allowed +// for each field. +func ParseGroupResource(gr string) GroupResource { + s := strings.SplitN(gr, ".", 2) + if len(s) == 1 { + return GroupResource{Resource: s[0]} + } + + return GroupResource{Group: s[1], Resource: s[0]} +} + // GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion // to avoid automatic coersion. It doesn't use a GroupVersion to avoid custom marshalling // diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/group_version_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/group_version_test.go deleted file mode 100644 index 4a26fbb10..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/group_version_test.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned - -import ( - "encoding/json" - "reflect" - "testing" - - "github.com/ugorji/go/codec" -) - -type GroupVersionHolder struct { - GV GroupVersion `json:"val"` -} - -func TestGroupVersionUnmarshalJSON(t *testing.T) { - cases := []struct { - input []byte - expect GroupVersion - }{ - {[]byte(`{"val": "v1"}`), GroupVersion{"", "v1"}}, - {[]byte(`{"val": "extensions/v1beta1"}`), GroupVersion{"extensions", "v1beta1"}}, - } - - for _, c := range cases { - var result GroupVersionHolder - // test golang lib's JSON codec - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("JSON codec failed to unmarshal input '%v': %v", c.input, err) - } - if !reflect.DeepEqual(result.GV, c.expect) { - t.Errorf("JSON codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV) - } - // test the Ugorji codec - if err := codec.NewDecoderBytes(c.input, new(codec.JsonHandle)).Decode(&result); err != nil { - t.Errorf("Ugorji codec failed to unmarshal input '%v': %v", c.input, err) - } - if !reflect.DeepEqual(result.GV, c.expect) { - t.Errorf("Ugorji codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV) - } - } -} - -func TestGroupVersionMarshalJSON(t *testing.T) { - cases := []struct { - input GroupVersion - expect []byte - }{ - {GroupVersion{"", "v1"}, []byte(`{"val":"v1"}`)}, - {GroupVersion{"extensions", "v1beta1"}, []byte(`{"val":"extensions/v1beta1"}`)}, - } - - for _, c := range cases { - input := GroupVersionHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input '%v': %v", input, err) - } - if !reflect.DeepEqual(result, c.expect) { - t.Errorf("Failed to marshal input '%+v': expected: %s, got: %s", input, c.expect, result) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/helpers.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/helpers.go index b26948b4d..b71297ec5 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/helpers.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/helpers.go @@ -25,6 +25,7 @@ import ( // LabelSelectorAsSelector converts the LabelSelector api type into a struct that implements // labels.Selector +// Note: This function should be kept in sync with the selector methods in pkg/labels/selector.go func LabelSelectorAsSelector(ps *LabelSelector) (labels.Selector, error) { if ps == nil { return labels.Nothing(), nil @@ -34,7 +35,7 @@ func LabelSelectorAsSelector(ps *LabelSelector) (labels.Selector, error) { } selector := labels.NewSelector() for k, v := range ps.MatchLabels { - r, err := labels.NewRequirement(k, labels.InOperator, sets.NewString(v)) + r, err := labels.NewRequirement(k, labels.EqualsOperator, sets.NewString(v)) if err != nil { return nil, err } @@ -63,6 +64,55 @@ func LabelSelectorAsSelector(ps *LabelSelector) (labels.Selector, error) { 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) { + reqs, err := labels.ParseToRequirements(selector) + if err != nil { + return nil, fmt.Errorf("couldn't parse the selector string \"%s\": %v", selector, err) + } + + labelSelector := &LabelSelector{ + MatchLabels: map[string]string{}, + MatchExpressions: []LabelSelectorRequirement{}, + } + for _, req := range reqs { + var op LabelSelectorOperator + switch req.Operator() { + case labels.EqualsOperator, labels.DoubleEqualsOperator: + vals := req.Values() + if vals.Len() != 1 { + return nil, fmt.Errorf("equals operator must have exactly one value") + } + val, ok := vals.PopAny() + if !ok { + return nil, fmt.Errorf("equals operator has exactly one value but it cannot be retrieved") + } + labelSelector.MatchLabels[req.Key()] = val + continue + case labels.InOperator: + op = LabelSelectorOpIn + case labels.NotInOperator: + op = LabelSelectorOpNotIn + case labels.ExistsOperator: + op = LabelSelectorOpExists + case labels.DoesNotExistOperator: + op = LabelSelectorOpDoesNotExist + case labels.GreaterThanOperator, labels.LessThanOperator: + // Adding a separate case for these operators to indicate that this is deliberate + return nil, fmt.Errorf("%q isn't supported in label selectors", req.Operator()) + default: + return nil, fmt.Errorf("%q is not a valid label selector operator", req.Operator()) + } + labelSelector.MatchExpressions = append(labelSelector.MatchExpressions, LabelSelectorRequirement{ + Key: req.Key(), + Operator: op, + Values: req.Values().List(), + }) + } + return labelSelector, nil +} + // SetAsLabelSelector converts the labels.Set object into a LabelSelector api object. func SetAsLabelSelector(ls labels.Set) *LabelSelector { if ls == nil { @@ -92,3 +142,13 @@ func FormatLabelSelector(labelSelector *LabelSelector) string { } return l } + +func ExtractGroupVersions(l *APIGroupList) []string { + var groupVersions []string + for _, g := range l.Groups { + for _, gv := range g.Versions { + groupVersions = append(groupVersions, gv.GroupVersion) + } + } + return groupVersions +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/helpers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/helpers_test.go deleted file mode 100644 index 334c78597..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/helpers_test.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -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. -*/ - -package unversioned - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/labels" -) - -func TestLabelSelectorAsSelector(t *testing.T) { - matchLabels := map[string]string{"foo": "bar"} - matchExpressions := []LabelSelectorRequirement{{ - Key: "baz", - Operator: LabelSelectorOpIn, - Values: []string{"qux", "norf"}, - }} - mustParse := func(s string) labels.Selector { - out, e := labels.Parse(s) - if e != nil { - panic(e) - } - return out - } - tc := []struct { - in *LabelSelector - out labels.Selector - expectErr bool - }{ - {in: nil, out: labels.Nothing()}, - {in: &LabelSelector{}, out: labels.Everything()}, - { - in: &LabelSelector{MatchLabels: matchLabels}, - out: mustParse("foo in (bar)"), - }, - { - in: &LabelSelector{MatchExpressions: matchExpressions}, - out: mustParse("baz in (norf,qux)"), - }, - { - in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions}, - out: mustParse("foo in (bar),baz in (norf,qux)"), - }, - { - in: &LabelSelector{ - MatchExpressions: []LabelSelectorRequirement{{ - Key: "baz", - Operator: LabelSelectorOpExists, - Values: []string{"qux", "norf"}, - }}, - }, - expectErr: true, - }, - } - - for i, tc := range tc { - out, err := LabelSelectorAsSelector(tc.in) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - if !reflect.DeepEqual(out, tc.out) { - t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/time.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/time.go index 4072833d9..1180e6bd1 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/time.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/time.go @@ -97,6 +97,27 @@ func (t *Time) UnmarshalJSON(b []byte) error { return nil } +// UnmarshalQueryParameter converts from a URL query parameter value to an object +func (t *Time) UnmarshalQueryParameter(str string) error { + if len(str) == 0 { + t.Time = time.Time{} + return nil + } + // Tolerate requests from older clients that used JSON serialization to build query params + if len(str) == 4 && str == "null" { + t.Time = time.Time{} + return nil + } + + pt, err := time.Parse(time.RFC3339, str) + if err != nil { + return err + } + + t.Time = pt.Local() + return nil +} + // MarshalJSON implements the json.Marshaler interface. func (t Time) MarshalJSON() ([]byte, error) { if t.IsZero() { @@ -107,6 +128,16 @@ func (t Time) MarshalJSON() ([]byte, error) { return json.Marshal(t.UTC().Format(time.RFC3339)) } +// MarshalQueryParameter converts to a URL query parameter value +func (t Time) MarshalQueryParameter() (string, error) { + if t.IsZero() { + // Encode unset/nil objects as an empty string + return "", nil + } + + return t.UTC().Format(time.RFC3339), nil +} + // Fuzz satisfies fuzz.Interface. func (t *Time) Fuzz(c fuzz.Continue) { if t == nil { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/time_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/time_test.go deleted file mode 100644 index 2f4f3696d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/time_test.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "encoding/json" - "testing" - "time" - - "github.com/ghodss/yaml" -) - -type TimeHolder struct { - T Time `json:"t"` -} - -func TestTimeMarshalYAML(t *testing.T) { - cases := []struct { - input Time - result string - }{ - {Time{}, "t: null\n"}, - {Date(1998, time.May, 5, 1, 5, 5, 50, time.FixedZone("test", -4*60*60)), "t: 1998-05-05T05:05:05Z\n"}, - {Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "t: 1998-05-05T05:05:05Z\n"}, - } - - for _, c := range cases { - input := TimeHolder{c.input} - result, err := yaml.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestTimeUnmarshalYAML(t *testing.T) { - cases := []struct { - input string - result Time - }{ - {"t: null\n", Time{}}, - {"t: 1998-05-05T05:05:05Z\n", Time{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}}, - } - - for _, c := range cases { - var result TimeHolder - if err := yaml.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.T != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestTimeMarshalJSON(t *testing.T) { - cases := []struct { - input Time - result string - }{ - {Time{}, "{\"t\":null}"}, - {Date(1998, time.May, 5, 5, 5, 5, 50, time.UTC), "{\"t\":\"1998-05-05T05:05:05Z\"}"}, - {Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "{\"t\":\"1998-05-05T05:05:05Z\"}"}, - } - - for _, c := range cases { - input := TimeHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestTimeUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result Time - }{ - {"{\"t\":null}", Time{}}, - {"{\"t\":\"1998-05-05T05:05:05Z\"}", Time{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}}, - } - - for _, c := range cases { - var result TimeHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.T != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestTimeMarshalJSONUnmarshalYAML(t *testing.T) { - cases := []struct { - input Time - }{ - {Time{}}, - {Date(1998, time.May, 5, 5, 5, 5, 50, time.Local).Rfc3339Copy()}, - {Date(1998, time.May, 5, 5, 5, 5, 0, time.Local).Rfc3339Copy()}, - } - - for i, c := range cases { - input := TimeHolder{c.input} - jsonMarshalled, err := json.Marshal(&input) - if err != nil { - t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err) - } - - var result TimeHolder - err = yaml.Unmarshal(jsonMarshalled, &result) - if err != nil { - t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err) - } - - iN, iO := input.T.Zone() - oN, oO := result.T.Zone() - if iN != oN || iO != oO { - t.Errorf("%d-3: Time zones differ before and after serialization %s:%d %s:%d", i, iN, iO, oN, oO) - } - - if input.T.UnixNano() != result.T.UnixNano() { - t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types.go index 4d7a8f7d8..786be86cf 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types.go @@ -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/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#resources APIVersion string `json:"apiVersion,omitempty"` } @@ -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/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#concurrency-control-and-consistency ResourceVersion string `json:"resourceVersion,omitempty"` } @@ -75,12 +75,12 @@ type ExportOptions struct { type Status struct { TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds ListMeta `json:"metadata,omitempty"` // Status of the operation. // One of: "Success" or "Failure". - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status string `json:"status,omitempty"` // A human-readable description of the status of this operation. Message string `json:"message,omitempty"` @@ -112,7 +112,7 @@ type StatusDetails struct { Group string `json:"group,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind,omitempty"` // The Causes array includes more details associated with the StatusReason // failure. Not all StatusReasons may provide detailed causes. diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go index 9df14a044..b45a46e62 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go @@ -16,7 +16,7 @@ limitations under the License. package unversioned -// This file contains a collection of methods that can be used from go-resful to +// 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 // @@ -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/HEAD/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/release-1.2/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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/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.2/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/HEAD/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/release-1.2/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/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", + "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.2/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.2/docs/devel/api-conventions.md#resources", } func (TypeMeta) SwaggerDoc() map[string]string { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/validation/validation.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/validation/validation.go deleted file mode 100644 index f42f37b04..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/unversioned/validation/validation.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package validation - -import ( - "k8s.io/kubernetes/pkg/api/unversioned" - apivalidation "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -func ValidateLabelSelector(ps *unversioned.LabelSelector, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if ps == nil { - return allErrs - } - allErrs = append(allErrs, apivalidation.ValidateLabels(ps.MatchLabels, fldPath.Child("matchLabels"))...) - for i, expr := range ps.MatchExpressions { - allErrs = append(allErrs, ValidateLabelSelectorRequirement(expr, fldPath.Child("matchExpressions").Index(i))...) - } - return allErrs -} - -func ValidateLabelSelectorRequirement(sr unversioned.LabelSelectorRequirement, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - switch sr.Operator { - case unversioned.LabelSelectorOpIn, unversioned.LabelSelectorOpNotIn: - if len(sr.Values) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified when `operator` is 'In' or 'NotIn'")) - } - case unversioned.LabelSelectorOpExists, unversioned.LabelSelectorOpDoesNotExist: - if len(sr.Values) > 0 { - allErrs = append(allErrs, field.Forbidden(fldPath.Child("values"), "may not be specified when `operator` is 'Exists' or 'DoesNotExist'")) - } - default: - allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), sr.Operator, "not a valid selector operator")) - } - allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, fldPath.Child("key"))...) - return allErrs -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/util/group_version_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/util/group_version_test.go deleted file mode 100644 index d53b5f4e5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/util/group_version_test.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package util - -import "testing" - -func TestGetVersion(t *testing.T) { - testCases := []struct { - groupVersion string - output string - }{ - { - "v1", - "v1", - }, - { - "extensions/v1beta1", - "v1beta1", - }, - } - for _, test := range testCases { - actual := GetVersion(test.groupVersion) - if test.output != actual { - t.Errorf("expect version: %s, got: %s\n", test.output, actual) - } - } -} - -func TestGetGroup(t *testing.T) { - testCases := []struct { - groupVersion string - output string - }{ - { - "v1", - "", - }, - { - "extensions/v1beta1", - "extensions", - }, - } - for _, test := range testCases { - actual := GetGroup(test.groupVersion) - if test.output != actual { - t.Errorf("expect version: %s, got: %s\n", test.output, actual) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/backward_compatibility_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/backward_compatibility_test.go deleted file mode 100644 index 2ef3d926f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/backward_compatibility_test.go +++ /dev/null @@ -1,229 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package v1_test - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testing/compat" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -func TestCompatibility_v1_PodSecurityContext(t *testing.T) { - cases := []struct { - name string - input string - expectedKeys map[string]string - absentKeys []string - }{ - { - name: "hostNetwork = true", - input: ` -{ - "kind":"Pod", - "apiVersion":"v1", - "metadata":{"name":"my-pod-name", "namespace":"my-pod-namespace"}, - "spec": { - "hostNetwork": true, - "containers":[{ - "name":"a", - "image":"my-container-image" - }] - } -} -`, - expectedKeys: map[string]string{ - "spec.hostNetwork": "true", - }, - }, - { - name: "hostNetwork = false", - input: ` -{ - "kind":"Pod", - "apiVersion":"v1", - "metadata":{"name":"my-pod-name", "namespace":"my-pod-namespace"}, - "spec": { - "hostNetwork": false, - "containers":[{ - "name":"a", - "image":"my-container-image" - }] - } -} -`, - absentKeys: []string{ - "spec.hostNetwork", - }, - }, - { - name: "hostIPC = true", - input: ` -{ - "kind":"Pod", - "apiVersion":"v1", - "metadata":{"name":"my-pod-name", "namespace":"my-pod-namespace"}, - "spec": { - "hostIPC": true, - "containers":[{ - "name":"a", - "image":"my-container-image" - }] - } -} -`, - expectedKeys: map[string]string{ - "spec.hostIPC": "true", - }, - }, - { - name: "hostIPC = false", - input: ` -{ - "kind":"Pod", - "apiVersion":"v1", - "metadata":{"name":"my-pod-name", "namespace":"my-pod-namespace"}, - "spec": { - "hostIPC": false, - "containers":[{ - "name":"a", - "image":"my-container-image" - }] - } -} -`, - absentKeys: []string{ - "spec.hostIPC", - }, - }, - { - name: "hostPID = true", - input: ` -{ - "kind":"Pod", - "apiVersion":"v1", - "metadata":{"name":"my-pod-name", "namespace":"my-pod-namespace"}, - "spec": { - "hostPID": true, - "containers":[{ - "name":"a", - "image":"my-container-image" - }] - } -} -`, - expectedKeys: map[string]string{ - "spec.hostPID": "true", - }, - }, - { - name: "hostPID = false", - input: ` -{ - "kind":"Pod", - "apiVersion":"v1", - "metadata":{"name":"my-pod-name", "namespace":"my-pod-namespace"}, - "spec": { - "hostPID": false, - "containers":[{ - "name":"a", - "image":"my-container-image" - }] - } -} -`, - absentKeys: []string{ - "spec.hostPID", - }, - }, - { - name: "reseting defaults for pre-v1.1 mirror pods", - input: ` -{ - "kind":"Pod", - "apiVersion":"v1", - "metadata":{ - "name":"my-pod-name", - "namespace":"my-pod-namespace", - "annotations": { - "kubernetes.io/config.mirror": "mirror" - } - }, - "spec": { - "containers":[{ - "name":"a", - "image":"my-container-image", - "resources": { - "limits": { - "cpu": "100m" - } - } - }] - } -} -`, - absentKeys: []string{ - "spec.terminationGracePeriodSeconds", - "spec.containers[0].resources.requests", - }, - }, - { - name: "preserving defaults for v1.1+ mirror pods", - input: ` - { - "kind":"Pod", - "apiVersion":"v1", - "metadata":{ - "name":"my-pod-name", - "namespace":"my-pod-namespace", - "annotations": { - "kubernetes.io/config.mirror": "cbe924f710c7e26f7693d6a341bcfad0" - } - }, - "spec": { - "containers":[{ - "name":"a", - "image":"my-container-image", - "resources": { - "limits": { - "cpu": "100m" - } - } - }] - } - } - `, - expectedKeys: map[string]string{ - "spec.terminationGracePeriodSeconds": "30", - "spec.containers[0].resources.requests": "map[cpu:100m]", - }, - }, - } - - validator := func(obj runtime.Object) field.ErrorList { - return validation.ValidatePodSpec(&(obj.(*api.Pod).Spec), field.NewPath("spec")) - } - - for _, tc := range cases { - t.Logf("Testing 1.0.0 backward compatibility for %v", tc.name) - compat.TestCompatibility(t, v1.SchemeGroupVersion, []byte(tc.input), validator, tc.expectedKeys, tc.absentKeys) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/conversion_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/conversion_generated.go index a0e405e9e..687da425a 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/conversion_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/conversion_generated.go @@ -2598,6 +2598,7 @@ func autoConvert_api_ReplicationControllerStatus_To_v1_ReplicationControllerStat defaulting.(func(*api.ReplicationControllerStatus))(in) } out.Replicas = int32(in.Replicas) + out.FullyLabeledReplicas = int32(in.FullyLabeledReplicas) out.ObservedGeneration = in.ObservedGeneration return nil } @@ -2666,6 +2667,14 @@ func autoConvert_api_ResourceQuotaSpec_To_v1_ResourceQuotaSpec(in *api.ResourceQ } else { out.Hard = nil } + if in.Scopes != nil { + out.Scopes = make([]ResourceQuotaScope, len(in.Scopes)) + for i := range in.Scopes { + out.Scopes[i] = ResourceQuotaScope(in.Scopes[i]) + } + } else { + out.Scopes = nil + } return nil } @@ -5828,6 +5837,7 @@ func autoConvert_v1_ReplicationControllerStatus_To_api_ReplicationControllerStat defaulting.(func(*ReplicationControllerStatus))(in) } out.Replicas = int(in.Replicas) + out.FullyLabeledReplicas = int(in.FullyLabeledReplicas) out.ObservedGeneration = in.ObservedGeneration return nil } @@ -5887,6 +5897,14 @@ func autoConvert_v1_ResourceQuotaSpec_To_api_ResourceQuotaSpec(in *ResourceQuota if err := s.Convert(&in.Hard, &out.Hard, 0); err != nil { return err } + if in.Scopes != nil { + out.Scopes = make([]api.ResourceQuotaScope, len(in.Scopes)) + for i := range in.Scopes { + out.Scopes[i] = api.ResourceQuotaScope(in.Scopes[i]) + } + } else { + out.Scopes = nil + } return nil } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/conversion_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/conversion_test.go deleted file mode 100644 index 8cc2f0474..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/conversion_test.go +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package v1_test - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - versioned "k8s.io/kubernetes/pkg/api/v1" -) - -// TestPodSpecConversion tests that ServiceAccount is an alias for -// ServiceAccountName. -func TestPodSpecConversion(t *testing.T) { - name, other := "foo", "bar" - - // Test internal -> v1. Should have both alias (DeprecatedServiceAccount) - // and new field (ServiceAccountName). - i := &api.PodSpec{ - ServiceAccountName: name, - } - v := versioned.PodSpec{} - if err := api.Scheme.Convert(i, &v); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if v.ServiceAccountName != name { - t.Fatalf("want v1.ServiceAccountName %q, got %q", name, v.ServiceAccountName) - } - if v.DeprecatedServiceAccount != name { - t.Fatalf("want v1.DeprecatedServiceAccount %q, got %q", name, v.DeprecatedServiceAccount) - } - - // Test v1 -> internal. Either DeprecatedServiceAccount, ServiceAccountName, - // or both should translate to ServiceAccountName. ServiceAccountName wins - // if both are set. - testCases := []*versioned.PodSpec{ - // New - {ServiceAccountName: name}, - // Alias - {DeprecatedServiceAccount: name}, - // Both: same - {ServiceAccountName: name, DeprecatedServiceAccount: name}, - // Both: different - {ServiceAccountName: name, DeprecatedServiceAccount: other}, - } - for k, v := range testCases { - got := api.PodSpec{} - err := api.Scheme.Convert(v, &got) - if err != nil { - t.Fatalf("unexpected error for case %d: %v", k, err) - } - if got.ServiceAccountName != name { - t.Fatalf("want api.ServiceAccountName %q, got %q", name, got.ServiceAccountName) - } - } -} - -func TestResourceListConversion(t *testing.T) { - bigMilliQuantity := resource.NewQuantity(resource.MaxMilliValue, resource.DecimalSI) - bigMilliQuantity.Add(resource.MustParse("12345m")) - - tests := []struct { - input versioned.ResourceList - expected api.ResourceList - }{ - { // No changes necessary. - input: versioned.ResourceList{ - versioned.ResourceMemory: resource.MustParse("30M"), - versioned.ResourceCPU: resource.MustParse("100m"), - versioned.ResourceStorage: resource.MustParse("1G"), - }, - expected: api.ResourceList{ - api.ResourceMemory: resource.MustParse("30M"), - api.ResourceCPU: resource.MustParse("100m"), - api.ResourceStorage: resource.MustParse("1G"), - }, - }, - { // Nano-scale values should be rounded up to milli-scale. - input: versioned.ResourceList{ - versioned.ResourceCPU: resource.MustParse("3.000023m"), - versioned.ResourceMemory: resource.MustParse("500.000050m"), - }, - expected: api.ResourceList{ - api.ResourceCPU: resource.MustParse("4m"), - api.ResourceMemory: resource.MustParse("501m"), - }, - }, - { // Large values should still be accurate. - input: versioned.ResourceList{ - versioned.ResourceCPU: *bigMilliQuantity.Copy(), - versioned.ResourceStorage: *bigMilliQuantity.Copy(), - }, - expected: api.ResourceList{ - api.ResourceCPU: *bigMilliQuantity.Copy(), - api.ResourceStorage: *bigMilliQuantity.Copy(), - }, - }, - } - - output := api.ResourceList{} - for i, test := range tests { - err := api.Scheme.Convert(&test.input, &output) - if err != nil { - t.Fatalf("unexpected error for case %d: %v", i, err) - } - if !api.Semantic.DeepEqual(test.expected, output) { - t.Errorf("unexpected conversion for case %d: Expected %+v; Got %+v", i, test.expected, output) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/deep_copy_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/deep_copy_generated.go index f6aaedc88..1252bf4e6 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/deep_copy_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/deep_copy_generated.go @@ -2031,6 +2031,7 @@ func deepCopy_v1_ReplicationControllerSpec(in ReplicationControllerSpec, out *Re 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 } @@ -2084,6 +2085,14 @@ func deepCopy_v1_ResourceQuotaSpec(in ResourceQuotaSpec, out *ResourceQuotaSpec, } else { out.Hard = nil } + if in.Scopes != nil { + out.Scopes = make([]ResourceQuotaScope, len(in.Scopes)) + for i := range in.Scopes { + out.Scopes[i] = in.Scopes[i] + } + } else { + out.Scopes = nil + } return nil } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/defaults_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/defaults_test.go deleted file mode 100644 index b1a78e758..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/defaults_test.go +++ /dev/null @@ -1,645 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package v1_test - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - versioned "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/intstr" -) - -func roundTrip(t *testing.T, obj runtime.Object) runtime.Object { - codec := api.Codecs.LegacyCodec(versioned.SchemeGroupVersion) - data, err := runtime.Encode(codec, obj) - if err != nil { - t.Errorf("%v\n %#v", err, obj) - return nil - } - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), obj) - return nil - } - obj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object) - err = api.Scheme.Convert(obj2, obj3) - if err != nil { - t.Errorf("%v\nSource: %#v", err, obj2) - return nil - } - return obj3 -} - -func TestSetDefaultReplicationController(t *testing.T) { - tests := []struct { - rc *versioned.ReplicationController - expectLabels bool - expectSelector bool - }{ - { - rc: &versioned.ReplicationController{ - Spec: versioned.ReplicationControllerSpec{ - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: true, - expectSelector: true, - }, - { - rc: &versioned.ReplicationController{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: versioned.ReplicationControllerSpec{ - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: false, - expectSelector: true, - }, - { - rc: &versioned.ReplicationController{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: versioned.ReplicationControllerSpec{ - Selector: map[string]string{ - "some": "other", - }, - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: false, - expectSelector: false, - }, - { - rc: &versioned.ReplicationController{ - Spec: versioned.ReplicationControllerSpec{ - Selector: map[string]string{ - "some": "other", - }, - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: true, - expectSelector: false, - }, - } - - for _, test := range tests { - rc := test.rc - obj2 := roundTrip(t, runtime.Object(rc)) - rc2, ok := obj2.(*versioned.ReplicationController) - if !ok { - t.Errorf("unexpected object: %v", rc2) - t.FailNow() - } - if test.expectSelector != reflect.DeepEqual(rc2.Spec.Selector, rc2.Spec.Template.Labels) { - if test.expectSelector { - t.Errorf("expected: %v, got: %v", rc2.Spec.Template.Labels, rc2.Spec.Selector) - } else { - t.Errorf("unexpected equality: %v", rc.Spec.Selector) - } - } - if test.expectLabels != reflect.DeepEqual(rc2.Labels, rc2.Spec.Template.Labels) { - if test.expectLabels { - t.Errorf("expected: %v, got: %v", rc2.Spec.Template.Labels, rc2.Labels) - } else { - t.Errorf("unexpected equality: %v", rc.Labels) - } - } - } -} - -func newInt(val int32) *int32 { - p := new(int32) - *p = val - return p -} - -func TestSetDefaultReplicationControllerReplicas(t *testing.T) { - tests := []struct { - rc versioned.ReplicationController - expectReplicas int32 - }{ - { - rc: versioned.ReplicationController{ - Spec: versioned.ReplicationControllerSpec{ - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 1, - }, - { - rc: versioned.ReplicationController{ - Spec: versioned.ReplicationControllerSpec{ - Replicas: newInt(0), - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 0, - }, - { - rc: versioned.ReplicationController{ - Spec: versioned.ReplicationControllerSpec{ - Replicas: newInt(3), - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 3, - }, - } - - for _, test := range tests { - rc := &test.rc - obj2 := roundTrip(t, runtime.Object(rc)) - rc2, ok := obj2.(*versioned.ReplicationController) - if !ok { - t.Errorf("unexpected object: %v", rc2) - t.FailNow() - } - if rc2.Spec.Replicas == nil { - t.Errorf("unexpected nil Replicas") - } else if test.expectReplicas != *rc2.Spec.Replicas { - t.Errorf("expected: %d replicas, got: %d", test.expectReplicas, *rc2.Spec.Replicas) - } - } -} - -func TestSetDefaultService(t *testing.T) { - svc := &versioned.Service{} - obj2 := roundTrip(t, runtime.Object(svc)) - svc2 := obj2.(*versioned.Service) - if svc2.Spec.SessionAffinity != versioned.ServiceAffinityNone { - t.Errorf("Expected default session affinity type:%s, got: %s", versioned.ServiceAffinityNone, svc2.Spec.SessionAffinity) - } - if svc2.Spec.Type != versioned.ServiceTypeClusterIP { - t.Errorf("Expected default type:%s, got: %s", versioned.ServiceTypeClusterIP, svc2.Spec.Type) - } -} - -func TestSetDefaultSecret(t *testing.T) { - s := &versioned.Secret{} - obj2 := roundTrip(t, runtime.Object(s)) - s2 := obj2.(*versioned.Secret) - - if s2.Type != versioned.SecretTypeOpaque { - t.Errorf("Expected secret type %v, got %v", versioned.SecretTypeOpaque, s2.Type) - } -} - -func TestSetDefaultPersistentVolume(t *testing.T) { - pv := &versioned.PersistentVolume{} - obj2 := roundTrip(t, runtime.Object(pv)) - pv2 := obj2.(*versioned.PersistentVolume) - - if pv2.Status.Phase != versioned.VolumePending { - t.Errorf("Expected volume phase %v, got %v", versioned.VolumePending, pv2.Status.Phase) - } - if pv2.Spec.PersistentVolumeReclaimPolicy != versioned.PersistentVolumeReclaimRetain { - t.Errorf("Expected pv reclaim policy %v, got %v", versioned.PersistentVolumeReclaimRetain, pv2.Spec.PersistentVolumeReclaimPolicy) - } -} - -func TestSetDefaultPersistentVolumeClaim(t *testing.T) { - pvc := &versioned.PersistentVolumeClaim{} - obj2 := roundTrip(t, runtime.Object(pvc)) - pvc2 := obj2.(*versioned.PersistentVolumeClaim) - - if pvc2.Status.Phase != versioned.ClaimPending { - t.Errorf("Expected claim phase %v, got %v", versioned.ClaimPending, pvc2.Status.Phase) - } -} - -func TestSetDefaulEndpointsProtocol(t *testing.T) { - in := &versioned.Endpoints{Subsets: []versioned.EndpointSubset{ - {Ports: []versioned.EndpointPort{{}, {Protocol: "UDP"}, {}}}, - }} - obj := roundTrip(t, runtime.Object(in)) - out := obj.(*versioned.Endpoints) - - for i := range out.Subsets { - for j := range out.Subsets[i].Ports { - if in.Subsets[i].Ports[j].Protocol == "" { - if out.Subsets[i].Ports[j].Protocol != versioned.ProtocolTCP { - t.Errorf("Expected protocol %s, got %s", versioned.ProtocolTCP, out.Subsets[i].Ports[j].Protocol) - } - } else { - if out.Subsets[i].Ports[j].Protocol != in.Subsets[i].Ports[j].Protocol { - t.Errorf("Expected protocol %s, got %s", in.Subsets[i].Ports[j].Protocol, out.Subsets[i].Ports[j].Protocol) - } - } - } - } -} - -func TestSetDefaulServiceTargetPort(t *testing.T) { - in := &versioned.Service{Spec: versioned.ServiceSpec{Ports: []versioned.ServicePort{{Port: 1234}}}} - obj := roundTrip(t, runtime.Object(in)) - out := obj.(*versioned.Service) - if out.Spec.Ports[0].TargetPort != intstr.FromInt(1234) { - t.Errorf("Expected TargetPort to be defaulted, got %v", out.Spec.Ports[0].TargetPort) - } - - in = &versioned.Service{Spec: versioned.ServiceSpec{Ports: []versioned.ServicePort{{Port: 1234, TargetPort: intstr.FromInt(5678)}}}} - obj = roundTrip(t, runtime.Object(in)) - out = obj.(*versioned.Service) - if out.Spec.Ports[0].TargetPort != intstr.FromInt(5678) { - t.Errorf("Expected TargetPort to be unchanged, got %v", out.Spec.Ports[0].TargetPort) - } -} - -func TestSetDefaultServicePort(t *testing.T) { - // Unchanged if set. - in := &versioned.Service{Spec: versioned.ServiceSpec{ - Ports: []versioned.ServicePort{ - {Protocol: "UDP", Port: 9376, TargetPort: intstr.FromString("p")}, - {Protocol: "UDP", Port: 8675, TargetPort: intstr.FromInt(309)}, - }, - }} - out := roundTrip(t, runtime.Object(in)).(*versioned.Service) - if out.Spec.Ports[0].Protocol != versioned.ProtocolUDP { - t.Errorf("Expected protocol %s, got %s", versioned.ProtocolUDP, out.Spec.Ports[0].Protocol) - } - if out.Spec.Ports[0].TargetPort != intstr.FromString("p") { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort) - } - if out.Spec.Ports[1].Protocol != versioned.ProtocolUDP { - t.Errorf("Expected protocol %s, got %s", versioned.ProtocolUDP, out.Spec.Ports[1].Protocol) - } - if out.Spec.Ports[1].TargetPort != intstr.FromInt(309) { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort) - } - - // Defaulted. - in = &versioned.Service{Spec: versioned.ServiceSpec{ - Ports: []versioned.ServicePort{ - {Protocol: "", Port: 9376, TargetPort: intstr.FromString("")}, - {Protocol: "", Port: 8675, TargetPort: intstr.FromInt(0)}, - }, - }} - out = roundTrip(t, runtime.Object(in)).(*versioned.Service) - if out.Spec.Ports[0].Protocol != versioned.ProtocolTCP { - t.Errorf("Expected protocol %s, got %s", versioned.ProtocolTCP, out.Spec.Ports[0].Protocol) - } - if out.Spec.Ports[0].TargetPort != intstr.FromInt(int(in.Spec.Ports[0].Port)) { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort) - } - if out.Spec.Ports[1].Protocol != versioned.ProtocolTCP { - t.Errorf("Expected protocol %s, got %s", versioned.ProtocolTCP, out.Spec.Ports[1].Protocol) - } - if out.Spec.Ports[1].TargetPort != intstr.FromInt(int(in.Spec.Ports[1].Port)) { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort) - } -} - -func TestSetDefaultNamespace(t *testing.T) { - s := &versioned.Namespace{} - obj2 := roundTrip(t, runtime.Object(s)) - s2 := obj2.(*versioned.Namespace) - - if s2.Status.Phase != versioned.NamespaceActive { - t.Errorf("Expected phase %v, got %v", versioned.NamespaceActive, s2.Status.Phase) - } -} - -func TestSetDefaultPodSpecHostNetwork(t *testing.T) { - portNum := int32(8080) - s := versioned.PodSpec{} - s.HostNetwork = true - s.Containers = []versioned.Container{ - { - Ports: []versioned.ContainerPort{ - { - ContainerPort: portNum, - }, - }, - }, - } - pod := &versioned.Pod{ - Spec: s, - } - obj2 := roundTrip(t, runtime.Object(pod)) - pod2 := obj2.(*versioned.Pod) - s2 := pod2.Spec - - hostPortNum := s2.Containers[0].Ports[0].HostPort - if hostPortNum != portNum { - t.Errorf("Expected container port to be defaulted, was made %d instead of %d", hostPortNum, portNum) - } -} - -func TestSetDefaultNodeExternalID(t *testing.T) { - name := "node0" - n := &versioned.Node{} - n.Name = name - obj2 := roundTrip(t, runtime.Object(n)) - n2 := obj2.(*versioned.Node) - if n2.Spec.ExternalID != name { - t.Errorf("Expected default External ID: %s, got: %s", name, n2.Spec.ExternalID) - } - if n2.Spec.ProviderID != "" { - t.Errorf("Expected empty default Cloud Provider ID, got: %s", n2.Spec.ProviderID) - } -} - -func TestSetDefaultNodeStatusAllocatable(t *testing.T) { - capacity := versioned.ResourceList{ - versioned.ResourceCPU: resource.MustParse("1000m"), - versioned.ResourceMemory: resource.MustParse("10G"), - } - allocatable := versioned.ResourceList{ - versioned.ResourceCPU: resource.MustParse("500m"), - versioned.ResourceMemory: resource.MustParse("5G"), - } - tests := []struct { - capacity versioned.ResourceList - allocatable versioned.ResourceList - expectedAllocatable versioned.ResourceList - }{{ // Everything set, no defaulting. - capacity: capacity, - allocatable: allocatable, - expectedAllocatable: allocatable, - }, { // Allocatable set, no defaulting. - capacity: nil, - allocatable: allocatable, - expectedAllocatable: allocatable, - }, { // Capacity set, allocatable defaults to capacity. - capacity: capacity, - allocatable: nil, - expectedAllocatable: capacity, - }, { // Nothing set, allocatable "defaults" to capacity. - capacity: nil, - allocatable: nil, - expectedAllocatable: nil, - }} - - copyResourceList := func(rl versioned.ResourceList) versioned.ResourceList { - if rl == nil { - return nil - } - copy := make(versioned.ResourceList, len(rl)) - for k, v := range rl { - copy[k] = *v.Copy() - } - return copy - } - - resourceListsEqual := func(a versioned.ResourceList, b versioned.ResourceList) bool { - if len(a) != len(b) { - return false - } - for k, v := range a { - vb, found := b[k] - if !found { - return false - } - if v.Cmp(vb) != 0 { - return false - } - } - return true - } - - for i, testcase := range tests { - node := versioned.Node{ - Status: versioned.NodeStatus{ - Capacity: copyResourceList(testcase.capacity), - Allocatable: copyResourceList(testcase.allocatable), - }, - } - node2 := roundTrip(t, runtime.Object(&node)).(*versioned.Node) - actual := node2.Status.Allocatable - expected := testcase.expectedAllocatable - if !resourceListsEqual(expected, actual) { - t.Errorf("[%d] Expected NodeStatus.Allocatable: %+v; Got: %+v", i, expected, actual) - } - } -} - -func TestSetDefaultObjectFieldSelectorAPIVersion(t *testing.T) { - s := versioned.PodSpec{ - Containers: []versioned.Container{ - { - Env: []versioned.EnvVar{ - { - ValueFrom: &versioned.EnvVarSource{ - FieldRef: &versioned.ObjectFieldSelector{}, - }, - }, - }, - }, - }, - } - pod := &versioned.Pod{ - Spec: s, - } - obj2 := roundTrip(t, runtime.Object(pod)) - pod2 := obj2.(*versioned.Pod) - s2 := pod2.Spec - - apiVersion := s2.Containers[0].Env[0].ValueFrom.FieldRef.APIVersion - if apiVersion != "v1" { - t.Errorf("Expected default APIVersion v1, got: %v", apiVersion) - } -} - -func TestSetDefaultRequestsPod(t *testing.T) { - // verify we default if limits are specified - s := versioned.PodSpec{} - s.Containers = []versioned.Container{ - { - Resources: versioned.ResourceRequirements{ - Limits: versioned.ResourceList{ - versioned.ResourceCPU: resource.MustParse("100m"), - }, - }, - }, - } - pod := &versioned.Pod{ - Spec: s, - } - output := roundTrip(t, runtime.Object(pod)) - pod2 := output.(*versioned.Pod) - defaultRequest := pod2.Spec.Containers[0].Resources.Requests - requestValue := defaultRequest[versioned.ResourceCPU] - if requestValue.String() != "100m" { - t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String()) - } - - // verify we do nothing if no limits are specified - s = versioned.PodSpec{} - s.Containers = []versioned.Container{{}} - pod = &versioned.Pod{ - Spec: s, - } - output = roundTrip(t, runtime.Object(pod)) - pod2 = output.(*versioned.Pod) - defaultRequest = pod2.Spec.Containers[0].Resources.Requests - requestValue = defaultRequest[versioned.ResourceCPU] - if requestValue.String() != "0" { - t.Errorf("Expected 0 request value, got: %s", requestValue.String()) - } -} - -func TestDefaultRequestIsNotSetForReplicationController(t *testing.T) { - s := versioned.PodSpec{} - s.Containers = []versioned.Container{ - { - Resources: versioned.ResourceRequirements{ - Limits: versioned.ResourceList{ - versioned.ResourceCPU: resource.MustParse("100m"), - }, - }, - }, - } - rc := &versioned.ReplicationController{ - Spec: versioned.ReplicationControllerSpec{ - Replicas: newInt(3), - Template: &versioned.PodTemplateSpec{ - ObjectMeta: versioned.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - Spec: s, - }, - }, - } - output := roundTrip(t, runtime.Object(rc)) - rc2 := output.(*versioned.ReplicationController) - defaultRequest := rc2.Spec.Template.Spec.Containers[0].Resources.Requests - requestValue := defaultRequest[versioned.ResourceCPU] - if requestValue.String() != "0" { - t.Errorf("Expected 0 request value, got: %s", requestValue.String()) - } -} - -func TestSetDefaultLimitRangeItem(t *testing.T) { - limitRange := &versioned.LimitRange{ - ObjectMeta: versioned.ObjectMeta{ - Name: "test-defaults", - }, - Spec: versioned.LimitRangeSpec{ - Limits: []versioned.LimitRangeItem{{ - Type: versioned.LimitTypeContainer, - Max: versioned.ResourceList{ - versioned.ResourceCPU: resource.MustParse("100m"), - }, - Min: versioned.ResourceList{ - versioned.ResourceMemory: resource.MustParse("100Mi"), - }, - Default: versioned.ResourceList{}, - DefaultRequest: versioned.ResourceList{}, - }}, - }, - } - - output := roundTrip(t, runtime.Object(limitRange)) - limitRange2 := output.(*versioned.LimitRange) - defaultLimit := limitRange2.Spec.Limits[0].Default - defaultRequest := limitRange2.Spec.Limits[0].DefaultRequest - - // verify that default cpu was set to the max - defaultValue := defaultLimit[versioned.ResourceCPU] - if defaultValue.String() != "100m" { - t.Errorf("Expected default cpu: %s, got: %s", "100m", defaultValue.String()) - } - // verify that default request was set to the limit - requestValue := defaultRequest[versioned.ResourceCPU] - if requestValue.String() != "100m" { - t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String()) - } - // verify that if a min is provided, it will be the default if no limit is specified - requestMinValue := defaultRequest[versioned.ResourceMemory] - if requestMinValue.String() != "100Mi" { - t.Errorf("Expected request memory: %s, got: %s", "100Mi", requestMinValue.String()) - } -} - -func TestSetDefaultProbe(t *testing.T) { - originalProbe := versioned.Probe{} - expectedProbe := versioned.Probe{ - InitialDelaySeconds: 0, - TimeoutSeconds: 1, - PeriodSeconds: 10, - SuccessThreshold: 1, - FailureThreshold: 3, - } - - pod := &versioned.Pod{ - Spec: versioned.PodSpec{ - Containers: []versioned.Container{{LivenessProbe: &originalProbe}}, - }, - } - - output := roundTrip(t, runtime.Object(pod)).(*versioned.Pod) - actualProbe := *output.Spec.Containers[0].LivenessProbe - if actualProbe != expectedProbe { - t.Errorf("Expected probe: %+v\ngot: %+v\n", expectedProbe, actualProbe) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.generated.go index 18ae2139a..1dc4938a8 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.generated.go @@ -26683,13 +26683,14 @@ func (x *ReplicationControllerStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [2]bool + var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[1] = x.ObservedGeneration != 0 + yyq2[1] = x.FullyLabeledReplicas != 0 + yyq2[2] = x.ObservedGeneration != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(2) + r.EncodeArrayStart(3) } else { yynn2 = 1 for _, b := range yyq2 { @@ -26726,7 +26727,7 @@ func (x *ReplicationControllerStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym7 if false { } else { - r.EncodeInt(int64(x.ObservedGeneration)) + r.EncodeInt(int64(x.FullyLabeledReplicas)) } } else { r.EncodeInt(0) @@ -26734,11 +26735,36 @@ func (x *ReplicationControllerStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + r.EncodeString(codecSelferC_UTF81234, string("fullyLabeledReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { + } else { + r.EncodeInt(int64(x.FullyLabeledReplicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeInt(int64(x.ObservedGeneration)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { } else { r.EncodeInt(int64(x.ObservedGeneration)) } @@ -26811,6 +26837,12 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromMap(l int, d *codec1978 } else { x.Replicas = int32(r.DecodeInt(32)) } + case "fullyLabeledReplicas": + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int32(r.DecodeInt(32)) + } case "observedGeneration": if r.TryDecodeAsNil() { x.ObservedGeneration = 0 @@ -26828,16 +26860,16 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromArray(l int, d *codec19 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 + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -26847,13 +26879,29 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromArray(l int, d *codec19 } else { x.Replicas = int32(r.DecodeInt(32)) } - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int32(r.DecodeInt(32)) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -26864,17 +26912,17 @@ func (x *ReplicationControllerStatus) codecDecodeSelfFromArray(l int, d *codec19 x.ObservedGeneration = int64(r.DecodeInt(64)) } for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj6-1, "") + z.DecStructFieldNotFound(yyj7-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -43999,6 +44047,32 @@ func (x *LimitRangeList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } +func (x ResourceQuotaScope) 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 *ResourceQuotaScope) 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 *ResourceQuotaSpec) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -44013,13 +44087,14 @@ func (x *ResourceQuotaSpec) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [1]bool + var yyq2 [2]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[0] = len(x.Hard) != 0 + yyq2[1] = len(x.Scopes) != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(1) + r.EncodeArrayStart(2) } else { yynn2 = 0 for _, b := range yyq2 { @@ -44053,6 +44128,39 @@ func (x *ResourceQuotaSpec) CodecEncodeSelf(e *codec1978.Encoder) { } } } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.Scopes == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + h.encSliceResourceQuotaScope(([]ResourceQuotaScope)(x.Scopes), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("scopes")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Scopes == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + h.encSliceResourceQuotaScope(([]ResourceQuotaScope)(x.Scopes), e) + } + } + } + } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { @@ -44121,6 +44229,18 @@ func (x *ResourceQuotaSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) yyv4 := &x.Hard yyv4.CodecDecodeSelf(d) } + case "scopes": + if r.TryDecodeAsNil() { + x.Scopes = nil + } else { + yyv5 := &x.Scopes + yym6 := z.DecBinary() + _ = yym6 + if false { + } else { + h.decSliceResourceQuotaScope((*[]ResourceQuotaScope)(yyv5), d) + } + } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 @@ -44132,16 +44252,16 @@ func (x *ResourceQuotaSpec) 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 + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb5 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb5 { + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -44149,21 +44269,43 @@ func (x *ResourceQuotaSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder if r.TryDecodeAsNil() { x.Hard = nil } else { - yyv6 := &x.Hard - yyv6.CodecDecodeSelf(d) + yyv8 := &x.Hard + yyv8.CodecDecodeSelf(d) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Scopes = nil + } else { + yyv9 := &x.Scopes + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + h.decSliceResourceQuotaScope((*[]ResourceQuotaScope)(yyv9), d) + } } for { - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb5 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb5 { + if yyb7 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj5-1, "") + z.DecStructFieldNotFound(yyj7-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -53826,6 +53968,116 @@ func (x codecSelfer1234) decSliceLimitRange(v *[]LimitRange, d *codec1978.Decode } } +func (x codecSelfer1234) encSliceResourceQuotaScope(v []ResourceQuotaScope, 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) + yyv1.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceResourceQuotaScope(v *[]ResourceQuotaScope, 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 = []ResourceQuotaScope{} + 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) { + + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]ResourceQuotaScope, yyrl1) + } + } else { + yyv1 = make([]ResourceQuotaScope, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = "" + } else { + yyv1[yyj1] = ResourceQuotaScope(r.DecodeString()) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, "") + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = "" + } else { + yyv1[yyj1] = ResourceQuotaScope(r.DecodeString()) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, "") // var yyz1 ResourceQuotaScope + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = "" + } else { + yyv1[yyj1] = ResourceQuotaScope(r.DecodeString()) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []ResourceQuotaScope{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + func (x codecSelfer1234) encSliceResourceQuota(v []ResourceQuota, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -53865,7 +54117,7 @@ func (x codecSelfer1234) decSliceResourceQuota(v *[]ResourceQuota, d *codec1978. yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 216) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 240) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.go index ad4686ec9..12ad83191 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types.go @@ -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/HEAD/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names Name string `json:"name,omitempty"` // 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/HEAD/docs/devel/api-conventions.md#idempotency + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#idempotency GenerateName string `json:"generateName,omitempty"` // 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/HEAD/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/namespaces.md Namespace string `json:"namespace,omitempty"` // 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/HEAD/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#uids UID types.UID `json:"uid,omitempty"` // An opaque value that represents the internal version of this object that can @@ -124,13 +124,11 @@ type ObjectMeta struct { // Populated 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#concurrency-control-and-consistency ResourceVersion string `json:"resourceVersion,omitempty"` // A sequence number representing a specific generation of the desired state. - // Currently only implemented by replication controllers. - // Populated by the system. - // Read-only. + // Populated by the system. Read-only. Generation int64 `json:"generation,omitempty"` // CreationTimestamp is a timestamp representing the server time when this object was @@ -140,7 +138,7 @@ type ObjectMeta struct { // Populated by the system. // Read-only. // Null for lists. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata CreationTimestamp unversioned.Time `json:"creationTimestamp,omitempty"` // DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This @@ -156,7 +154,7 @@ type ObjectMeta struct { // // Populated by the system when a graceful deletion is requested. // Read-only. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata DeletionTimestamp *unversioned.Time `json:"deletionTimestamp,omitempty"` // Number of seconds allowed for this object to gracefully terminate before @@ -168,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/HEAD/docs/user-guide/labels.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md // TODO: replace map[string]string with labels.LabelSet type Labels map[string]string `json:"labels,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/annotations.md Annotations map[string]string `json:"annotations,omitempty"` } @@ -190,7 +188,7 @@ const ( type Volume struct { // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names Name string `json:"name"` // VolumeSource represents the location and type of the mounted volume. // If not specified, the Volume is implied to be an EmptyDir. @@ -205,50 +203,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/HEAD/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/release-1.2/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"` // EmptyDir represents a temporary directory that shares a pod's lifetime. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#emptydir EmptyDir *EmptyDirVolumeSource `json:"emptyDir,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#gcepersistentdisk GCEPersistentDisk *GCEPersistentDiskVolumeSource `json:"gcePersistentDisk,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#awselasticblockstore AWSElasticBlockStore *AWSElasticBlockStoreVolumeSource `json:"awsElasticBlockStore,omitempty"` // GitRepo represents a git repository at a particular revision. GitRepo *GitRepoVolumeSource `json:"gitRepo,omitempty"` // Secret represents a secret that should populate this volume. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#secrets + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#secrets Secret *SecretVolumeSource `json:"secret,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#nfs NFS *NFSVolumeSource `json:"nfs,omitempty"` // 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/iscsi/README.md + // More info: http://releases.k8s.io/release-1.2/examples/iscsi/README.md ISCSI *ISCSIVolumeSource `json:"iscsi,omitempty"` // Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/HEAD/examples/glusterfs/README.md + // More info: http://releases.k8s.io/release-1.2/examples/glusterfs/README.md Glusterfs *GlusterfsVolumeSource `json:"glusterfs,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims PersistentVolumeClaim *PersistentVolumeClaimVolumeSource `json:"persistentVolumeClaim,omitempty"` // RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md RBD *RBDVolumeSource `json:"rbd,omitempty"` // 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"` // 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 + // More info: http://releases.k8s.io/release-1.2/examples/mysql-cinder-pd/README.md Cinder *CinderVolumeSource `json:"cinder,omitempty"` // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime @@ -273,7 +271,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/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims ClaimName string `json:"claimName"` // Will force the ReadOnly setting in VolumeMounts. // Default false. @@ -285,33 +283,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/HEAD/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#gcepersistentdisk GCEPersistentDisk *GCEPersistentDiskVolumeSource `json:"gcePersistentDisk,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#awselasticblockstore AWSElasticBlockStore *AWSElasticBlockStoreVolumeSource `json:"awsElasticBlockStore,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#hostpath HostPath *HostPathVolumeSource `json:"hostPath,omitempty"` // 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/glusterfs/README.md + // More info: http://releases.k8s.io/release-1.2/examples/glusterfs/README.md Glusterfs *GlusterfsVolumeSource `json:"glusterfs,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#nfs NFS *NFSVolumeSource `json:"nfs,omitempty"` // RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md RBD *RBDVolumeSource `json:"rbd,omitempty"` // 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"` // 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 + // More info: http://releases.k8s.io/release-1.2/examples/mysql-cinder-pd/README.md Cinder *CinderVolumeSource `json:"cinder,omitempty"` // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime CephFS *CephFSVolumeSource `json:"cephfs,omitempty"` @@ -331,44 +329,44 @@ type PersistentVolumeSource struct { // 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 +// More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md type PersistentVolume struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistent-volumes Spec PersistentVolumeSpec `json:"spec,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistent-volumes Status PersistentVolumeStatus `json:"status,omitempty"` } // 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/HEAD/docs/user-guide/persistent-volumes.md#capacity + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#capacity Capacity ResourceList `json:"capacity,omitempty"` // The actual volume backing the persistent volume. PersistentVolumeSource `json:",inline"` // AccessModes contains all ways the volume can be mounted. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#access-modes AccessModes []PersistentVolumeAccessMode `json:"accessModes,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#binding ClaimRef *ObjectReference `json:"claimRef,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#recycling-policy PersistentVolumeReclaimPolicy PersistentVolumeReclaimPolicy `json:"persistentVolumeReclaimPolicy,omitempty"` } @@ -390,7 +388,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/HEAD/docs/user-guide/persistent-volumes.md#phase + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#phase Phase PersistentVolumePhase `json:"phase,omitempty"` // A human-readable message indicating details about why the volume is in this state. Message string `json:"message,omitempty"` @@ -403,10 +401,10 @@ type PersistentVolumeStatus struct { type PersistentVolumeList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of persistent volumes. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md Items []PersistentVolume `json:"items"` } @@ -414,16 +412,16 @@ type PersistentVolumeList struct { type PersistentVolumeClaim struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims Spec PersistentVolumeClaimSpec `json:"spec,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims Status PersistentVolumeClaimStatus `json:"status,omitempty"` } @@ -431,10 +429,10 @@ type PersistentVolumeClaim struct { type PersistentVolumeClaimList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // A list of persistent volume claims. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims Items []PersistentVolumeClaim `json:"items"` } @@ -442,10 +440,10 @@ 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/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#access-modes-1 AccessModes []PersistentVolumeAccessMode `json:"accessModes,omitempty"` // Resources represents the minimum resources the volume should have. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#resources Resources ResourceRequirements `json:"resources,omitempty"` // VolumeName is the binding reference to the PersistentVolume backing this claim. VolumeName string `json:"volumeName,omitempty"` @@ -456,7 +454,7 @@ type PersistentVolumeClaimStatus struct { // Phase represents the current phase of PersistentVolumeClaim. Phase PersistentVolumeClaimPhase `json:"phase,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#access-modes-1 AccessModes []PersistentVolumeAccessMode `json:"accessModes,omitempty"` // Represents the actual resources of the underlying volume. Capacity ResourceList `json:"capacity,omitempty"` @@ -504,7 +502,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/HEAD/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#hostpath Path string `json:"path"` } @@ -514,7 +512,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/HEAD/docs/user-guide/volumes.md#emptydir + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#emptydir Medium StorageMedium `json:"medium,omitempty"` } @@ -522,16 +520,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/HEAD/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/release-1.2/examples/glusterfs/README.md#create-a-pod EndpointsName string `json:"endpoints"` // Path is the Glusterfs volume path. - // More info: http://releases.k8s.io/HEAD/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/release-1.2/examples/glusterfs/README.md#create-a-pod Path string `json:"path"` // 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/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/release-1.2/examples/glusterfs/README.md#create-a-pod ReadOnly bool `json:"readOnly,omitempty"` } @@ -539,37 +537,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/HEAD/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it CephMonitors []string `json:"monitors"` // The rados image name. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it RBDImage string `json:"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/HEAD/docs/user-guide/volumes.md#rbd + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#rbd // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty"` // The rados pool name. // Default is rbd. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md#how-to-use-it. + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it. RBDPool string `json:"pool"` // The rados user name. // Default is admin. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it RadosUser string `json:"user"` // Keyring is the path to key ring for RBDUser. // Default is /etc/ceph/keyring. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it Keyring string `json:"keyring"` // SecretRef is name of the authentication secret for RBDUser. If provided // overrides keyring. // Default is empty. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it SecretRef *LocalObjectReference `json:"secretRef"` // ReadOnly here will force the ReadOnly setting in VolumeMounts. // Defaults to false. - // More info: http://releases.k8s.io/HEAD/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it ReadOnly bool `json:"readOnly,omitempty"` } @@ -579,16 +577,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/HEAD/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/release-1.2/examples/mysql-cinder-pd/README.md VolumeID string `json:"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/HEAD/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/release-1.2/examples/mysql-cinder-pd/README.md FSType string `json:"fsType,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/examples/mysql-cinder-pd/README.md ReadOnly bool `json:"readOnly,omitempty"` } @@ -596,22 +594,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/HEAD/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/cephfs/README.md#how-to-use-it Monitors []string `json:"monitors"` // Optional: Used as the mounted root, rather than the full Ceph tree, default is / Path string `json:"path,omitempty"` // Optional: User is the rados user name, default is admin - // More info: http://releases.k8s.io/HEAD/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/cephfs/README.md#how-to-use-it User string `json:"user,omitempty"` // Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret - // More info: http://releases.k8s.io/HEAD/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/cephfs/README.md#how-to-use-it SecretFile string `json:"secretFile,omitempty"` // Optional: SecretRef is reference to the authentication secret for User, default is empty. - // More info: http://releases.k8s.io/HEAD/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/cephfs/README.md#how-to-use-it SecretRef *LocalObjectReference `json:"secretRef,omitempty"` // Optional: Defaults to false (read/write). ReadOnly here will force // the ReadOnly setting in VolumeMounts. - // More info: http://releases.k8s.io/HEAD/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/release-1.2/examples/cephfs/README.md#how-to-use-it ReadOnly bool `json:"readOnly,omitempty"` } @@ -642,29 +640,29 @@ const ( // Represents a Persistent Disk resource in Google Compute Engine. // -// A GCE PD must exist and be formatted 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. -// GCE PDs support ownership management and SELinux relabeling. +// A 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. type GCEPersistentDiskVolumeSource struct { // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#gcepersistentdisk PDName string `json:"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/HEAD/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#gcepersistentdisk // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#gcepersistentdisk Partition int32 `json:"partition,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#gcepersistentdisk ReadOnly bool `json:"readOnly,omitempty"` } @@ -688,18 +686,18 @@ type FlexVolumeSource struct { // Represents a Persistent Disk resource in AWS. // -// An AWS EBS disk must exist and be formatted 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. +// An 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. type AWSElasticBlockStoreVolumeSource struct { // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#awselasticblockstore VolumeID string `json:"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/HEAD/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#awselasticblockstore // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty"` // The partition in the volume that you want to mount. @@ -709,7 +707,7 @@ type AWSElasticBlockStoreVolumeSource struct { Partition int32 `json:"partition,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#awselasticblockstore ReadOnly bool `json:"readOnly,omitempty"` } @@ -735,7 +733,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/HEAD/docs/user-guide/volumes.md#secrets + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#secrets SecretName string `json:"secretName,omitempty"` } @@ -743,17 +741,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/HEAD/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#nfs Server string `json:"server"` // Path that is exported by the NFS server. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#nfs Path string `json:"path"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#nfs ReadOnly bool `json:"readOnly,omitempty"` } @@ -773,7 +771,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/HEAD/docs/user-guide/volumes.md#iscsi + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#iscsi // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty"` // ReadOnly here will force the ReadOnly setting in VolumeMounts. @@ -868,7 +866,8 @@ type VolumeMount struct { // Mounted read-only if true, read-write otherwise (false or unspecified). // Defaults to false. ReadOnly bool `json:"readOnly,omitempty"` - // Path within the container at which the volume should be mounted. + // Path within the container at which the volume should be mounted. Must + // not contain ':'. MountPath string `json:"mountPath"` } @@ -986,11 +985,11 @@ type Probe struct { // The action taken to determine the health of a container Handler `json:",inline"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#container-probes InitialDelaySeconds int32 `json:"initialDelaySeconds,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#container-probes TimeoutSeconds int32 `json:"timeoutSeconds,omitempty"` // How often (in seconds) to perform the probe. // Default to 10 seconds. Minimum value is 1. @@ -1029,12 +1028,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/HEAD/docs/design/resources.md#resource-specifications + // More info: http://releases.k8s.io/release-1.2/docs/design/resources.md#resource-specifications Limits ResourceList `json:"limits,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/design/resources.md#resource-specifications Requests ResourceList `json:"requests,omitempty"` } @@ -1050,7 +1049,7 @@ type Container struct { // Cannot be updated. Name string `json:"name"` // Docker image name. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/images.md Image string `json:"image,omitempty"` // Entrypoint array. Not executed within a shell. // The docker image's ENTRYPOINT is used if this is not provided. @@ -1059,7 +1058,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/HEAD/docs/user-guide/containers.md#containers-and-commands + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/containers.md#containers-and-commands Command []string `json:"command,omitempty"` // Arguments to the entrypoint. // The docker image's CMD is used if this is not provided. @@ -1068,7 +1067,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/HEAD/docs/user-guide/containers.md#containers-and-commands + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/containers.md#containers-and-commands Args []string `json:"args,omitempty"` // Container's working directory. // If not specified, the container runtime's default will be used, which @@ -1088,7 +1087,7 @@ type Container struct { Env []EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name"` // Compute Resources required by this container. // Cannot be updated. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#resources Resources ResourceRequirements `json:"resources,omitempty"` // Pod volumes to mount into the container's filesyste. // Cannot be updated. @@ -1096,12 +1095,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/HEAD/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#container-probes LivenessProbe *Probe `json:"livenessProbe,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#container-probes ReadinessProbe *Probe `json:"readinessProbe,omitempty"` // Actions that the management system should take in response to container lifecycle events. // Cannot be updated. @@ -1116,10 +1115,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/HEAD/docs/user-guide/images.md#updating-images + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/images.md#updating-images ImagePullPolicy PullPolicy `json:"imagePullPolicy,omitempty"` // Security options the pod should run with. - // More info: http://releases.k8s.io/HEAD/docs/design/security_context.md + // More info: http://releases.k8s.io/release-1.2/docs/design/security_context.md SecurityContext *SecurityContext `json:"securityContext,omitempty"` // Variables for interactive containers, these have very specialized use-cases (e.g. debugging) @@ -1163,14 +1162,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/HEAD/docs/user-guide/container-environment.md#hook-details + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/container-environment.md#hook-details PostStart *Handler `json:"postStart,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/container-environment.md#hook-details PreStop *Handler `json:"preStop,omitempty"` } @@ -1247,13 +1246,13 @@ type ContainerStatus struct { // garbage collection. This value will get capped at 5 by GC. RestartCount int32 `json:"restartCount"` // The image the container is running. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/images.md // TODO(dchen1107): Which image the container is running with? Image string `json:"image"` // ImageID of the container's image. ImageID string `json:"imageID"` // Container's ID in the format 'docker://'. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#container-information + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/container-environment.md#container-information ContainerID string `json:"containerID,omitempty"` } @@ -1294,11 +1293,11 @@ const ( type PodCondition struct { // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#pod-conditions Type PodConditionType `json:"type"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#pod-conditions Status ConditionStatus `json:"status"` // Last time we probed the condition. LastProbeTime unversioned.Time `json:"lastProbeTime,omitempty"` @@ -1428,18 +1427,18 @@ type PreferredSchedulingTerm struct { // 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/HEAD/docs/user-guide/volumes.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md Volumes []Volume `json:"volumes,omitempty" 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/HEAD/docs/user-guide/containers.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/containers.md Containers []Container `json:"containers" patchStrategy:"merge" patchMergeKey:"name"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#restartpolicy RestartPolicy RestartPolicy `json:"restartPolicy,omitempty"` // 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. @@ -1459,11 +1458,11 @@ type PodSpec struct { DNSPolicy DNSPolicy `json:"dnsPolicy,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/node-selection/README.md NodeSelector map[string]string `json:"nodeSelector,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/design/service_accounts.md ServiceAccountName string `json:"serviceAccountName,omitempty"` // DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. // Deprecated: Use serviceAccountName instead. @@ -1489,7 +1488,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/HEAD/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod ImagePullSecrets []LocalObjectReference `json:"imagePullSecrets,omitempty" patchStrategy:"merge" patchMergeKey:"name"` } @@ -1536,10 +1535,10 @@ type PodSecurityContext struct { // state of a system. type PodStatus struct { // Current condition of the pod. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-phase + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#pod-phase Phase PodPhase `json:"phase,omitempty"` // Current service state of pod. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#pod-conditions Conditions []PodCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` // A human readable message indicating details about why the pod is in this condition. Message string `json:"message,omitempty"` @@ -1559,7 +1558,7 @@ type PodStatus struct { // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#container-statuses ContainerStatuses []ContainerStatus `json:"containerStatuses,omitempty"` } @@ -1567,13 +1566,13 @@ type PodStatus struct { type PodStatusResult struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status PodStatus `json:"status,omitempty"` } @@ -1584,18 +1583,18 @@ type PodStatusResult struct { type Pod struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Specification of the desired behavior of the pod. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec PodSpec `json:"spec,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status PodStatus `json:"status,omitempty"` } @@ -1603,22 +1602,22 @@ type Pod struct { type PodList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of pods. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/pods.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/pods.md Items []Pod `json:"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/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Specification of the desired behavior of the pod. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec PodSpec `json:"spec,omitempty"` } @@ -1628,11 +1627,11 @@ type PodTemplateSpec struct { type PodTemplate struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // 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 + // http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Template PodTemplateSpec `json:"template,omitempty"` } @@ -1640,7 +1639,7 @@ type PodTemplate struct { type PodTemplateList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of pod templates @@ -1652,14 +1651,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/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas *int32 `json:"replicas,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors Selector map[string]string `json:"selector,omitempty"` // TemplateRef is a reference to an object that describes the pod that will be created if @@ -1669,7 +1668,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/HEAD/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#pod-template Template *PodTemplateSpec `json:"template,omitempty"` } @@ -1677,9 +1676,12 @@ type ReplicationControllerSpec struct { // controller. type ReplicationControllerStatus struct { // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas int32 `json:"replicas"` + // The number of pods that have labels matching the labels of the pod template of the replication controller. + FullyLabeledReplicas int32 `json:"fullyLabeledReplicas,omitempty"` + // ObservedGeneration reflects the generation of the most recently observed replication controller. ObservedGeneration int64 `json:"observedGeneration,omitempty"` } @@ -1692,18 +1694,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/HEAD/docs/devel/api-conventions.md#metadata + // Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec ReplicationControllerSpec `json:"spec,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status ReplicationControllerStatus `json:"status,omitempty"` } @@ -1711,11 +1713,11 @@ type ReplicationController struct { type ReplicationControllerList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of replication controllers. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md Items []ReplicationController `json:"items"` } @@ -1777,13 +1779,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/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/services.md#virtual-ips-and-service-proxies Ports []ServicePort `json:"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/HEAD/docs/user-guide/services.md#overview + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/services.md#overview Selector map[string]string `json:"selector,omitempty"` // ClusterIP is usually assigned by the master and is the IP address of the service. @@ -1792,12 +1794,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/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/services.md#virtual-ips-and-service-proxies ClusterIP string `json:"clusterIP,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/services.md#external-services Type ServiceType `json:"type,omitempty"` // externalIPs is a list of IP addresses for which nodes in the cluster @@ -1820,7 +1822,7 @@ type ServiceSpec struct { // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/services.md#virtual-ips-and-service-proxies SessionAffinity ServiceAffinity `json:"sessionAffinity,omitempty"` // Only applies to Service Type: LoadBalancer @@ -1850,16 +1852,17 @@ type ServicePort struct { // 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 Port is used (an identity map). - // Defaults to the service port. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service + // 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.2/docs/user-guide/services.md#defining-a-service TargetPort intstr.IntOrString `json:"targetPort,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/services.md#type--nodeport NodePort int32 `json:"nodePort,omitempty"` } @@ -1871,17 +1874,17 @@ type ServicePort struct { type Service struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Spec defines the behavior of a service. - // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec ServiceSpec `json:"spec,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status ServiceStatus `json:"status,omitempty"` } @@ -1895,7 +1898,7 @@ const ( type ServiceList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of services @@ -1911,17 +1914,17 @@ type ServiceList struct { type ServiceAccount struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/secrets.md Secrets []ObjectReference `json:"secrets,omitempty" patchStrategy:"merge" patchMergeKey:"name"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret ImagePullSecrets []LocalObjectReference `json:"imagePullSecrets,omitempty"` } @@ -1929,11 +1932,11 @@ type ServiceAccount struct { type ServiceAccountList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of ServiceAccounts. - // More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md#service-accounts + // More info: http://releases.k8s.io/release-1.2/docs/design/service_accounts.md#service-accounts Items []ServiceAccount `json:"items"` } @@ -1954,7 +1957,7 @@ type ServiceAccountList struct { type Endpoints struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // The set of all endpoints is the union of all subsets. Addresses are placed into @@ -2021,7 +2024,7 @@ type EndpointPort struct { type EndpointsList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of endpoints. @@ -2038,7 +2041,7 @@ type NodeSpec struct { // ID of the node assigned by the cloud provider in the format: :// ProviderID string `json:"providerID,omitempty"` // 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"` + // More info: http://releases.k8s.io/release-1.2/docs/admin/node.md#manual-node-administration"` Unschedulable bool `json:"unschedulable,omitempty"` } @@ -2077,25 +2080,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/HEAD/docs/user-guide/persistent-volumes.md#capacity for more details. + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#capacity for more details. Capacity ResourceList `json:"capacity,omitempty"` // Allocatable represents the resources of a node that are available for scheduling. // Defaults to Capacity. Allocatable ResourceList `json:"allocatable,omitempty"` // NodePhase is the recently observed lifecycle phase of the node. - // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-phase + // More info: http://releases.k8s.io/release-1.2/docs/admin/node.md#node-phase Phase NodePhase `json:"phase,omitempty"` // Conditions is an array of current observed node conditions. - // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-condition + // More info: http://releases.k8s.io/release-1.2/docs/admin/node.md#node-condition Conditions []NodeCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/admin/node.md#node-addresses Addresses []NodeAddress `json:"addresses,omitempty" patchStrategy:"merge" patchMergeKey:"type"` // Endpoints of daemons running on the Node. DaemonEndpoints NodeDaemonEndpoints `json:"daemonEndpoints,omitempty"` // Set of ids/uuids to uniquely identify the node. - // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-info + // More info: http://releases.k8s.io/release-1.2/docs/admin/node.md#node-info NodeInfo NodeSystemInfo `json:"nodeInfo,omitempty"` // List of container images on this node Images []ContainerImage `json:"images",omitempty` @@ -2190,17 +2193,17 @@ type ResourceList map[ResourceName]resource.Quantity type Node struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Spec defines the behavior of a node. - // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec NodeSpec `json:"spec,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status NodeStatus `json:"status,omitempty"` } @@ -2208,7 +2211,7 @@ type Node struct { type NodeList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of nodes @@ -2225,14 +2228,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/HEAD/docs/design/namespaces.md#finalizers + // More info: http://releases.k8s.io/release-1.2/docs/design/namespaces.md#finalizers Finalizers []FinalizerName `json:"finalizers,omitempty"` } // 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/HEAD/docs/design/namespaces.md#phases + // More info: http://releases.k8s.io/release-1.2/docs/design/namespaces.md#phases Phase NamespacePhase `json:"phase,omitempty"` } @@ -2253,15 +2256,15 @@ const ( type Namespace struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Spec defines the behavior of the Namespace. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec NamespaceSpec `json:"spec,omitempty"` // Status describes the current status of a Namespace. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status NamespaceStatus `json:"status,omitempty"` } @@ -2269,11 +2272,11 @@ type Namespace struct { type NamespaceList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of Namespace objects in the list. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/namespaces.md Items []Namespace `json:"items"` } @@ -2282,7 +2285,7 @@ type NamespaceList struct { type Binding struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // The target object that you want to bind to the standard object. @@ -2454,21 +2457,21 @@ type ServiceProxyOptions 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/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind,omitempty"` // Namespace of the referent. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/namespaces.md Namespace string `json:"namespace,omitempty"` // Name of the referent. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names Name string `json:"name,omitempty"` // UID of the referent. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#uids UID types.UID `json:"uid,omitempty"` // API version of the referent. APIVersion string `json:"apiVersion,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#concurrency-control-and-consistency ResourceVersion string `json:"resourceVersion,omitempty"` // If referring to a piece of an object instead of an entire object, this string @@ -2486,7 +2489,7 @@ type ObjectReference struct { // referenced object inside the same namespace. type LocalObjectReference struct { // Name of the referent. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names // TODO: Add other useful fields. apiVersion, kind, uid? Name string `json:"name,omitempty"` } @@ -2521,7 +2524,7 @@ const ( type Event struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata"` // The object that this event is about. @@ -2556,7 +2559,7 @@ type Event struct { type EventList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of events @@ -2567,7 +2570,7 @@ type EventList struct { type List struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of objects @@ -2612,11 +2615,11 @@ type LimitRangeSpec struct { type LimitRange struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Spec defines the limits enforced. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec LimitRangeSpec `json:"spec,omitempty"` } @@ -2624,11 +2627,11 @@ type LimitRange struct { type LimitRangeList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of LimitRange objects. - // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_limit_range.md + // More info: http://releases.k8s.io/release-1.2/docs/design/admission_control_limit_range.md Items []LimitRange `json:"items"` } @@ -2644,21 +2647,48 @@ const ( ResourceQuotas ResourceName = "resourcequotas" // ResourceSecrets, number ResourceSecrets ResourceName = "secrets" + // ResourceConfigMaps, number + ResourceConfigMaps ResourceName = "configmaps" // ResourcePersistentVolumeClaims, number ResourcePersistentVolumeClaims ResourceName = "persistentvolumeclaims" + // CPU request, in cores. (500m = .5 cores) + ResourceCPURequest ResourceName = "cpu.request" + // CPU limit, in cores. (500m = .5 cores) + ResourceCPULimit ResourceName = "cpu.limit" + // Memory request, in bytes. (500Gi = 500GiB = 500 * 1024 * 1024 * 1024) + ResourceMemoryRequest ResourceName = "memory.request" + // Memory limit, in bytes. (500Gi = 500GiB = 500 * 1024 * 1024 * 1024) + ResourceMemoryLimit ResourceName = "memory.limit" +) + +// A ResourceQuotaScope defines a filter that must match each object tracked by a quota +type ResourceQuotaScope string + +const ( + // Match all pod objects where spec.activeDeadlineSeconds + ResourceQuotaScopeTerminating ResourceQuotaScope = "Terminating" + // Match all pod objects where !spec.activeDeadlineSeconds + ResourceQuotaScopeNotTerminating ResourceQuotaScope = "NotTerminating" + // Match all pod objects that have best effort quality of service + ResourceQuotaScopeBestEffort ResourceQuotaScope = "BestEffort" + // Match all pod objects that do not have best effort quality of service + ResourceQuotaScopeNotBestEffort ResourceQuotaScope = "NotBestEffort" ) // 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/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/release-1.2/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota Hard ResourceList `json:"hard,omitempty"` + // A collection of filters that must match each object tracked by a quota. + // If not specified, the quota matches all objects. + Scopes []ResourceQuotaScope `json:"scopes,omitempty"` } // 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/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/release-1.2/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota Hard ResourceList `json:"hard,omitempty"` // Used is the current observed total usage of the resource in the namespace. Used ResourceList `json:"used,omitempty"` @@ -2670,15 +2700,15 @@ type ResourceQuotaStatus struct { type ResourceQuota struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Spec defines the desired quota. - // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec ResourceQuotaSpec `json:"spec,omitempty"` // Status defines the actual enforced quota and its current usage. - // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status ResourceQuotaStatus `json:"status,omitempty"` } @@ -2686,11 +2716,11 @@ type ResourceQuota struct { type ResourceQuotaList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of ResourceQuota objects. - // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/release-1.2/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota Items []ResourceQuota `json:"items"` } @@ -2701,7 +2731,7 @@ type ResourceQuotaList struct { type Secret struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Data contains the secret data. Each key must be a valid DNS_SUBDOMAIN @@ -2773,11 +2803,11 @@ const ( type SecretList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of secret objects. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/secrets.md Items []Secret `json:"items"` } @@ -2787,7 +2817,7 @@ type SecretList struct { type ConfigMap struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Data contains the configuration data. @@ -2799,7 +2829,7 @@ type ConfigMap struct { type ConfigMapList struct { unversioned.TypeMeta `json:",inline"` - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of ConfigMaps. @@ -2836,7 +2866,7 @@ type ComponentCondition struct { type ComponentStatus struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // List of component conditions observed @@ -2847,7 +2877,7 @@ type ComponentStatus struct { type ComponentStatusList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of ComponentStatus objects. @@ -2918,7 +2948,7 @@ type SELinuxOptions struct { type RangeAllocation struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty"` // Range is string that identifies the range represented by 'data'. diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go index 4a7bd2dba..f1878b548 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go @@ -16,7 +16,7 @@ limitations under the License. package v1 -// This file contains a collection of methods that can be used from go-resful to +// 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 // @@ -28,11 +28,11 @@ 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 and be formatted 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/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", + "": "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.2/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.2/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/HEAD/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/release-1.2/docs/user-guide/volumes.md#awselasticblockstore", } func (AWSElasticBlockStoreVolumeSource) SwaggerDoc() map[string]string { @@ -61,7 +61,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "target": "The target object that you want to bind to the standard object.", } @@ -81,12 +81,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/HEAD/examples/cephfs/README.md#how-to-use-it", + "monitors": "Required: Monitors is a collection of Ceph monitors More info: http://releases.k8s.io/release-1.2/examples/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/HEAD/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/HEAD/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/HEAD/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/HEAD/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/release-1.2/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.2/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.2/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.2/examples/cephfs/README.md#how-to-use-it", } func (CephFSVolumeSource) SwaggerDoc() map[string]string { @@ -95,9 +95,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/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", + "volumeID": "volume id used to identify the volume in cinder More info: http://releases.k8s.io/release-1.2/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.2/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.2/examples/mysql-cinder-pd/README.md", } func (CinderVolumeSource) SwaggerDoc() map[string]string { @@ -118,7 +118,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "conditions": "List of component conditions observed", } @@ -128,7 +128,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/HEAD/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", "items": "List of ComponentStatus objects.", } @@ -138,7 +138,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.", } @@ -157,7 +157,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "items": "Items is the list of ConfigMaps.", } @@ -177,20 +177,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/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", + "image": "Docker image name. More info: http://releases.k8s.io/release-1.2/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.2/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.2/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/HEAD/docs/user-guide/persistent-volumes.md#resources", + "resources": "Compute Resources required by this container. Cannot be updated. More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#resources", "volumeMounts": "Pod volumes to mount into the container's filesyste. 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/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", + "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.2/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.2/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/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", + "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.2/docs/user-guide/images.md#updating-images", + "securityContext": "Security options the pod should run with. More info: http://releases.k8s.io/release-1.2/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.", @@ -275,9 +275,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/HEAD/docs/user-guide/images.md", + "image": "The image the container is running. More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/user-guide/container-environment.md#container-information", + "containerID": "Container's ID in the format 'docker://'. More info: http://releases.k8s.io/release-1.2/docs/user-guide/container-environment.md#container-information", } func (ContainerStatus) SwaggerDoc() map[string]string { @@ -323,7 +323,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/HEAD/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/release-1.2/docs/user-guide/volumes.md#emptydir", } func (EmptyDirVolumeSource) SwaggerDoc() map[string]string { @@ -364,7 +364,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.", } @@ -374,7 +374,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/HEAD/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", "items": "List of endpoints.", } @@ -406,7 +406,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.", @@ -423,7 +423,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/HEAD/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", "items": "List of events", } @@ -495,11 +495,11 @@ 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 and be formatted 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. 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/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", + "": "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.2/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.2/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.2/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.2/docs/user-guide/volumes.md#gcepersistentdisk", } func (GCEPersistentDiskVolumeSource) SwaggerDoc() map[string]string { @@ -519,9 +519,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/HEAD/examples/glusterfs/README.md#create-a-pod", - "path": "Path is the Glusterfs volume path. More info: http://releases.k8s.io/HEAD/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/HEAD/examples/glusterfs/README.md#create-a-pod", + "endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: http://releases.k8s.io/release-1.2/examples/glusterfs/README.md#create-a-pod", + "path": "Path is the Glusterfs volume path. More info: http://releases.k8s.io/release-1.2/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.2/examples/glusterfs/README.md#create-a-pod", } func (GlusterfsVolumeSource) SwaggerDoc() map[string]string { @@ -564,7 +564,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/HEAD/docs/user-guide/volumes.md#hostpath", + "path": "Path of the directory on the host. More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#hostpath", } func (HostPathVolumeSource) SwaggerDoc() map[string]string { @@ -577,7 +577,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/HEAD/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/release-1.2/docs/user-guide/volumes.md#iscsi", "readOnly": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", } @@ -597,8 +597,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/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", + "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.2/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.2/docs/user-guide/container-environment.md#hook-details", } func (Lifecycle) SwaggerDoc() map[string]string { @@ -607,8 +607,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the limits enforced. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status", } func (LimitRange) SwaggerDoc() map[string]string { @@ -631,8 +631,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "Items is a list of LimitRange objects. More info: http://releases.k8s.io/release-1.2/docs/design/admission_control_limit_range.md", } func (LimitRangeList) SwaggerDoc() map[string]string { @@ -650,7 +650,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/HEAD/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", "items": "List of objects", } @@ -692,7 +692,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/HEAD/docs/user-guide/identifiers.md#names", + "name": "Name of the referent. More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names", } func (LocalObjectReference) SwaggerDoc() map[string]string { @@ -701,9 +701,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/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", + "server": "Server is the hostname or IP address of the NFS server. More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#nfs", + "path": "Path that is exported by the NFS server. More info: http://releases.k8s.io/release-1.2/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.2/docs/user-guide/volumes.md#nfs", } func (NFSVolumeSource) SwaggerDoc() map[string]string { @@ -712,9 +712,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the behavior of the Namespace. More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (Namespace) SwaggerDoc() map[string]string { @@ -723,8 +723,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/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.2/docs/user-guide/namespaces.md", } func (NamespaceList) SwaggerDoc() map[string]string { @@ -733,7 +733,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/HEAD/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/release-1.2/docs/design/namespaces.md#finalizers", } func (NamespaceSpec) SwaggerDoc() map[string]string { @@ -742,7 +742,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/HEAD/docs/design/namespaces.md#phases", + "phase": "Phase is the current lifecycle phase of the namespace. More info: http://releases.k8s.io/release-1.2/docs/design/namespaces.md#phases", } func (NamespaceStatus) SwaggerDoc() map[string]string { @@ -751,9 +751,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the behavior of a node. http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (Node) SwaggerDoc() map[string]string { @@ -805,7 +805,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/HEAD/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", "items": "List of nodes", } @@ -856,7 +856,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/HEAD/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/release-1.2/docs/admin/node.md#manual-node-administration\"`", } func (NodeSpec) SwaggerDoc() map[string]string { @@ -865,13 +865,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/HEAD/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/release-1.2/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/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", + "phase": "NodePhase is the recently observed lifecycle phase of the node. More info: http://releases.k8s.io/release-1.2/docs/admin/node.md#node-phase", + "conditions": "Conditions is an array of current observed node conditions. More info: http://releases.k8s.io/release-1.2/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.2/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/HEAD/docs/admin/node.md#node-info", + "nodeInfo": "Set of ids/uuids to uniquely identify the node. More info: http://releases.k8s.io/release-1.2/docs/admin/node.md#node-info", "images": "List of container images on this node", } @@ -907,18 +907,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/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", + "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.2/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.2/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.2/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/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. Currently only implemented by replication controllers. 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/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", + "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.2/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.2/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.2/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.2/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/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", + "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.2/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.2/docs/user-guide/annotations.md", } func (ObjectMeta) SwaggerDoc() map[string]string { @@ -927,12 +927,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/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", + "kind": "Kind of the referent. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "namespace": "Namespace of the referent. More info: http://releases.k8s.io/release-1.2/docs/user-guide/namespaces.md", + "name": "Name of the referent. More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names", + "uid": "UID of the referent. More info: http://releases.k8s.io/release-1.2/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/HEAD/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/release-1.2/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.", } @@ -941,10 +941,10 @@ func (ObjectReference) 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/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", + "": "PersistentVolume (PV) is a storage resource provisioned by an administrator. It is analogous to a node. More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.2/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.2/docs/user-guide/persistent-volumes.md#persistent-volumes", } func (PersistentVolume) SwaggerDoc() map[string]string { @@ -953,9 +953,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.2/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.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", } func (PersistentVolumeClaim) SwaggerDoc() map[string]string { @@ -964,8 +964,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "A list of persistent volume claims. More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", } func (PersistentVolumeClaimList) SwaggerDoc() map[string]string { @@ -974,8 +974,8 @@ 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/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1", - "resources": "Resources represents the minimum resources the volume should have. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources", + "accessModes": "AccessModes contains the desired access modes the volume should have. More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#access-modes-1", + "resources": "Resources represents the minimum resources the volume should have. More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md#resources", "volumeName": "VolumeName is the binding reference to the PersistentVolume backing this claim.", } @@ -986,7 +986,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/HEAD/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/release-1.2/docs/user-guide/persistent-volumes.md#access-modes-1", "capacity": "Represents the actual resources of the underlying volume.", } @@ -996,7 +996,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/HEAD/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/release-1.2/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", "readOnly": "Will force the ReadOnly setting in VolumeMounts. Default false.", } @@ -1006,8 +1006,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "List of persistent volumes. More info: http://releases.k8s.io/release-1.2/docs/user-guide/persistent-volumes.md", } func (PersistentVolumeList) SwaggerDoc() map[string]string { @@ -1016,14 +1016,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/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/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/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/release-1.2/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.2/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.2/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.2/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.2/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.2/examples/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/HEAD/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/release-1.2/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", @@ -1037,10 +1037,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/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", + "capacity": "A description of the persistent volume's resources and capacity. More info: http://releases.k8s.io/release-1.2/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.2/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.2/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.2/docs/user-guide/persistent-volumes.md#recycling-policy", } func (PersistentVolumeSpec) SwaggerDoc() map[string]string { @@ -1049,7 +1049,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/HEAD/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/release-1.2/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.", } @@ -1060,9 +1060,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Specification of the desired behavior of the pod. More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (Pod) SwaggerDoc() map[string]string { @@ -1084,8 +1084,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/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", + "type": "Type is the type of the condition. Currently only Ready. More info: http://releases.k8s.io/release-1.2/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.2/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.", @@ -1112,8 +1112,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/HEAD/docs/devel/api-conventions.md#types-kinds", - "items": "List of pods. More info: http://releases.k8s.io/HEAD/docs/user-guide/pods.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "List of pods. More info: http://releases.k8s.io/release-1.2/docs/user-guide/pods.md", } func (PodList) SwaggerDoc() map[string]string { @@ -1160,21 +1160,21 @@ func (PodSecurityContext) SwaggerDoc() map[string]string { 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/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", + "volumes": "List of volumes that can be mounted by containers belonging to the pod. More info: http://releases.k8s.io/release-1.2/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.2/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.2/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/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", + "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.2/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.2/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/HEAD/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/release-1.2/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod", } func (PodSpec) SwaggerDoc() map[string]string { @@ -1183,14 +1183,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/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", + "phase": "Current condition of the pod. More info: http://releases.k8s.io/release-1.2/docs/user-guide/pod-states.md#pod-phase", + "conditions": "Current service state of pod. More info: http://releases.k8s.io/release-1.2/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/HEAD/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/release-1.2/docs/user-guide/pod-states.md#container-statuses", } func (PodStatus) SwaggerDoc() map[string]string { @@ -1199,8 +1199,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (PodStatusResult) SwaggerDoc() map[string]string { @@ -1209,8 +1209,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (PodTemplate) SwaggerDoc() map[string]string { @@ -1219,7 +1219,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/HEAD/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", "items": "List of pod templates", } @@ -1229,8 +1229,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Specification of the desired behavior of the pod. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status", } func (PodTemplateSpec) SwaggerDoc() map[string]string { @@ -1249,8 +1249,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/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", + "initialDelaySeconds": "Number of seconds after the container has started before liveness probes are initiated. More info: http://releases.k8s.io/release-1.2/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.2/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.", @@ -1262,14 +1262,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/HEAD/examples/rbd/README.md#how-to-use-it", - "image": "The rados image name. More info: http://releases.k8s.io/HEAD/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/HEAD/docs/user-guide/volumes.md#rbd", - "pool": "The rados pool name. Default is rbd. More info: http://releases.k8s.io/HEAD/examples/rbd/README.md#how-to-use-it.", - "user": "The rados user name. Default is admin. More info: http://releases.k8s.io/HEAD/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/HEAD/examples/rbd/README.md#how-to-use-it", - "secretRef": "SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is empty. More info: http://releases.k8s.io/HEAD/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/HEAD/examples/rbd/README.md#how-to-use-it", + "monitors": "A collection of Ceph monitors. More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it", + "image": "The rados image name. More info: http://releases.k8s.io/release-1.2/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.2/docs/user-guide/volumes.md#rbd", + "pool": "The rados pool name. Default is rbd. More info: http://releases.k8s.io/release-1.2/examples/rbd/README.md#how-to-use-it.", + "user": "The rados user name. Default is admin. More info: http://releases.k8s.io/release-1.2/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.2/examples/rbd/README.md#how-to-use-it", + "secretRef": "SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is empty. More info: http://releases.k8s.io/release-1.2/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.2/examples/rbd/README.md#how-to-use-it", } func (RBDVolumeSource) SwaggerDoc() map[string]string { @@ -1278,7 +1278,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.", } @@ -1289,9 +1289,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/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", + "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.2/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.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (ReplicationController) SwaggerDoc() map[string]string { @@ -1300,8 +1300,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "List of replication controllers. More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md", } func (ReplicationControllerList) SwaggerDoc() map[string]string { @@ -1310,9 +1310,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/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", + "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.2/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.2/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.2/docs/user-guide/replication-controller.md#pod-template", } func (ReplicationControllerSpec) SwaggerDoc() map[string]string { @@ -1320,9 +1320,10 @@ 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/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller", - "observedGeneration": "ObservedGeneration reflects the generation of the most recently observed replication controller.", + "": "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.2/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.", } func (ReplicationControllerStatus) SwaggerDoc() map[string]string { @@ -1331,9 +1332,9 @@ func (ReplicationControllerStatus) 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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the desired quota. http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (ResourceQuota) SwaggerDoc() map[string]string { @@ -1342,8 +1343,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "Items is a list of ResourceQuota objects. More info: http://releases.k8s.io/release-1.2/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", } func (ResourceQuotaList) SwaggerDoc() map[string]string { @@ -1351,8 +1352,9 @@ 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/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", + "": "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.2/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.", } func (ResourceQuotaSpec) SwaggerDoc() map[string]string { @@ -1361,7 +1363,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/HEAD/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/release-1.2/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", "used": "Used is the current observed total usage of the resource in the namespace.", } @@ -1371,8 +1373,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/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", + "limits": "Limits describes the maximum amount of compute resources allowed. More info: http://releases.k8s.io/release-1.2/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.2/docs/design/resources.md#resource-specifications", } func (ResourceRequirements) SwaggerDoc() map[string]string { @@ -1393,7 +1395,7 @@ 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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.", } @@ -1413,8 +1415,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "Items is a list of secret objects. More info: http://releases.k8s.io/release-1.2/docs/user-guide/secrets.md", } func (SecretList) SwaggerDoc() map[string]string { @@ -1423,7 +1425,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/HEAD/docs/user-guide/volumes.md#secrets", + "secretName": "Name of the secret in the pod's namespace to use. More info: http://releases.k8s.io/release-1.2/docs/user-guide/volumes.md#secrets", } func (SecretVolumeSource) SwaggerDoc() map[string]string { @@ -1455,9 +1457,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the behavior of a service. http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (Service) SwaggerDoc() map[string]string { @@ -1466,9 +1468,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.2/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.2/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret", } func (ServiceAccount) SwaggerDoc() map[string]string { @@ -1477,8 +1479,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "List of ServiceAccounts. More info: http://releases.k8s.io/release-1.2/docs/design/service_accounts.md#service-accounts", } func (ServiceAccountList) SwaggerDoc() map[string]string { @@ -1487,7 +1489,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/HEAD/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", "items": "List of services", } @@ -1500,8 +1502,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 Port is used (an identity map). Defaults to the service port. 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", + "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.2/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.2/docs/user-guide/services.md#type--nodeport", } func (ServicePort) SwaggerDoc() map[string]string { @@ -1519,13 +1521,13 @@ 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/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 empty, all pods are selected, if not specified, endpoints must be manually specified. 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", + "ports": "The list of ports that are exposed by this service. More info: http://releases.k8s.io/release-1.2/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.2/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.2/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.2/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/HEAD/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/release-1.2/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.", } @@ -1553,7 +1555,7 @@ func (TCPSocketAction) 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/HEAD/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/release-1.2/docs/user-guide/identifiers.md#names", } func (Volume) SwaggerDoc() map[string]string { @@ -1564,7 +1566,7 @@ var map_VolumeMount = map[string]string{ "": "VolumeMount describes a mounting of a Volume within a container.", "name": "This must match the Name of a Volume.", "readOnly": "Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.", - "mountPath": "Path within the container at which the volume should be mounted.", + "mountPath": "Path within the container at which the volume should be mounted. Must not contain ':'.", } func (VolumeMount) SwaggerDoc() map[string]string { @@ -1573,19 +1575,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/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", + "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.2/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.2/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.2/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.2/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/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/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/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/rbd/README.md", + "secret": "Secret represents a secret that should populate this volume. More info: http://releases.k8s.io/release-1.2/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.2/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.2/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.2/examples/glusterfs/README.md", + "persistentVolumeClaim": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: http://releases.k8s.io/release-1.2/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.2/examples/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/HEAD/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/release-1.2/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/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/events_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/events_test.go deleted file mode 100644 index a2910d064..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/events_test.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package validation - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -func TestValidateEvent(t *testing.T) { - table := []struct { - *api.Event - valid bool - }{ - { - &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - Namespace: "foo", - }, - InvolvedObject: api.ObjectReference{ - Namespace: "bar", - }, - }, - false, - }, { - &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - Namespace: "aoeu-_-aoeu", - }, - InvolvedObject: api.ObjectReference{ - Namespace: "aoeu-_-aoeu", - }, - }, - false, - }, - } - - for _, item := range table { - if e, a := item.valid, len(ValidateEvent(item.Event)) == 0; e != a { - t.Errorf("%v: expected %v, got %v", item.Event.Name, e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/name_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/name_test.go deleted file mode 100644 index b8687cdcc..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/name_test.go +++ /dev/null @@ -1,149 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package validation - -import ( - "strings" - "testing" -) - -func TestValidatePathSegmentName(t *testing.T) { - testcases := map[string]struct { - Name string - Prefix bool - ExpectedOK bool - ExpectedMsg string - }{ - "empty": { - Name: "", - Prefix: false, - ExpectedOK: true, - ExpectedMsg: "", - }, - "empty,prefix": { - Name: "", - Prefix: true, - ExpectedOK: true, - ExpectedMsg: "", - }, - - "valid": { - Name: "foo.bar.baz", - Prefix: false, - ExpectedOK: true, - ExpectedMsg: "", - }, - "valid,prefix": { - Name: "foo.bar.baz", - Prefix: true, - ExpectedOK: true, - ExpectedMsg: "", - }, - - // Make sure mixed case, non DNS subdomain characters are tolerated - "valid complex": { - Name: "sha256:ABCDEF012345@ABCDEF012345", - Prefix: false, - ExpectedOK: true, - ExpectedMsg: "", - }, - // Make sure non-ascii characters are tolerated - "valid extended charset": { - Name: "Iñtërnâtiônàlizætiøn", - Prefix: false, - ExpectedOK: true, - ExpectedMsg: "", - }, - - "dot": { - Name: ".", - Prefix: false, - ExpectedOK: false, - ExpectedMsg: ".", - }, - "dot leading": { - Name: ".test", - Prefix: false, - ExpectedOK: true, - ExpectedMsg: "", - }, - "dot,prefix": { - Name: ".", - Prefix: true, - ExpectedOK: true, // allowed because a suffix could make it valid - ExpectedMsg: "", - }, - - "dot dot": { - Name: "..", - Prefix: false, - ExpectedOK: false, - ExpectedMsg: "..", - }, - "dot dot leading": { - Name: "..test", - Prefix: false, - ExpectedOK: true, - ExpectedMsg: "", - }, - "dot dot,prefix": { - Name: "..", - Prefix: true, - ExpectedOK: true, // allowed because a suffix could make it valid - ExpectedMsg: "", - }, - - "slash": { - Name: "foo/bar", - Prefix: false, - ExpectedOK: false, - ExpectedMsg: "/", - }, - "slash,prefix": { - Name: "foo/bar", - Prefix: true, - ExpectedOK: false, - ExpectedMsg: "/", - }, - - "percent": { - Name: "foo%bar", - Prefix: false, - ExpectedOK: false, - ExpectedMsg: "%", - }, - "percent,prefix": { - Name: "foo%bar", - Prefix: true, - ExpectedOK: false, - ExpectedMsg: "%", - }, - } - - for k, tc := range testcases { - ok, msg := ValidatePathSegmentName(tc.Name, tc.Prefix) - if ok != tc.ExpectedOK { - t.Errorf("%s: expected ok=%v, got %v", k, tc.ExpectedOK, ok) - } - if len(tc.ExpectedMsg) == 0 && len(msg) > 0 { - t.Errorf("%s: expected no message, got %v", k, msg) - } - if len(tc.ExpectedMsg) > 0 && !strings.Contains(msg, tc.ExpectedMsg) { - t.Errorf("%s: expected message containing %q, got %v", k, tc.ExpectedMsg, msg) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/schema.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/schema.go index 24c1e2619..6c55bc47f 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/schema.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/schema.go @@ -44,6 +44,14 @@ func NewInvalidTypeError(expected reflect.Kind, observed reflect.Kind, fieldName return &InvalidTypeError{expected, observed, fieldName} } +// TypeNotFoundError is returned when specified type +// can not found in schema +type TypeNotFoundError string + +func (tnfe TypeNotFoundError) Error() string { + return fmt.Sprintf("couldn't find type: %s", string(tnfe)) +} + // Schema is an interface that knows how to validate an API object serialized to a byte array. type Schema interface { ValidateBytes(data []byte) error @@ -164,7 +172,7 @@ func (s *SwaggerSchema) ValidateObject(obj interface{}, fieldName, typeName stri models := s.api.Models model, ok := models.At(typeName) if !ok { - return append(allErrs, fmt.Errorf("couldn't find type: %s", typeName)) + return append(allErrs, TypeNotFoundError(typeName)) } properties := model.Properties if len(properties.List) == 0 { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/schema_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/schema_test.go deleted file mode 100644 index be6fc83e7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/schema_test.go +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package validation - -import ( - "io/ioutil" - "math/rand" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/runtime" -) - -func readPod(filename string) (string, error) { - data, err := ioutil.ReadFile("testdata/" + testapi.Default.GroupVersion().Version + "/" + filename) - if err != nil { - return "", err - } - return string(data), nil -} - -func loadSchemaForTest() (Schema, error) { - // TODO this path is broken - pathToSwaggerSpec := "../../../api/swagger-spec/" + testapi.Default.GroupVersion().Version + ".json" - data, err := ioutil.ReadFile(pathToSwaggerSpec) - if err != nil { - return nil, err - } - return NewSwaggerSchemaFromBytes(data) -} - -func TestLoad(t *testing.T) { - _, err := loadSchemaForTest() - if err != nil { - t.Errorf("Failed to load: %v", err) - } -} - -func TestValidateOk(t *testing.T) { - schema, err := loadSchemaForTest() - if err != nil { - t.Errorf("Failed to load: %v", err) - } - tests := []struct { - obj runtime.Object - typeName string - }{ - {obj: &api.Pod{}}, - {obj: &api.Service{}}, - {obj: &api.ReplicationController{}}, - } - - seed := rand.Int63() - apiObjectFuzzer := apitesting.FuzzerFor(nil, testapi.Default.InternalGroupVersion(), rand.NewSource(seed)) - for i := 0; i < 5; i++ { - for _, test := range tests { - testObj := test.obj - apiObjectFuzzer.Fuzz(testObj) - data, err := runtime.Encode(testapi.Default.Codec(), testObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - err = schema.ValidateBytes(data) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - } - } -} - -func TestInvalid(t *testing.T) { - schema, err := loadSchemaForTest() - if err != nil { - t.Errorf("Failed to load: %v", err) - } - tests := []string{ - "invalidPod1.json", // command is a string, instead of []string. - "invalidPod2.json", // hostPort if of type string, instead of int. - "invalidPod3.json", // volumes is not an array of objects. - "invalidPod.yaml", // command is a string, instead of []string. - } - for _, test := range tests { - pod, err := readPod(test) - if err != nil { - t.Errorf("could not read file: %s", pod) - } - err = schema.ValidateBytes([]byte(pod)) - if err == nil { - t.Errorf("unexpected non-error, err: %s for pod: %s", err, pod) - } - } -} - -func TestValid(t *testing.T) { - schema, err := loadSchemaForTest() - if err != nil { - t.Errorf("Failed to load: %v", err) - } - tests := []string{ - "validPod.yaml", - } - for _, test := range tests { - pod, err := readPod(test) - if err != nil { - t.Errorf("could not read file: %s", test) - } - err = schema.ValidateBytes([]byte(pod)) - if err != nil { - t.Errorf("unexpected error %s, for pod %s", err, pod) - } - } -} - -func TestVersionRegex(t *testing.T) { - testCases := []struct { - typeName string - match bool - }{ - { - typeName: "v1.Binding", - match: true, - }, - { - typeName: "v1beta1.Binding", - match: true, - }, - { - typeName: "Binding", - match: false, - }, - } - for _, test := range testCases { - if versionRegexp.MatchString(test.typeName) && !test.match { - t.Errorf("unexpected error: expect %s not to match the regular expression", test.typeName) - } - if !versionRegexp.MatchString(test.typeName) && test.match { - t.Errorf("unexpected error: expect %s to match the regular expression", test.typeName) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod.yaml b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod.yaml deleted file mode 100644 index 059b2dc7b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -kind: Pod -metadata: - labels: - name: redis-master - name: name -spec: - containers: - - args: "this is a bad command" - image: redis - name: master diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod1.json b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod1.json deleted file mode 100644 index df256426c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod1.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "kind": "Pod", - "apiVersion": "v1", - "metadata": { - "name": "name", - "labels": { - "name": "redis-master" - } - }, - "spec": { - "containers": [ - { - "name": "master", - "image": "redis", - "args": "this is a bad command" - } - ] - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod2.json b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod2.json deleted file mode 100644 index 97f02ac13..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod2.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "kind": "Pod", - "apiVersion": "v1", - "metadata": { - "name": "apache-php", - "labels": { - "name": "apache-php" - } - }, - "spec": { - "volumes": [{ - "name": "shared-disk" - }], - "containers": [ - { - "name": "apache-php", - "image": "php:5.6.2-apache", - "ports": [ - { - "name": "apache", - "hostPort": "13380", - "containerPort": 80, - "protocol": "TCP" - } - ], - "volumeMounts": [ - { - "name": "shared-disk", - "mountPath": "/var/www/html" - } - ] - } - ] - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod3.json b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod3.json deleted file mode 100644 index 78bc87e8c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/invalidPod3.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "kind": "Pod", - "apiVersion": "v1", - "metadata": { - "name": "apache-php", - "labels": { - "name": "apache-php" - } - }, - "spec": { - "volumes": [ - "name": "shared-disk" - ], - "containers": [ - { - "name": "apache-php", - "image": "php:5.6.2-apache", - "ports": [ - { - "name": "apache", - "hostPort": 13380, - "containerPort": 80, - "protocol": "TCP" - } - ], - "volumeMounts": [ - { - "name": "shared-disk", - "mountPath": "/var/www/html" - } - ] - } - ] - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/validPod.yaml b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/validPod.yaml deleted file mode 100644 index b8bdbdf69..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/testdata/v1/validPod.yaml +++ /dev/null @@ -1,16 +0,0 @@ -apiVersion: v1 -kind: Pod -metadata: - labels: - name: redis-master - name: name -spec: - containers: - - args: - - this - - is - - an - - ok - - command - image: redis - name: master diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/validation.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/validation.go index 4546a2f5f..3d4d906c5 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/validation.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/validation.go @@ -27,16 +27,18 @@ import ( "regexp" "strings" + "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/endpoints" + utilpod "k8s.io/kubernetes/pkg/api/pod" "k8s.io/kubernetes/pkg/api/resource" + apiservice "k8s.io/kubernetes/pkg/api/service" "k8s.io/kubernetes/pkg/capabilities" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/validation" "k8s.io/kubernetes/pkg/util/validation/field" - - "github.com/golang/glog" ) // TODO: delete this global variable when we enable the validation of common @@ -44,6 +46,7 @@ import ( 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` @@ -111,10 +114,34 @@ func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) fie if totalSize > (int64)(totalAnnotationSizeLimitB) { allErrs = append(allErrs, field.TooLong(fldPath, "", totalAnnotationSizeLimitB)) } + return allErrs +} +func ValidatePodSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} if annotations[api.AffinityAnnotationKey] != "" { allErrs = append(allErrs, ValidateAffinityInPodAnnotations(annotations, fldPath)...) } + + if hostname, exists := annotations[utilpod.PodHostnameAnnotation]; exists && !validation.IsDNS1123Label(hostname) { + allErrs = append(allErrs, field.Invalid(fldPath, utilpod.PodHostnameAnnotation, DNS1123LabelErrorMsg)) + } + + if subdomain, exists := annotations[utilpod.PodSubdomainAnnotation]; exists && !validation.IsDNS1123Label(subdomain) { + allErrs = append(allErrs, field.Invalid(fldPath, utilpod.PodSubdomainAnnotation, DNS1123LabelErrorMsg)) + } + + return allErrs +} + +func ValidateEndpointsSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + hostnamesMap, exists := annotations[endpoints.PodHostnamesAnnotation] + if exists && !isValidHostnamesMap(hostnamesMap) { + allErrs = append(allErrs, field.Invalid(fldPath, endpoints.PodHostnamesAnnotation, + `must be a valid json representation of map[string(IP)][HostRecord] e.g. "{"10.245.1.6":{"HostName":"my-webserver"}}"`)) + } + return allErrs } @@ -1090,6 +1117,8 @@ func validateVolumeMounts(mounts []api.VolumeMount, volumes sets.String, fldPath } if len(mnt.MountPath) == 0 { allErrs = append(allErrs, field.Required(idxPath.Child("mountPath"), "")) + } else if strings.Contains(mnt.MountPath, ":") { + allErrs = append(allErrs, field.Invalid(idxPath.Child("mountPath"), mnt.MountPath, "must not contain ':'")) } } return allErrs @@ -1352,7 +1381,9 @@ func validateImagePullSecrets(imagePullSecrets []api.LocalObjectReference, fldPa // ValidatePod tests if required fields in the pod are set. func ValidatePod(pod *api.Pod) field.ErrorList { - allErrs := ValidateObjectMeta(&pod.ObjectMeta, true, ValidatePodName, field.NewPath("metadata")) + fldPath := field.NewPath("metadata") + allErrs := ValidateObjectMeta(&pod.ObjectMeta, true, ValidatePodName, fldPath) + allErrs = append(allErrs, ValidatePodSpecificAnnotations(pod.ObjectMeta.Annotations, fldPath.Child("annotations"))...) allErrs = append(allErrs, ValidatePodSpec(&pod.Spec, field.NewPath("spec"))...) return allErrs } @@ -1516,8 +1547,9 @@ func ValidatePodSecurityContext(securityContext *api.PodSecurityContext, spec *a // 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 { - allErrs := ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta, field.NewPath("metadata")) - + fldPath := field.NewPath("metadata") + 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 @@ -1735,6 +1767,12 @@ func ValidateService(service *api.Service) field.ErrorList { nodePorts[key] = true } + _, err := apiservice.GetLoadBalancerSourceRanges(service.Annotations) + if err != nil { + v := service.Annotations[apiservice.AnnotationLoadBalancerSourceRangesKey] + allErrs = append(allErrs, field.Invalid(field.NewPath("metadata", "annotations").Key(apiservice.AnnotationLoadBalancerSourceRangesKey), v, "must be a comma separated list of CIDRs e.g. 192.168.0.0/16,10.0.0.0/8")) + } + return allErrs } @@ -1770,11 +1808,14 @@ func validateServicePort(sp *api.ServicePort, requireName, isHeadlessService boo allErrs = append(allErrs, field.Invalid(fldPath.Child("targetPort"), sp.TargetPort, PortNameErrorMsg)) } - if isHeadlessService { - if sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int && sp.Port != sp.TargetPort.IntValue()) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), sp.Port, "must be equal to targetPort when clusterIP = None")) - } - } + // 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. + // + // if isHeadlessService { + // if sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int && sp.Port != sp.TargetPort.IntValue()) { + // allErrs = append(allErrs, field.Invalid(fldPath.Child("targetPort"), sp.TargetPort, "must be equal to the value of 'port' when clusterIP = None")) + // } + // } return allErrs } @@ -1817,6 +1858,7 @@ func ValidateReplicationControllerStatusUpdate(controller, oldController *api.Re allErrs := ValidateObjectMetaUpdate(&controller.ObjectMeta, &oldController.ObjectMeta, field.NewPath("metadata")) statusPath := field.NewPath("status") allErrs = append(allErrs, ValidateNonnegativeField(int64(controller.Status.Replicas), statusPath.Child("replicas"))...) + allErrs = append(allErrs, ValidateNonnegativeField(int64(controller.Status.FullyLabeledReplicas), statusPath.Child("fullyLabeledReplicas"))...) allErrs = append(allErrs, ValidateNonnegativeField(int64(controller.Status.ObservedGeneration), statusPath.Child("observedGeneration"))...) return allErrs } @@ -1871,6 +1913,7 @@ func ValidatePodTemplateSpec(spec *api.PodTemplateSpec, fldPath *field.Path) fie allErrs := field.ErrorList{} allErrs = append(allErrs, ValidateLabels(spec.Labels, fldPath.Child("labels"))...) allErrs = append(allErrs, ValidateAnnotations(spec.Annotations, fldPath.Child("annotations"))...) + allErrs = append(allErrs, ValidatePodSpecificAnnotations(spec.Annotations, fldPath.Child("annotations"))...) allErrs = append(allErrs, ValidatePodSpec(&spec.Spec, fldPath.Child("spec"))...) return allErrs } @@ -1968,6 +2011,57 @@ func validateResourceName(value string, fldPath *field.Path) field.ErrorList { return field.ErrorList{} } +// Validate container resource name +// Refer to docs/design/resources.md for more details. +func validateContainerResourceName(value string, fldPath *field.Path) field.ErrorList { + allErrs := validateResourceName(value, fldPath) + if len(strings.Split(value, "/")) == 1 { + if !api.IsStandardContainerResourceName(value) { + return append(allErrs, field.Invalid(fldPath, value, "must be a standard resource for containers")) + } + } + return field.ErrorList{} +} + +// 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 { + allErrs := validateResourceName(value, fldPath) + if len(strings.Split(value, "/")) == 1 { + if !api.IsStandardQuotaResourceName(value) { + return append(allErrs, field.Invalid(fldPath, value, isInvalidQuotaResource)) + } + } + return field.ErrorList{} +} + +// Validate limit range types +func validateLimitRangeTypeName(value string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + if !validation.IsQualifiedName(value) { + return append(allErrs, field.Invalid(fldPath, value, qualifiedNameErrorMsg)) + } + + if len(strings.Split(value, "/")) == 1 { + if !api.IsStandardLimitRangeType(value) { + return append(allErrs, field.Invalid(fldPath, value, "must be a standard limit type or fully qualified")) + } + } + + return allErrs +} + +// Validate limit range resource name +// limit types (other than Pod/Container) could contain storage not just cpu or memory +func validateLimitRangeResourceName(limitType api.LimitType, value string, fldPath *field.Path) field.ErrorList { + switch limitType { + case api.LimitTypePod, api.LimitTypeContainer: + return validateContainerResourceName(value, fldPath) + default: + return validateResourceName(value, fldPath) + } +} + // ValidateLimitRange tests if required fields in the LimitRange are set. func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { allErrs := ValidateObjectMeta(&limitRange.ObjectMeta, true, ValidateLimitRangeName, field.NewPath("metadata")) @@ -1978,6 +2072,8 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { for i := range limitRange.Spec.Limits { idxPath := fldPath.Index(i) limit := &limitRange.Spec.Limits[i] + allErrs = append(allErrs, validateLimitRangeTypeName(string(limit.Type), idxPath.Child("type"))...) + _, found := limitTypeSet[limit.Type] if found { allErrs = append(allErrs, field.Duplicate(idxPath.Child("type"), limit.Type)) @@ -1992,12 +2088,12 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { maxLimitRequestRatios := map[string]resource.Quantity{} for k, q := range limit.Max { - allErrs = append(allErrs, validateResourceName(string(k), idxPath.Child("max").Key(string(k)))...) + allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("max").Key(string(k)))...) keys.Insert(string(k)) max[string(k)] = q } for k, q := range limit.Min { - allErrs = append(allErrs, validateResourceName(string(k), idxPath.Child("min").Key(string(k)))...) + allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("min").Key(string(k)))...) keys.Insert(string(k)) min[string(k)] = q } @@ -2011,19 +2107,19 @@ func ValidateLimitRange(limitRange *api.LimitRange) field.ErrorList { } } else { for k, q := range limit.Default { - allErrs = append(allErrs, validateResourceName(string(k), idxPath.Child("default").Key(string(k)))...) + allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("default").Key(string(k)))...) keys.Insert(string(k)) defaults[string(k)] = q } for k, q := range limit.DefaultRequest { - allErrs = append(allErrs, validateResourceName(string(k), idxPath.Child("defaultRequest").Key(string(k)))...) + allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("defaultRequest").Key(string(k)))...) keys.Insert(string(k)) defaultRequests[string(k)] = q } } for k, q := range limit.MaxLimitRequestRatio { - allErrs = append(allErrs, validateResourceName(string(k), idxPath.Child("maxLimitRequestRatio").Key(string(k)))...) + allErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child("maxLimitRequestRatio").Key(string(k)))...) keys.Insert(string(k)) maxLimitRequestRatios[string(k)] = q } @@ -2246,7 +2342,7 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements, fldPat for resourceName, quantity := range requirements.Limits { fldPath := limPath.Key(string(resourceName)) // Validate resource name. - allErrs = append(allErrs, validateResourceName(string(resourceName), fldPath)...) + allErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...) if api.IsStandardResourceName(string(resourceName)) { allErrs = append(allErrs, validateBasicResource(quantity, fldPath.Key(string(resourceName)))...) } @@ -2262,7 +2358,7 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements, fldPat for resourceName, quantity := range requirements.Requests { fldPath := reqPath.Key(string(resourceName)) // Validate resource name. - allErrs = append(allErrs, validateResourceName(string(resourceName), fldPath)...) + allErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...) if api.IsStandardResourceName(string(resourceName)) { allErrs = append(allErrs, validateBasicResource(quantity, fldPath.Key(string(resourceName)))...) } @@ -2270,6 +2366,41 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements, fldPat return allErrs } +// validateResourceQuotaScopes ensures that each enumerated hard resource constraint is valid for set of scopes +func validateResourceQuotaScopes(resourceQuota *api.ResourceQuota) field.ErrorList { + allErrs := field.ErrorList{} + if len(resourceQuota.Spec.Scopes) == 0 { + return allErrs + } + hardLimits := sets.NewString() + for k := range resourceQuota.Spec.Hard { + hardLimits.Insert(string(k)) + } + fldPath := field.NewPath("spec", "scopes") + scopeSet := sets.NewString() + for _, scope := range resourceQuota.Spec.Scopes { + if !api.IsStandardResourceQuotaScope(string(scope)) { + allErrs = append(allErrs, field.Invalid(fldPath, resourceQuota.Spec.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")) + } + } + scopeSet.Insert(string(scope)) + } + invalidScopePairs := []sets.String{ + sets.NewString(string(api.ResourceQuotaScopeBestEffort), string(api.ResourceQuotaScopeNotBestEffort)), + sets.NewString(string(api.ResourceQuotaScopeTerminating), string(api.ResourceQuotaScopeNotTerminating)), + } + for _, invalidScopePair := range invalidScopePairs { + if scopeSet.HasAll(invalidScopePair.List()...) { + allErrs = append(allErrs, field.Invalid(fldPath, resourceQuota.Spec.Scopes, "conflicting scopes")) + } + } + return allErrs +} + // ValidateResourceQuota tests if required fields in the ResourceQuota are set. func ValidateResourceQuota(resourceQuota *api.ResourceQuota) field.ErrorList { allErrs := ValidateObjectMeta(&resourceQuota.ObjectMeta, true, ValidateResourceQuotaName, field.NewPath("metadata")) @@ -2277,21 +2408,24 @@ func ValidateResourceQuota(resourceQuota *api.ResourceQuota) field.ErrorList { fldPath := field.NewPath("spec", "hard") for k, v := range resourceQuota.Spec.Hard { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceName(string(k), 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 { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceName(string(k), 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 { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceName(string(k), resPath)...) + allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) } + return allErrs } @@ -2314,9 +2448,25 @@ func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.Resourc fldPath := field.NewPath("spec", "hard") for k, v := range newResourceQuota.Spec.Hard { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceName(string(k), resPath)...) + allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) } + + // ensure scopes cannot change, and that resources are still valid for scope + fldPath = field.NewPath("spec", "scopes") + oldScopes := sets.NewString() + newScopes := sets.NewString() + for _, scope := range newResourceQuota.Spec.Scopes { + newScopes.Insert(string(scope)) + } + for _, scope := range oldResourceQuota.Spec.Scopes { + oldScopes.Insert(string(scope)) + } + 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 } @@ -2331,13 +2481,13 @@ 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, validateResourceName(string(k), 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, validateResourceName(string(k), resPath)...) + allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) } newResourceQuota.Spec = oldResourceQuota.Spec @@ -2412,6 +2562,7 @@ func ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *api.Namespace) // ValidateEndpoints tests if required fields are set. func ValidateEndpoints(endpoints *api.Endpoints) field.ErrorList { allErrs := ValidateObjectMeta(&endpoints.ObjectMeta, true, ValidateEndpointsName, field.NewPath("metadata")) + allErrs = append(allErrs, ValidateEndpointsSpecificAnnotations(endpoints.Annotations, field.NewPath("annotations"))...) allErrs = append(allErrs, validateEndpointSubsets(endpoints.Subsets, field.NewPath("subsets"))...) return allErrs } @@ -2495,6 +2646,7 @@ func validateEndpointPort(port *api.EndpointPort, requireName bool, fldPath *fie func ValidateEndpointsUpdate(newEndpoints, oldEndpoints *api.Endpoints) field.ErrorList { allErrs := ValidateObjectMetaUpdate(&newEndpoints.ObjectMeta, &oldEndpoints.ObjectMeta, field.NewPath("metadata")) allErrs = append(allErrs, validateEndpointSubsets(newEndpoints.Subsets, field.NewPath("subsets"))...) + allErrs = append(allErrs, ValidateEndpointsSpecificAnnotations(newEndpoints.Annotations, field.NewPath("annotations"))...) return allErrs } @@ -2560,3 +2712,24 @@ func ValidateLoadBalancerStatus(status *api.LoadBalancerStatus, fldPath *field.P } return allErrs } + +func isValidHostnamesMap(serializedPodHostNames string) bool { + if len(serializedPodHostNames) == 0 { + return false + } + podHostNames := map[string]endpoints.HostRecord{} + err := json.Unmarshal([]byte(serializedPodHostNames), &podHostNames) + if err != nil { + return false + } + + for ip, hostRecord := range podHostNames { + if !validation.IsDNS1123Label(hostRecord.HostName) { + return false + } + if net.ParseIP(ip) == nil { + return false + } + } + return true +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/validation_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/validation_test.go deleted file mode 100644 index 04c27126a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/validation/validation_test.go +++ /dev/null @@ -1,5146 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package validation - -import ( - "math/rand" - "reflect" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/capabilities" - "k8s.io/kubernetes/pkg/util/intstr" - "k8s.io/kubernetes/pkg/util/sets" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -func expectPrefix(t *testing.T, prefix string, errs field.ErrorList) { - for i := range errs { - if f, p := errs[i].Field, prefix; !strings.HasPrefix(f, p) { - t.Errorf("expected prefix '%s' for field '%s' (%v)", p, f, errs[i]) - } - } -} - -// Ensure custom name functions are allowed -func TestValidateObjectMetaCustomName(t *testing.T) { - errs := ValidateObjectMeta( - &api.ObjectMeta{Name: "test", GenerateName: "foo"}, - false, - func(s string, prefix bool) (bool, string) { - if s == "test" { - return true, "" - } - return false, "name-gen" - }, - field.NewPath("field")) - if len(errs) != 1 { - t.Fatalf("unexpected errors: %v", errs) - } - if !strings.Contains(errs[0].Error(), "name-gen") { - t.Errorf("unexpected error message: %v", errs) - } -} - -// Ensure namespace names follow dns label format -func TestValidateObjectMetaNamespaces(t *testing.T) { - errs := ValidateObjectMeta( - &api.ObjectMeta{Name: "test", Namespace: "foo.bar"}, - true, - func(s string, prefix bool) (bool, string) { - return true, "" - }, - field.NewPath("field")) - if len(errs) != 1 { - t.Fatalf("unexpected errors: %v", errs) - } - if !strings.Contains(errs[0].Error(), `Invalid value: "foo.bar"`) { - t.Errorf("unexpected error message: %v", errs) - } - maxLength := 63 - letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") - b := make([]rune, maxLength+1) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - errs = ValidateObjectMeta( - &api.ObjectMeta{Name: "test", Namespace: string(b)}, - true, - func(s string, prefix bool) (bool, string) { - return true, "" - }, - field.NewPath("field")) - if len(errs) != 1 { - t.Fatalf("unexpected errors: %v", errs) - } - if !strings.Contains(errs[0].Error(), "Invalid value") { - t.Errorf("unexpected error message: %v", errs) - } -} - -func TestValidateObjectMetaUpdateIgnoresCreationTimestamp(t *testing.T) { - if errs := ValidateObjectMetaUpdate( - &api.ObjectMeta{Name: "test", ResourceVersion: "1"}, - &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(10, 0))}, - field.NewPath("field"), - ); len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } - if errs := ValidateObjectMetaUpdate( - &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(10, 0))}, - &api.ObjectMeta{Name: "test", ResourceVersion: "1"}, - field.NewPath("field"), - ); len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } - if errs := ValidateObjectMetaUpdate( - &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(10, 0))}, - &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(11, 0))}, - field.NewPath("field"), - ); len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } -} - -// Ensure trailing slash is allowed in generate name -func TestValidateObjectMetaTrimsTrailingSlash(t *testing.T) { - errs := ValidateObjectMeta( - &api.ObjectMeta{Name: "test", GenerateName: "foo-"}, - false, - NameIsDNSSubdomain, - field.NewPath("field")) - if len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } -} - -func TestValidateLabels(t *testing.T) { - successCases := []map[string]string{ - {"simple": "bar"}, - {"now-with-dashes": "bar"}, - {"1-starts-with-num": "bar"}, - {"1234": "bar"}, - {"simple/simple": "bar"}, - {"now-with-dashes/simple": "bar"}, - {"now-with-dashes/now-with-dashes": "bar"}, - {"now.with.dots/simple": "bar"}, - {"now-with.dashes-and.dots/simple": "bar"}, - {"1-num.2-num/3-num": "bar"}, - {"1234/5678": "bar"}, - {"1.2.3.4/5678": "bar"}, - {"UpperCaseAreOK123": "bar"}, - {"goodvalue": "123_-.BaR"}, - } - for i := range successCases { - errs := ValidateLabels(successCases[i], field.NewPath("field")) - if len(errs) != 0 { - t.Errorf("case[%d] expected success, got %#v", i, errs) - } - } - - labelNameErrorCases := []map[string]string{ - {"nospecialchars^=@": "bar"}, - {"cantendwithadash-": "bar"}, - {"only/one/slash": "bar"}, - {strings.Repeat("a", 254): "bar"}, - } - for i := range labelNameErrorCases { - errs := ValidateLabels(labelNameErrorCases[i], field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d] expected failure", i) - } else { - detail := errs[0].Detail - if detail != qualifiedNameErrorMsg { - t.Errorf("error detail %s should be equal %s", detail, qualifiedNameErrorMsg) - } - } - } - - labelValueErrorCases := []map[string]string{ - {"toolongvalue": strings.Repeat("a", 64)}, - {"backslashesinvalue": "some\\bad\\value"}, - {"nocommasallowed": "bad,value"}, - {"strangecharsinvalue": "?#$notsogood"}, - } - for i := range labelValueErrorCases { - errs := ValidateLabels(labelValueErrorCases[i], field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d] expected failure", i) - } else { - detail := errs[0].Detail - if detail != labelValueErrorMsg { - t.Errorf("error detail %s should be equal %s", detail, labelValueErrorMsg) - } - } - } -} - -func TestValidateAnnotations(t *testing.T) { - successCases := []map[string]string{ - {"simple": "bar"}, - {"now-with-dashes": "bar"}, - {"1-starts-with-num": "bar"}, - {"1234": "bar"}, - {"simple/simple": "bar"}, - {"now-with-dashes/simple": "bar"}, - {"now-with-dashes/now-with-dashes": "bar"}, - {"now.with.dots/simple": "bar"}, - {"now-with.dashes-and.dots/simple": "bar"}, - {"1-num.2-num/3-num": "bar"}, - {"1234/5678": "bar"}, - {"1.2.3.4/5678": "bar"}, - {"UpperCase123": "bar"}, - {"a": strings.Repeat("b", totalAnnotationSizeLimitB-1)}, - { - "a": strings.Repeat("b", totalAnnotationSizeLimitB/2-1), - "c": strings.Repeat("d", totalAnnotationSizeLimitB/2-1), - }, - } - for i := range successCases { - errs := ValidateAnnotations(successCases[i], field.NewPath("field")) - if len(errs) != 0 { - t.Errorf("case[%d] expected success, got %#v", i, errs) - } - } - - nameErrorCases := []map[string]string{ - {"nospecialchars^=@": "bar"}, - {"cantendwithadash-": "bar"}, - {"only/one/slash": "bar"}, - {strings.Repeat("a", 254): "bar"}, - } - for i := range nameErrorCases { - errs := ValidateAnnotations(nameErrorCases[i], field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d] expected failure", i) - } - detail := errs[0].Detail - if detail != qualifiedNameErrorMsg { - t.Errorf("error detail %s should be equal %s", detail, qualifiedNameErrorMsg) - } - } - totalSizeErrorCases := []map[string]string{ - {"a": strings.Repeat("b", totalAnnotationSizeLimitB)}, - { - "a": strings.Repeat("b", totalAnnotationSizeLimitB/2), - "c": strings.Repeat("d", totalAnnotationSizeLimitB/2), - }, - } - for i := range totalSizeErrorCases { - errs := ValidateAnnotations(totalSizeErrorCases[i], field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d] expected failure", i) - } - } -} - -func testVolume(name string, namespace string, spec api.PersistentVolumeSpec) *api.PersistentVolume { - objMeta := api.ObjectMeta{Name: name} - if namespace != "" { - objMeta.Namespace = namespace - } - - return &api.PersistentVolume{ - ObjectMeta: objMeta, - Spec: spec, - } -} - -func TestValidatePersistentVolumes(t *testing.T) { - scenarios := map[string]struct { - isExpectedFailure bool - volume *api.PersistentVolume - }{ - "good-volume": { - isExpectedFailure: false, - volume: testVolume("foo", "", api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }), - }, - "invalid-accessmode": { - isExpectedFailure: true, - volume: testVolume("foo", "", api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []api.PersistentVolumeAccessMode{"fakemode"}, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }), - }, - "unexpected-namespace": { - isExpectedFailure: true, - volume: testVolume("foo", "unexpected-namespace", api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }), - }, - "bad-name": { - isExpectedFailure: true, - volume: testVolume("123*Bad(Name", "unexpected-namespace", api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }), - }, - "missing-name": { - isExpectedFailure: true, - volume: testVolume("", "", api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, - }), - }, - "missing-capacity": { - isExpectedFailure: true, - volume: testVolume("foo", "", api.PersistentVolumeSpec{}), - }, - "missing-accessmodes": { - isExpectedFailure: true, - volume: testVolume("goodname", "missing-accessmodes", api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }), - }, - "too-many-sources": { - isExpectedFailure: true, - volume: testVolume("", "", api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("5G"), - }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "foo", FSType: "ext4"}, - }, - }), - }, - } - - for name, scenario := range scenarios { - errs := ValidatePersistentVolume(scenario.volume) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } - -} - -func testVolumeClaim(name string, namespace string, spec api.PersistentVolumeClaimSpec) *api.PersistentVolumeClaim { - return &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespace}, - Spec: spec, - } -} - -func TestValidatePersistentVolumeClaim(t *testing.T) { - scenarios := map[string]struct { - isExpectedFailure bool - claim *api.PersistentVolumeClaim - }{ - "good-claim": { - isExpectedFailure: false, - claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "invalid-accessmode": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{"fakemode"}, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "missing-namespace": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "no-access-modes": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "no-resource-requests": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - }, - }), - }, - "invalid-resource-requests": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - }), - }, - } - - for name, scenario := range scenarios { - errs := ValidatePersistentVolumeClaim(scenario.claim) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func TestValidatePersistentVolumeClaimUpdate(t *testing.T) { - validClaim := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - validUpdateClaim := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - invalidUpdateClaimResources := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("20G"), - }, - }, - VolumeName: "volume", - }) - invalidUpdateClaimAccessModes := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - scenarios := map[string]struct { - isExpectedFailure bool - oldClaim *api.PersistentVolumeClaim - newClaim *api.PersistentVolumeClaim - }{ - "valid-update": { - isExpectedFailure: false, - oldClaim: validClaim, - newClaim: validUpdateClaim, - }, - "invalid-update-change-resources-on-bound-claim": { - isExpectedFailure: true, - oldClaim: validUpdateClaim, - newClaim: invalidUpdateClaimResources, - }, - "invalid-update-change-access-modes-on-bound-claim": { - isExpectedFailure: true, - oldClaim: validUpdateClaim, - newClaim: invalidUpdateClaimAccessModes, - }, - } - - for name, scenario := range scenarios { - // ensure we have a resource version specified for updates - scenario.oldClaim.ResourceVersion = "1" - scenario.newClaim.ResourceVersion = "1" - errs := ValidatePersistentVolumeClaimUpdate(scenario.newClaim, scenario.oldClaim) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func TestValidateVolumes(t *testing.T) { - lun := 1 - successCase := []api.Volume{ - {Name: "abc", VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/mnt/path1"}}}, - {Name: "123", VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/mnt/path2"}}}, - {Name: "abc-123", VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/mnt/path3"}}}, - {Name: "empty", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, - {Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}, - {Name: "awsebs", VolumeSource: api.VolumeSource{AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{VolumeID: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}, - {Name: "gitrepo", VolumeSource: api.VolumeSource{GitRepo: &api.GitRepoVolumeSource{Repository: "my-repo", Revision: "hashstring", Directory: "target"}}}, - {Name: "gitrepodot", VolumeSource: api.VolumeSource{GitRepo: &api.GitRepoVolumeSource{Repository: "my-repo", Directory: "."}}}, - {Name: "iscsidisk", VolumeSource: api.VolumeSource{ISCSI: &api.ISCSIVolumeSource{TargetPortal: "127.0.0.1", IQN: "iqn.2015-02.example.com:test", Lun: 1, FSType: "ext4", ReadOnly: false}}}, - {Name: "secret", VolumeSource: api.VolumeSource{Secret: &api.SecretVolumeSource{SecretName: "my-secret"}}}, - {Name: "glusterfs", VolumeSource: api.VolumeSource{Glusterfs: &api.GlusterfsVolumeSource{EndpointsName: "host1", Path: "path", ReadOnly: false}}}, - {Name: "flocker", VolumeSource: api.VolumeSource{Flocker: &api.FlockerVolumeSource{DatasetName: "datasetName"}}}, - {Name: "rbd", VolumeSource: api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{"foo"}, RBDImage: "bar", FSType: "ext4"}}}, - {Name: "cinder", VolumeSource: api.VolumeSource{Cinder: &api.CinderVolumeSource{"29ea5088-4f60-4757-962e-dba678767887", "ext4", false}}}, - {Name: "cephfs", VolumeSource: api.VolumeSource{CephFS: &api.CephFSVolumeSource{Monitors: []string{"foo"}}}}, - {Name: "downwardapi", VolumeSource: api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{ - {Path: "labels", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}, - {Path: "annotations", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.annotations"}}, - {Path: "namespace", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.namespace"}}, - {Path: "name", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.name"}}, - {Path: "path/withslash/andslash", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}, - {Path: "path/./withdot", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}, - {Path: "path/with..dot", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}, - {Path: "second-level-dirent-can-have/..dot", FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}, - }}}}, - {Name: "fc", VolumeSource: api.VolumeSource{FC: &api.FCVolumeSource{[]string{"some_wwn"}, &lun, "ext4", false}}}, - {Name: "flexvolume", VolumeSource: api.VolumeSource{FlexVolume: &api.FlexVolumeSource{Driver: "kubernetes.io/blue", FSType: "ext4"}}}, - {Name: "azure", VolumeSource: api.VolumeSource{AzureFile: &api.AzureFileVolumeSource{"key", "share", false}}}, - } - names, errs := validateVolumes(successCase, field.NewPath("field")) - if len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - if len(names) != len(successCase) || !names.HasAll("abc", "123", "abc-123", "empty", "gcepd", "gitrepo", "secret", "iscsidisk", "cinder", "cephfs", "flexvolume", "fc") { - t.Errorf("wrong names result: %v", names) - } - emptyVS := api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}} - emptyPortal := api.VolumeSource{ISCSI: &api.ISCSIVolumeSource{TargetPortal: "", IQN: "iqn.2015-02.example.com:test", Lun: 1, FSType: "ext4", ReadOnly: false}} - emptyIQN := api.VolumeSource{ISCSI: &api.ISCSIVolumeSource{TargetPortal: "127.0.0.1", IQN: "", Lun: 1, FSType: "ext4", ReadOnly: false}} - emptyHosts := api.VolumeSource{Glusterfs: &api.GlusterfsVolumeSource{EndpointsName: "", Path: "path", ReadOnly: false}} - emptyPath := api.VolumeSource{Glusterfs: &api.GlusterfsVolumeSource{EndpointsName: "host", Path: "", ReadOnly: false}} - emptyName := api.VolumeSource{Flocker: &api.FlockerVolumeSource{DatasetName: ""}} - emptyMon := api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{}, RBDImage: "bar", FSType: "ext4"}} - emptyImage := api.VolumeSource{RBD: &api.RBDVolumeSource{CephMonitors: []string{"foo"}, RBDImage: "", FSType: "ext4"}} - emptyCephFSMon := api.VolumeSource{CephFS: &api.CephFSVolumeSource{Monitors: []string{}}} - startsWithDots := api.VolumeSource{GitRepo: &api.GitRepoVolumeSource{Repository: "foo", Directory: "..dots/bar"}} - containsDots := api.VolumeSource{GitRepo: &api.GitRepoVolumeSource{Repository: "foo", Directory: "dots/../bar"}} - absPath := api.VolumeSource{GitRepo: &api.GitRepoVolumeSource{Repository: "foo", Directory: "/abstarget"}} - emptyPathName := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "", - FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}}, - }} - absolutePathName := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "/absolutepath", - FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}}, - }} - dotDotInPath := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "../../passwd", - FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}}, - }} - dotDotPathName := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "..badFileName", - FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}}, - }} - dotDotFirstLevelDirent := api.VolumeSource{DownwardAPI: &api.DownwardAPIVolumeSource{Items: []api.DownwardAPIVolumeFile{{Path: "..badDirName/goodFileName", - FieldRef: api.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels"}}}, - }} - zeroWWN := api.VolumeSource{FC: &api.FCVolumeSource{[]string{}, &lun, "ext4", false}} - emptyLun := api.VolumeSource{FC: &api.FCVolumeSource{[]string{"wwn"}, nil, "ext4", false}} - slashInName := api.VolumeSource{Flocker: &api.FlockerVolumeSource{DatasetName: "foo/bar"}} - emptyAzureSecret := api.VolumeSource{AzureFile: &api.AzureFileVolumeSource{"", "share", false}} - emptyAzureShare := api.VolumeSource{AzureFile: &api.AzureFileVolumeSource{"name", "", false}} - errorCases := map[string]struct { - V []api.Volume - T field.ErrorType - F string - D string - }{ - "zero-length name": { - []api.Volume{{Name: "", VolumeSource: emptyVS}}, - field.ErrorTypeRequired, - "name", "", - }, - "name > 63 characters": { - []api.Volume{{Name: strings.Repeat("a", 64), VolumeSource: emptyVS}}, - field.ErrorTypeInvalid, - "name", "must be a DNS label", - }, - "name not a DNS label": { - []api.Volume{{Name: "a.b.c", VolumeSource: emptyVS}}, - field.ErrorTypeInvalid, - "name", "must be a DNS label", - }, - "name not unique": { - []api.Volume{{Name: "abc", VolumeSource: emptyVS}, {Name: "abc", VolumeSource: emptyVS}}, - field.ErrorTypeDuplicate, - "[1].name", "", - }, - "empty portal": { - []api.Volume{{Name: "badportal", VolumeSource: emptyPortal}}, - field.ErrorTypeRequired, - "iscsi.targetPortal", "", - }, - "empty iqn": { - []api.Volume{{Name: "badiqn", VolumeSource: emptyIQN}}, - field.ErrorTypeRequired, - "iscsi.iqn", "", - }, - "empty hosts": { - []api.Volume{{Name: "badhost", VolumeSource: emptyHosts}}, - field.ErrorTypeRequired, - "glusterfs.endpoints", "", - }, - "empty path": { - []api.Volume{{Name: "badpath", VolumeSource: emptyPath}}, - field.ErrorTypeRequired, - "glusterfs.path", "", - }, - "empty datasetName": { - []api.Volume{{Name: "badname", VolumeSource: emptyName}}, - field.ErrorTypeRequired, - "flocker.datasetName", "", - }, - "empty mon": { - []api.Volume{{Name: "badmon", VolumeSource: emptyMon}}, - field.ErrorTypeRequired, - "rbd.monitors", "", - }, - "empty image": { - []api.Volume{{Name: "badimage", VolumeSource: emptyImage}}, - field.ErrorTypeRequired, - "rbd.image", "", - }, - "empty cephfs mon": { - []api.Volume{{Name: "badmon", VolumeSource: emptyCephFSMon}}, - field.ErrorTypeRequired, - "cephfs.monitors", "", - }, - "empty metatada path": { - []api.Volume{{Name: "emptyname", VolumeSource: emptyPathName}}, - field.ErrorTypeRequired, - "downwardAPI.path", "", - }, - "absolute path": { - []api.Volume{{Name: "absolutepath", VolumeSource: absolutePathName}}, - field.ErrorTypeInvalid, - "downwardAPI.path", "", - }, - "dot dot path": { - []api.Volume{{Name: "dotdotpath", VolumeSource: dotDotInPath}}, - field.ErrorTypeInvalid, - "downwardAPI.path", `must not contain '..'`, - }, - "dot dot file name": { - []api.Volume{{Name: "dotdotfilename", VolumeSource: dotDotPathName}}, - field.ErrorTypeInvalid, - "downwardAPI.path", `must not start with '..'`, - }, - "dot dot first level dirent": { - []api.Volume{{Name: "dotdotdirfilename", VolumeSource: dotDotFirstLevelDirent}}, - field.ErrorTypeInvalid, - "downwardAPI.path", `must not start with '..'`, - }, - "empty wwn": { - []api.Volume{{Name: "badimage", VolumeSource: zeroWWN}}, - field.ErrorTypeRequired, - "fc.targetWWNs", "", - }, - "empty lun": { - []api.Volume{{Name: "badimage", VolumeSource: emptyLun}}, - field.ErrorTypeRequired, - "fc.lun", "", - }, - "slash in datasetName": { - []api.Volume{{Name: "slashinname", VolumeSource: slashInName}}, - field.ErrorTypeInvalid, - "flocker.datasetName", "must not contain '/'", - }, - "starts with '..'": { - []api.Volume{{Name: "badprefix", VolumeSource: startsWithDots}}, - field.ErrorTypeInvalid, - "gitRepo.directory", `must not start with '..'`, - }, - "contains '..'": { - []api.Volume{{Name: "containsdots", VolumeSource: containsDots}}, - field.ErrorTypeInvalid, - "gitRepo.directory", `must not contain '..'`, - }, - "absolute target": { - []api.Volume{{Name: "absolutetarget", VolumeSource: absPath}}, - field.ErrorTypeInvalid, - "gitRepo.directory", "", - }, - "empty secret": { - []api.Volume{{Name: "emptyaccount", VolumeSource: emptyAzureSecret}}, - field.ErrorTypeRequired, - "azureFile.secretName", "", - }, - "empty share": { - []api.Volume{{Name: "emptyaccount", VolumeSource: emptyAzureShare}}, - field.ErrorTypeRequired, - "azureFile.shareName", "", - }, - } - for k, v := range errorCases { - _, errs := validateVolumes(v.V, field.NewPath("field")) - if len(errs) == 0 { - t.Errorf("expected failure %s for %v", k, v.V) - continue - } - for i := range errs { - if errs[i].Type != v.T { - t.Errorf("%s: expected error to have type %q: %q", k, v.T, errs[i].Type) - } - if !strings.Contains(errs[i].Field, v.F) { - t.Errorf("%s: expected error field %q: %q", k, v.F, errs[i].Field) - } - if !strings.Contains(errs[i].Detail, v.D) { - t.Errorf("%s: expected error detail %q, got %q", k, v.D, errs[i].Detail) - } - } - } -} - -func TestValidatePorts(t *testing.T) { - successCase := []api.ContainerPort{ - {Name: "abc", ContainerPort: 80, HostPort: 80, Protocol: "TCP"}, - {Name: "easy", ContainerPort: 82, Protocol: "TCP"}, - {Name: "as", ContainerPort: 83, Protocol: "UDP"}, - {Name: "do-re-me", ContainerPort: 84, Protocol: "UDP"}, - {ContainerPort: 85, Protocol: "TCP"}, - } - if errs := validateContainerPorts(successCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - nonCanonicalCase := []api.ContainerPort{ - {ContainerPort: 80, Protocol: "TCP"}, - } - if errs := validateContainerPorts(nonCanonicalCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - errorCases := map[string]struct { - P []api.ContainerPort - T field.ErrorType - F string - D string - }{ - "name > 15 characters": { - []api.ContainerPort{{Name: strings.Repeat("a", 16), ContainerPort: 80, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "name", PortNameErrorMsg, - }, - "name not a IANA svc name ": { - []api.ContainerPort{{Name: "a.b.c", ContainerPort: 80, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "name", PortNameErrorMsg, - }, - "name not a IANA svc name (i.e. a number)": { - []api.ContainerPort{{Name: "80", ContainerPort: 80, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "name", PortNameErrorMsg, - }, - "name not unique": { - []api.ContainerPort{ - {Name: "abc", ContainerPort: 80, Protocol: "TCP"}, - {Name: "abc", ContainerPort: 81, Protocol: "TCP"}, - }, - field.ErrorTypeDuplicate, - "[1].name", "", - }, - "zero container port": { - []api.ContainerPort{{ContainerPort: 0, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "containerPort", PortRangeErrorMsg, - }, - "invalid container port": { - []api.ContainerPort{{ContainerPort: 65536, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "containerPort", PortRangeErrorMsg, - }, - "invalid host port": { - []api.ContainerPort{{ContainerPort: 80, HostPort: 65536, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "hostPort", PortRangeErrorMsg, - }, - "invalid protocol case": { - []api.ContainerPort{{ContainerPort: 80, Protocol: "tcp"}}, - field.ErrorTypeNotSupported, - "protocol", "supported values: TCP, UDP", - }, - "invalid protocol": { - []api.ContainerPort{{ContainerPort: 80, Protocol: "ICMP"}}, - field.ErrorTypeNotSupported, - "protocol", "supported values: TCP, UDP", - }, - "protocol required": { - []api.ContainerPort{{Name: "abc", ContainerPort: 80}}, - field.ErrorTypeRequired, - "protocol", "", - }, - } - for k, v := range errorCases { - errs := validateContainerPorts(v.P, field.NewPath("field")) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - if errs[i].Type != v.T { - t.Errorf("%s: expected error to have type %q: %q", k, v.T, errs[i].Type) - } - if !strings.Contains(errs[i].Field, v.F) { - t.Errorf("%s: expected error field %q: %q", k, v.F, errs[i].Field) - } - if !strings.Contains(errs[i].Detail, v.D) { - t.Errorf("%s: expected error detail %q, got %q", k, v.D, errs[i].Detail) - } - } - } -} - -func TestValidateEnv(t *testing.T) { - successCase := []api.EnvVar{ - {Name: "abc", Value: "value"}, - {Name: "ABC", Value: "value"}, - {Name: "AbC_123", Value: "value"}, - {Name: "abc", Value: ""}, - { - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: testapi.Default.GroupVersion().String(), - FieldPath: "metadata.name", - }, - }, - }, - { - Name: "secret_value", - ValueFrom: &api.EnvVarSource{ - SecretKeyRef: &api.SecretKeySelector{ - LocalObjectReference: api.LocalObjectReference{ - Name: "some-secret", - }, - Key: "secret-key", - }, - }, - }, - { - Name: "ENV_VAR_1", - ValueFrom: &api.EnvVarSource{ - ConfigMapKeyRef: &api.ConfigMapKeySelector{ - LocalObjectReference: api.LocalObjectReference{ - Name: "some-config-map", - }, - Key: "some-key", - }, - }, - }, - } - if errs := validateEnv(successCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - errorCases := []struct { - name string - envs []api.EnvVar - expectedError string - }{ - { - name: "zero-length name", - envs: []api.EnvVar{{Name: ""}}, - expectedError: "[0].name: Required value", - }, - { - name: "name not a C identifier", - envs: []api.EnvVar{{Name: "a.b.c"}}, - expectedError: `[0].name: Invalid value: "a.b.c": must be a C identifier (matching regex [A-Za-z_][A-Za-z0-9_]*): e.g. "my_name" or "MyName"`, - }, - { - name: "value and valueFrom specified", - envs: []api.EnvVar{{ - Name: "abc", - Value: "foo", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: testapi.Default.GroupVersion().String(), - FieldPath: "metadata.name", - }, - }, - }}, - expectedError: "[0].valueFrom: Invalid value: \"\": may not be specified when `value` is not empty", - }, - { - name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified", - envs: []api.EnvVar{{ - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: testapi.Default.GroupVersion().String(), - FieldPath: "metadata.name", - }, - SecretKeyRef: &api.SecretKeySelector{ - LocalObjectReference: api.LocalObjectReference{ - Name: "a-secret", - }, - Key: "a-key", - }, - }, - }}, - expectedError: "[0].valueFrom: Invalid value: \"\": may not have more than one field specified at a time", - }, - { - name: "valueFrom.fieldRef and valueFrom.configMapKeyRef set", - envs: []api.EnvVar{{ - Name: "some_var_name", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: testapi.Default.GroupVersion().String(), - FieldPath: "metadata.name", - }, - ConfigMapKeyRef: &api.ConfigMapKeySelector{ - LocalObjectReference: api.LocalObjectReference{ - Name: "some-config-map", - }, - Key: "some-key", - }, - }, - }}, - expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`, - }, - { - name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified", - envs: []api.EnvVar{{ - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: testapi.Default.GroupVersion().String(), - FieldPath: "metadata.name", - }, - SecretKeyRef: &api.SecretKeySelector{ - LocalObjectReference: api.LocalObjectReference{ - Name: "a-secret", - }, - Key: "a-key", - }, - ConfigMapKeyRef: &api.ConfigMapKeySelector{ - LocalObjectReference: api.LocalObjectReference{ - Name: "some-config-map", - }, - Key: "some-key", - }, - }, - }}, - expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`, - }, - { - name: "missing FieldPath on ObjectFieldSelector", - envs: []api.EnvVar{{ - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - APIVersion: testapi.Default.GroupVersion().String(), - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Required value`, - }, - { - name: "missing APIVersion on ObjectFieldSelector", - envs: []api.EnvVar{{ - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - FieldPath: "metadata.name", - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.apiVersion: Required value`, - }, - { - name: "invalid fieldPath", - envs: []api.EnvVar{{ - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - FieldPath: "metadata.whoops", - APIVersion: testapi.Default.GroupVersion().String(), - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Invalid value: "metadata.whoops": error converting fieldPath`, - }, - { - name: "invalid fieldPath labels", - envs: []api.EnvVar{{ - Name: "labels", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - FieldPath: "metadata.labels", - APIVersion: "v1", - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.labels": supported values: metadata.name, metadata.namespace, status.podIP`, - }, - { - name: "invalid fieldPath annotations", - envs: []api.EnvVar{{ - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - FieldPath: "metadata.annotations", - APIVersion: "v1", - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.annotations": supported values: metadata.name, metadata.namespace, status.podIP`, - }, - { - name: "unsupported fieldPath", - envs: []api.EnvVar{{ - Name: "abc", - ValueFrom: &api.EnvVarSource{ - FieldRef: &api.ObjectFieldSelector{ - FieldPath: "status.phase", - APIVersion: testapi.Default.GroupVersion().String(), - }, - }, - }}, - expectedError: `valueFrom.fieldRef.fieldPath: Unsupported value: "status.phase": supported values: metadata.name, metadata.namespace, status.podIP`, - }, - } - for _, tc := range errorCases { - if errs := validateEnv(tc.envs, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", tc.name) - } else { - for i := range errs { - str := errs[i].Error() - if str != "" && !strings.Contains(str, tc.expectedError) { - t.Errorf("%s: expected error detail either empty or %q, got %q", tc.name, tc.expectedError, str) - } - } - } - } -} - -func TestValidateVolumeMounts(t *testing.T) { - volumes := sets.NewString("abc", "123", "abc-123") - - successCase := []api.VolumeMount{ - {Name: "abc", MountPath: "/foo"}, - {Name: "123", MountPath: "/foo"}, - {Name: "abc-123", MountPath: "/bar"}, - } - if errs := validateVolumeMounts(successCase, volumes, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - errorCases := map[string][]api.VolumeMount{ - "empty name": {{Name: "", MountPath: "/foo"}}, - "name not found": {{Name: "", MountPath: "/foo"}}, - "empty mountpath": {{Name: "abc", MountPath: ""}}, - } - for k, v := range errorCases { - if errs := validateVolumeMounts(v, volumes, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func TestValidateProbe(t *testing.T) { - handler := api.Handler{Exec: &api.ExecAction{Command: []string{"echo"}}} - // These fields must be positive. - positiveFields := [...]string{"InitialDelaySeconds", "TimeoutSeconds", "PeriodSeconds", "SuccessThreshold", "FailureThreshold"} - successCases := []*api.Probe{nil} - for _, field := range positiveFields { - probe := &api.Probe{Handler: handler} - reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(10) - successCases = append(successCases, probe) - } - - for _, p := range successCases { - if errs := validateProbe(p, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []*api.Probe{{TimeoutSeconds: 10, InitialDelaySeconds: 10}} - for _, field := range positiveFields { - probe := &api.Probe{Handler: handler} - reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(-10) - errorCases = append(errorCases, probe) - } - for _, p := range errorCases { - if errs := validateProbe(p, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %v", p) - } - } -} - -func TestValidateHandler(t *testing.T) { - successCases := []api.Handler{ - {Exec: &api.ExecAction{Command: []string{"echo"}}}, - {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromInt(1), Host: "", Scheme: "HTTP"}}, - {HTTPGet: &api.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65535), Host: "host", Scheme: "HTTP"}}, - {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP"}}, - {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{"Host", "foo.example.com"}}}}, - {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{"X-Forwarded-For", "1.2.3.4"}, {"X-Forwarded-For", "5.6.7.8"}}}}, - } - for _, h := range successCases { - if errs := validateHandler(&h, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []api.Handler{ - {}, - {Exec: &api.ExecAction{Command: []string{}}}, - {HTTPGet: &api.HTTPGetAction{Path: "", Port: intstr.FromInt(0), Host: ""}}, - {HTTPGet: &api.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65536), Host: "host"}}, - {HTTPGet: &api.HTTPGetAction{Path: "", Port: intstr.FromString(""), Host: ""}}, - {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{"Host:", "foo.example.com"}}}}, - {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{"X_Forwarded_For", "foo.example.com"}}}}, - } - for _, h := range errorCases { - if errs := validateHandler(&h, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %#v", h) - } - } -} - -func TestValidatePullPolicy(t *testing.T) { - type T struct { - Container api.Container - ExpectedPolicy api.PullPolicy - } - testCases := map[string]T{ - "NotPresent1": { - api.Container{Name: "abc", Image: "image:latest", ImagePullPolicy: "IfNotPresent"}, - api.PullIfNotPresent, - }, - "NotPresent2": { - api.Container{Name: "abc1", Image: "image", ImagePullPolicy: "IfNotPresent"}, - api.PullIfNotPresent, - }, - "Always1": { - api.Container{Name: "123", Image: "image:latest", ImagePullPolicy: "Always"}, - api.PullAlways, - }, - "Always2": { - api.Container{Name: "1234", Image: "image", ImagePullPolicy: "Always"}, - api.PullAlways, - }, - "Never1": { - api.Container{Name: "abc-123", Image: "image:latest", ImagePullPolicy: "Never"}, - api.PullNever, - }, - "Never2": { - api.Container{Name: "abc-1234", Image: "image", ImagePullPolicy: "Never"}, - api.PullNever, - }, - } - for k, v := range testCases { - ctr := &v.Container - errs := validatePullPolicy(ctr.ImagePullPolicy, field.NewPath("field")) - if len(errs) != 0 { - t.Errorf("case[%s] expected success, got %#v", k, errs) - } - if ctr.ImagePullPolicy != v.ExpectedPolicy { - t.Errorf("case[%s] expected policy %v, got %v", k, v.ExpectedPolicy, ctr.ImagePullPolicy) - } - } -} - -func getResourceLimits(cpu, memory string) api.ResourceList { - res := api.ResourceList{} - res[api.ResourceCPU] = resource.MustParse(cpu) - res[api.ResourceMemory] = resource.MustParse(memory) - return res -} - -func TestValidateContainers(t *testing.T) { - volumes := sets.String{} - capabilities.SetForTests(capabilities.Capabilities{ - AllowPrivileged: true, - }) - - successCase := []api.Container{ - {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}, - {Name: "123", Image: "image", ImagePullPolicy: "IfNotPresent"}, - {Name: "abc-123", Image: "image", ImagePullPolicy: "IfNotPresent"}, - { - Name: "life-123", - Image: "image", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - Exec: &api.ExecAction{Command: []string{"ls", "-l"}}, - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - { - Name: "resources-test", - Image: "image", - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - api.ResourceName("my.org/resource"): resource.MustParse("10m"), - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - { - Name: "resources-request-limit-simple", - Image: "image", - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("8"), - }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - { - Name: "resources-request-limit-edge", - Image: "image", - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - api.ResourceName("my.org/resource"): resource.MustParse("10m"), - }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - api.ResourceName("my.org/resource"): resource.MustParse("10m"), - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - { - Name: "resources-request-limit-partials", - Image: "image", - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("9.5"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName("my.org/resource"): resource.MustParse("10m"), - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - { - Name: "resources-request", - Image: "image", - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("9.5"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - { - Name: "same-host-port-different-protocol", - Image: "image", - Ports: []api.ContainerPort{ - {ContainerPort: 80, HostPort: 80, Protocol: "TCP"}, - {ContainerPort: 80, HostPort: 80, Protocol: "UDP"}, - }, - ImagePullPolicy: "IfNotPresent", - }, - {Name: "abc-1234", Image: "image", ImagePullPolicy: "IfNotPresent", SecurityContext: fakeValidSecurityContext(true)}, - } - if errs := validateContainers(successCase, volumes, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - capabilities.SetForTests(capabilities.Capabilities{ - AllowPrivileged: false, - }) - errorCases := map[string][]api.Container{ - "zero-length name": {{Name: "", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - "name > 63 characters": {{Name: strings.Repeat("a", 64), Image: "image", ImagePullPolicy: "IfNotPresent"}}, - "name not a DNS label": {{Name: "a.b.c", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - "name not unique": { - {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}, - {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}, - }, - "zero-length image": {{Name: "abc", Image: "", ImagePullPolicy: "IfNotPresent"}}, - "host port not unique": { - {Name: "abc", Image: "image", Ports: []api.ContainerPort{{ContainerPort: 80, HostPort: 80, Protocol: "TCP"}}, - ImagePullPolicy: "IfNotPresent"}, - {Name: "def", Image: "image", Ports: []api.ContainerPort{{ContainerPort: 81, HostPort: 80, Protocol: "TCP"}}, - ImagePullPolicy: "IfNotPresent"}, - }, - "invalid env var name": { - {Name: "abc", Image: "image", Env: []api.EnvVar{{Name: "ev.1"}}, ImagePullPolicy: "IfNotPresent"}, - }, - "unknown volume name": { - {Name: "abc", Image: "image", VolumeMounts: []api.VolumeMount{{Name: "anything", MountPath: "/foo"}}, - ImagePullPolicy: "IfNotPresent"}, - }, - "invalid lifecycle, no exec command.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - Exec: &api.ExecAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "invalid lifecycle, no http path.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - HTTPGet: &api.HTTPGetAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "invalid lifecycle, no tcp socket port.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - TCPSocket: &api.TCPSocketAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "invalid lifecycle, zero tcp socket port.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{ - TCPSocket: &api.TCPSocketAction{ - Port: intstr.FromInt(0), - }, - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "invalid lifecycle, no action.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &api.Lifecycle{ - PreStop: &api.Handler{}, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "invalid liveness probe, no tcp socket port.": { - { - Name: "life-123", - Image: "image", - LivenessProbe: &api.Probe{ - Handler: api.Handler{ - TCPSocket: &api.TCPSocketAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "invalid liveness probe, no action.": { - { - Name: "life-123", - Image: "image", - LivenessProbe: &api.Probe{ - Handler: api.Handler{}, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "privilege disabled": { - {Name: "abc", Image: "image", SecurityContext: fakeValidSecurityContext(true)}, - }, - "invalid compute resource": { - { - Name: "abc-123", - Image: "image", - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - "disk": resource.MustParse("10G"), - }, - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "Resource CPU invalid": { - { - Name: "abc-123", - Image: "image", - Resources: api.ResourceRequirements{ - Limits: getResourceLimits("-10", "0"), - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "Resource Requests CPU invalid": { - { - Name: "abc-123", - Image: "image", - Resources: api.ResourceRequirements{ - Requests: getResourceLimits("-10", "0"), - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "Resource Memory invalid": { - { - Name: "abc-123", - Image: "image", - Resources: api.ResourceRequirements{ - Limits: getResourceLimits("0", "-10"), - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "Request limit simple invalid": { - { - Name: "abc-123", - Image: "image", - Resources: api.ResourceRequirements{ - Limits: getResourceLimits("5", "3"), - Requests: getResourceLimits("6", "3"), - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - "Request limit multiple invalid": { - { - Name: "abc-123", - Image: "image", - Resources: api.ResourceRequirements{ - Limits: getResourceLimits("5", "3"), - Requests: getResourceLimits("6", "4"), - }, - ImagePullPolicy: "IfNotPresent", - }, - }, - } - for k, v := range errorCases { - if errs := validateContainers(v, volumes, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func TestValidateRestartPolicy(t *testing.T) { - successCases := []api.RestartPolicy{ - api.RestartPolicyAlways, - api.RestartPolicyOnFailure, - api.RestartPolicyNever, - } - for _, policy := range successCases { - if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []api.RestartPolicy{"", "newpolicy"} - - for k, policy := range errorCases { - if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %d", k) - } - } -} - -func TestValidateDNSPolicy(t *testing.T) { - successCases := []api.DNSPolicy{api.DNSClusterFirst, api.DNSDefault, api.DNSPolicy(api.DNSClusterFirst)} - for _, policy := range successCases { - if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []api.DNSPolicy{api.DNSPolicy("invalid")} - for _, policy := range errorCases { - if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %v", policy) - } - } -} - -func TestValidatePodSpec(t *testing.T) { - activeDeadlineSeconds := int64(30) - minID := int64(0) - maxID := int64(2147483647) - successCases := []api.PodSpec{ - { // Populate basic fields, leave defaults for most. - Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}}, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - { // Populate all fields. - Volumes: []api.Volume{ - {Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, - }, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - DNSPolicy: api.DNSClusterFirst, - ActiveDeadlineSeconds: &activeDeadlineSeconds, - ServiceAccountName: "acct", - }, - { // Populate HostNetwork. - Containers: []api.Container{ - {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", Ports: []api.ContainerPort{ - {HostPort: 8080, ContainerPort: 8080, Protocol: "TCP"}}, - }, - }, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - { // Populate RunAsUser SupplementalGroups FSGroup with minID 0 - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - SupplementalGroups: []int64{minID}, - RunAsUser: &minID, - FSGroup: &minID, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - { // Populate RunAsUser SupplementalGroups FSGroup with maxID 2147483647 - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - SupplementalGroups: []int64{maxID}, - RunAsUser: &maxID, - FSGroup: &maxID, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - { // Populate HostIPC. - SecurityContext: &api.PodSecurityContext{ - HostIPC: true, - }, - Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}}, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - { // Populate HostPID. - SecurityContext: &api.PodSecurityContext{ - HostPID: true, - }, - Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}}, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - { // Populate Affinity. - Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}}, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - } - for i := range successCases { - if errs := ValidatePodSpec(&successCases[i], field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - activeDeadlineSeconds = int64(0) - minID = int64(-1) - maxID = int64(2147483648) - failureCases := map[string]api.PodSpec{ - "bad volume": { - Volumes: []api.Volume{{}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - "no containers": { - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad container": { - Containers: []api.Container{{}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad DNS policy": { - DNSPolicy: api.DNSPolicy("invalid"), - RestartPolicy: api.RestartPolicyAlways, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - "bad service account name": { - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - ServiceAccountName: "invalidName", - }, - "bad restart policy": { - RestartPolicy: "UnknowPolicy", - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - "with hostNetwork hostPort not equal to containerPort": { - Containers: []api.Container{ - {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", Ports: []api.ContainerPort{ - {HostPort: 8080, ContainerPort: 2600, Protocol: "TCP"}}, - }, - }, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: true, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad supplementalGroups large than math.MaxInt32": { - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - SupplementalGroups: []int64{maxID, 1234}, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad supplementalGroups less than 0": { - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - SupplementalGroups: []int64{minID, 1234}, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad runAsUser large than math.MaxInt32": { - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - RunAsUser: &maxID, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad runAsUser less than 0": { - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - RunAsUser: &minID, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad fsGroup large than math.MaxInt32": { - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - FSGroup: &maxID, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad fsGroup less than 0": { - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - SecurityContext: &api.PodSecurityContext{ - HostNetwork: false, - FSGroup: &minID, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - "bad-active-deadline-seconds": { - Volumes: []api.Volume{ - {Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, - }, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - DNSPolicy: api.DNSClusterFirst, - ActiveDeadlineSeconds: &activeDeadlineSeconds, - }, - "bad nodeName": { - NodeName: "node name", - Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}}, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - } - for k, v := range failureCases { - if errs := ValidatePodSpec(&v, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %q", k) - } - } -} - -func TestValidatePod(t *testing.T) { - successCases := []api.Pod{ - { // Basic fields. - ObjectMeta: api.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}}, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - }, - { // Just about everything. - ObjectMeta: api.ObjectMeta{Name: "abc.123.do-re-mi", Namespace: "ns"}, - Spec: api.PodSpec{ - Volumes: []api.Volume{ - {Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, - }, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - }, - }, - { // Serialized affinity requirements in annotations. - ObjectMeta: api.ObjectMeta{ - Name: "123", - Namespace: "ns", - // TODO: Uncomment and move this block into Annotations map once - // RequiredDuringSchedulingRequiredDuringExecution is implemented - // "requiredDuringSchedulingRequiredDuringExecution": { - // "nodeSelectorTerms": [{ - // "matchExpressions": [{ - // "key": "key1", - // "operator": "Exists" - // }] - // }] - // }, - Annotations: map[string]string{ - api.AffinityAnnotationKey: ` - {"nodeAffinity": { - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [{ - "matchExpressions": [{ - "key": "key2", - "operator": "In", - "values": ["value1", "value2"] - }] - }] - }, - "preferredDuringSchedulingIgnoredDuringExecution": [ - { - "weight": 10, - "preference": {"matchExpressions": [ - { - "key": "foo", - "operator": "In", "values": ["bar"] - } - ]} - } - ] - }}`, - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - }, - } - for _, pod := range successCases { - if errs := ValidatePod(&pod); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]api.Pod{ - "bad name": { - ObjectMeta: api.ObjectMeta{Name: "", Namespace: "ns"}, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - "bad namespace": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: ""}, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - "bad spec": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "ns"}, - Spec: api.PodSpec{ - Containers: []api.Container{{}}, - }, - }, - "bad label": { - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "ns", - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - "invalid json of affinity in pod annotations": { - ObjectMeta: api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - api.AffinityAnnotationKey: ` - {"nodeAffinity": { - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [{ - `, - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - }, - "invalid node selector requirement in affinity in pod annotations, operator can't be null": { - ObjectMeta: api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - api.AffinityAnnotationKey: ` - {"nodeAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [{ - "matchExpressions": [{ - "key": "key1", - }] - }] - }}}`, - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - }, - "invalid preferredSchedulingTerm in affinity in pod annotations, weight should be in range 1-100": { - ObjectMeta: api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - api.AffinityAnnotationKey: ` - {"nodeAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [ - { - "weight": 199, - "preference": {"matchExpressions": [ - { - "key": "foo", - "operator": "In", - "values": ["bar"] - } - ]} - } - ]}}`, - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - }, - "invalid requiredDuringSchedulingIgnoredDuringExecution node selector, nodeSelectorTerms must have at least one term": { - ObjectMeta: api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - api.AffinityAnnotationKey: ` - {"nodeAffinity": { - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [] - }, - }}`, - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - }, - "invalid requiredDuringSchedulingIgnoredDuringExecution node selector term, matchExpressions must have at least one node selector requirement": { - ObjectMeta: api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - api.AffinityAnnotationKey: ` - {"nodeAffinity": { - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [{ - "matchExpressions": [] - }] - }, - }}`, - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - }, - } - for k, v := range errorCases { - if errs := ValidatePod(&v); len(errs) == 0 { - t.Errorf("expected failure for %q", k) - } - } -} - -func TestValidatePodUpdate(t *testing.T) { - var ( - activeDeadlineSecondsZero = int64(0) - activeDeadlineSecondsNegative = int64(-30) - activeDeadlineSecondsPositive = int64(30) - activeDeadlineSecondsLarger = int64(31) - - now = unversioned.Now() - grace = int64(30) - grace2 = int64(31) - ) - - tests := []struct { - a api.Pod - b api.Pod - isValid bool - test string - }{ - {api.Pod{}, api.Pod{}, true, "nothing"}, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "bar"}, - }, - false, - "ids", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "bar": "foo", - }, - }, - }, - true, - "labels", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - "foo": "bar", - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - "bar": "foo", - }, - }, - }, - true, - "annotations", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V1", - }, - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V2", - }, - { - Image: "bar:V2", - }, - }, - }, - }, - false, - "more containers", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", DeletionTimestamp: &now}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}}, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}}, - }, - true, - "deletion timestamp filled out", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}}, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace2}, - Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}}, - }, - false, - "deletion grace period seconds cleared", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V1", - }, - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V2", - }, - }, - }, - }, - true, - "image change", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - {}, - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V2", - }, - }, - }, - }, - false, - "image change to empty", - }, - { - api.Pod{ - Spec: api.PodSpec{}, - }, - api.Pod{ - Spec: api.PodSpec{}, - }, - true, - "activeDeadlineSeconds no change, nil", - }, - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - true, - "activeDeadlineSeconds no change, set", - }, - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - api.Pod{}, - true, - "activeDeadlineSeconds change to positive from nil", - }, - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsLarger, - }, - }, - true, - "activeDeadlineSeconds change to smaller positive", - }, - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsLarger, - }, - }, - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - false, - "activeDeadlineSeconds change to larger positive", - }, - - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsNegative, - }, - }, - api.Pod{}, - false, - "activeDeadlineSeconds change to negative from nil", - }, - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsNegative, - }, - }, - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - false, - "activeDeadlineSeconds change to negative from positive", - }, - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsZero, - }, - }, - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - true, - "activeDeadlineSeconds change to zero from positive", - }, - { - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsZero, - }, - }, - api.Pod{}, - true, - "activeDeadlineSeconds change to zero from nil", - }, - { - api.Pod{}, - api.Pod{ - Spec: api.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - false, - "activeDeadlineSeconds change to nil from positive", - }, - - { - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V1", - Resources: api.ResourceRequirements{ - Limits: getResourceLimits("100m", "0"), - }, - }, - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V2", - Resources: api.ResourceRequirements{ - Limits: getResourceLimits("1000m", "0"), - }, - }, - }, - }, - }, - false, - "cpu change", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V1", - Ports: []api.ContainerPort{ - {HostPort: 8080, ContainerPort: 80}, - }, - }, - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo:V2", - Ports: []api.ContainerPort{ - {HostPort: 8000, ContainerPort: 80}, - }, - }, - }, - }, - }, - false, - "port change", - }, - { - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "Bar": "foo", - }, - }, - }, - true, - "bad label change", - }, - } - - for _, test := range tests { - test.a.ObjectMeta.ResourceVersion = "1" - test.b.ObjectMeta.ResourceVersion = "1" - errs := ValidatePodUpdate(&test.a, &test.b) - if test.isValid { - if len(errs) != 0 { - t.Errorf("unexpected invalid: %s (%+v)\nA: %+v\nB: %+v", test.test, errs, test.a, test.b) - } - } else { - if len(errs) == 0 { - t.Errorf("unexpected valid: %s\nA: %+v\nB: %+v", test.test, test.a, test.b) - } - } - } -} - -func makeValidService() api.Service { - return api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "valid", - Namespace: "valid", - Labels: map[string]string{}, - Annotations: map[string]string{}, - ResourceVersion: "1", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{"key": "val"}, - SessionAffinity: "None", - Type: api.ServiceTypeClusterIP, - Ports: []api.ServicePort{{Name: "p", Protocol: "TCP", Port: 8675, TargetPort: intstr.FromInt(8675)}}, - }, - } -} - -func TestValidateService(t *testing.T) { - testCases := []struct { - name string - tweakSvc func(svc *api.Service) // given a basic valid service, each test case can customize it - numErrs int - }{ - { - name: "missing namespace", - tweakSvc: func(s *api.Service) { - s.Namespace = "" - }, - numErrs: 1, - }, - { - name: "invalid namespace", - tweakSvc: func(s *api.Service) { - s.Namespace = "-123" - }, - numErrs: 1, - }, - { - name: "missing name", - tweakSvc: func(s *api.Service) { - s.Name = "" - }, - numErrs: 1, - }, - { - name: "invalid name", - tweakSvc: func(s *api.Service) { - s.Name = "-123" - }, - numErrs: 1, - }, - { - name: "too long name", - tweakSvc: func(s *api.Service) { - s.Name = strings.Repeat("a", 25) - }, - numErrs: 1, - }, - { - name: "invalid generateName", - tweakSvc: func(s *api.Service) { - s.GenerateName = "-123" - }, - numErrs: 1, - }, - { - name: "too long generateName", - tweakSvc: func(s *api.Service) { - s.GenerateName = strings.Repeat("a", 25) - }, - numErrs: 1, - }, - { - name: "invalid label", - tweakSvc: func(s *api.Service) { - s.Labels["NoUppercaseOrSpecialCharsLike=Equals"] = "bar" - }, - numErrs: 1, - }, - { - name: "invalid annotation", - tweakSvc: func(s *api.Service) { - s.Annotations["NoSpecialCharsLike=Equals"] = "bar" - }, - numErrs: 1, - }, - { - name: "nil selector", - tweakSvc: func(s *api.Service) { - s.Spec.Selector = nil - }, - numErrs: 0, - }, - { - name: "invalid selector", - tweakSvc: func(s *api.Service) { - s.Spec.Selector["NoSpecialCharsLike=Equals"] = "bar" - }, - numErrs: 1, - }, - { - name: "missing session affinity", - tweakSvc: func(s *api.Service) { - s.Spec.SessionAffinity = "" - }, - numErrs: 1, - }, - { - name: "missing type", - tweakSvc: func(s *api.Service) { - s.Spec.Type = "" - }, - numErrs: 1, - }, - { - name: "missing ports", - tweakSvc: func(s *api.Service) { - s.Spec.Ports = nil - }, - numErrs: 1, - }, - { - name: "missing ports but headless", - tweakSvc: func(s *api.Service) { - s.Spec.Ports = nil - s.Spec.ClusterIP = api.ClusterIPNone - }, - numErrs: 0, - }, - { - name: "empty port[0] name", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Name = "" - }, - numErrs: 0, - }, - { - name: "empty port[1] name", - tweakSvc: func(s *api.Service) { - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "empty multi-port port[0] name", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Name = "" - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "invalid port name", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Name = "INVALID" - }, - numErrs: 1, - }, - { - name: "missing protocol", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Protocol = "" - }, - numErrs: 1, - }, - { - name: "invalid protocol", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Protocol = "INVALID" - }, - numErrs: 1, - }, - { - name: "invalid cluster ip", - tweakSvc: func(s *api.Service) { - s.Spec.ClusterIP = "invalid" - }, - numErrs: 1, - }, - { - name: "missing port", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Port = 0 - }, - numErrs: 1, - }, - { - name: "invalid port", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Port = 65536 - }, - numErrs: 1, - }, - { - name: "invalid TargetPort int", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].TargetPort = intstr.FromInt(65536) - }, - numErrs: 1, - }, - { - name: "valid port headless", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Port = 11722 - s.Spec.Ports[0].TargetPort = intstr.FromInt(11722) - s.Spec.ClusterIP = api.ClusterIPNone - }, - numErrs: 0, - }, - { - name: "invalid port headless", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Port = 11722 - s.Spec.Ports[0].TargetPort = intstr.FromInt(11721) - s.Spec.ClusterIP = api.ClusterIPNone - }, - numErrs: 1, - }, - { - name: "invalid port headless", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Port = 11722 - s.Spec.Ports[0].TargetPort = intstr.FromString("target") - s.Spec.ClusterIP = api.ClusterIPNone - }, - numErrs: 1, - }, - { - name: "invalid publicIPs localhost", - tweakSvc: func(s *api.Service) { - s.Spec.ExternalIPs = []string{"127.0.0.1"} - }, - numErrs: 1, - }, - { - name: "invalid publicIPs", - tweakSvc: func(s *api.Service) { - s.Spec.ExternalIPs = []string{"0.0.0.0"} - }, - numErrs: 1, - }, - { - name: "invalid publicIPs host", - tweakSvc: func(s *api.Service) { - s.Spec.ExternalIPs = []string{"myhost.mydomain"} - }, - numErrs: 1, - }, - { - name: "dup port name", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Name = "p" - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "valid load balancer protocol UDP 1", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports[0].Protocol = "UDP" - }, - numErrs: 0, - }, - { - name: "valid load balancer protocol UDP 2", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports[0] = api.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)} - }, - numErrs: 0, - }, - { - name: "invalid load balancer with mix protocol", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "valid 1", - tweakSvc: func(s *api.Service) { - // do nothing - }, - numErrs: 0, - }, - { - name: "valid 2", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].Protocol = "UDP" - s.Spec.Ports[0].TargetPort = intstr.FromInt(12345) - }, - numErrs: 0, - }, - { - name: "valid 3", - tweakSvc: func(s *api.Service) { - s.Spec.Ports[0].TargetPort = intstr.FromString("http") - }, - numErrs: 0, - }, - { - name: "valid cluster ip - none ", - tweakSvc: func(s *api.Service) { - s.Spec.ClusterIP = "None" - }, - numErrs: 0, - }, - { - name: "valid cluster ip - empty", - tweakSvc: func(s *api.Service) { - s.Spec.ClusterIP = "" - s.Spec.Ports[0].TargetPort = intstr.FromString("http") - }, - numErrs: 0, - }, - { - name: "valid type - cluster", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeClusterIP - }, - numErrs: 0, - }, - { - name: "valid type - loadbalancer", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - }, - numErrs: 0, - }, - { - name: "valid type loadbalancer 2 ports", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid external load balancer 2 ports", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "duplicate nodeports", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)}) - }, - numErrs: 1, - }, - { - name: "duplicate nodeports (different protocols)", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "UDP", NodePort: 1, TargetPort: intstr.FromInt(2)}) - }, - numErrs: 0, - }, - { - name: "valid type - cluster", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeClusterIP - }, - numErrs: 0, - }, - { - name: "valid type - nodeport", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort - }, - numErrs: 0, - }, - { - name: "valid type - loadbalancer", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - }, - numErrs: 0, - }, - { - name: "valid type loadbalancer 2 ports", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid type loadbalancer with NodePort", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid type=NodePort service with NodePort", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid type=NodePort service without NodePort", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid cluster service without NodePort", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeClusterIP - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "invalid cluster service with NodePort", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeClusterIP - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "invalid public service with duplicate NodePort", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p1", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p2", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)}) - }, - numErrs: 1, - }, - { - name: "valid type=LoadBalancer", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - // For now we open firewalls, and its insecure if we open 10250, remove this - // when we have better protections in place. - name: "invalid port type=LoadBalancer", - tweakSvc: func(s *api.Service) { - s.Spec.Type = api.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "kubelet", Port: 10250, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - } - - for _, tc := range testCases { - svc := makeValidService() - tc.tweakSvc(&svc) - errs := ValidateService(&svc) - if len(errs) != tc.numErrs { - t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate()) - } - } -} - -func TestValidateReplicationControllerStatusUpdate(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - type rcUpdateTest struct { - old api.ReplicationController - update api.ReplicationController - } - successCases := []rcUpdateTest{ - { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: api.ReplicationControllerStatus{ - Replicas: 2, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 3, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: api.ReplicationControllerStatus{ - Replicas: 4, - }, - }, - }, - } - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateReplicationControllerStatusUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]rcUpdateTest{ - "negative replicas": { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: api.ReplicationControllerStatus{ - Replicas: 3, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: api.ReplicationControllerStatus{ - Replicas: -3, - }, - }, - }, - } - for testName, errorCase := range errorCases { - if errs := ValidateReplicationControllerStatusUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } - -} - -func TestValidateReplicationControllerUpdate(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - readWriteVolumePodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}}, - }, - }, - } - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - invalidPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - ObjectMeta: api.ObjectMeta{ - Labels: invalidSelector, - }, - }, - } - type rcUpdateTest struct { - old api.ReplicationController - update api.ReplicationController - } - successCases := []rcUpdateTest{ - { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 3, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - }, - { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - }, - } - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateReplicationControllerUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]rcUpdateTest{ - "more than one read/write": { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - }, - "invalid selector": { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Selector: invalidSelector, - Template: &validPodTemplate.Template, - }, - }, - }, - "invalid pod": { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &invalidPodTemplate.Template, - }, - }, - }, - "negative replicas": { - old: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: -1, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - }, - } - for testName, errorCase := range errorCases { - if errs := ValidateReplicationControllerUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } -} - -func TestValidateReplicationController(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - readWriteVolumePodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - invalidPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - ObjectMeta: api.ObjectMeta{ - Labels: invalidSelector, - }, - }, - } - successCases := []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateReplicationController(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]api.ReplicationController{ - "zero-length ID": { - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "missing-namespace": { - ObjectMeta: api.ObjectMeta{Name: "abc-123"}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "empty selector": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Template: &validPodTemplate.Template, - }, - }, - "selector_doesnt_match": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{"foo": "bar"}, - Template: &validPodTemplate.Template, - }, - }, - "invalid manifest": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - }, - }, - "read-write persistent disk with > 1 pod": { - ObjectMeta: api.ObjectMeta{Name: "abc"}, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - "negative_replicas": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: api.ReplicationControllerSpec{ - Replicas: -1, - Selector: validSelector, - }, - }, - "invalid_label": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "invalid_label 2": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: api.ReplicationControllerSpec{ - Template: &invalidPodTemplate.Template, - }, - }, - "invalid_annotation": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "invalid restart policy 1": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - }, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - }, - }, - }, - "invalid restart policy 2": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - }, - Spec: api.ReplicationControllerSpec{ - Selector: validSelector, - Template: &api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - }, - }, - }, - } - for k, v := range errorCases { - errs := ValidateReplicationController(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - field := errs[i].Field - if !strings.HasPrefix(field, "spec.template.") && - field != "metadata.name" && - field != "metadata.namespace" && - field != "spec.selector" && - field != "spec.template" && - field != "GCEPersistentDisk.ReadOnly" && - field != "spec.replicas" && - field != "spec.template.labels" && - field != "metadata.annotations" && - field != "metadata.labels" && - field != "status.replicas" { - t.Errorf("%s: missing prefix for: %v", k, errs[i]) - } - } - } -} - -func TestValidateNode(t *testing.T) { - validSelector := map[string]string{"a": "b"} - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - successCases := []api.Node{ - { - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Labels: validSelector, - }, - Status: api.NodeStatus{ - Addresses: []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: "something"}, - }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - api.ResourceName("my.org/gpu"): resource.MustParse("10"), - }, - }, - Spec: api.NodeSpec{ - ExternalID: "external", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - Status: api.NodeStatus{ - Addresses: []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: "something"}, - }, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: api.NodeSpec{ - ExternalID: "external", - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateNode(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]api.Node{ - "zero-length Name": { - ObjectMeta: api.ObjectMeta{ - Name: "", - Labels: validSelector, - }, - Status: api.NodeStatus{ - Addresses: []api.NodeAddress{}, - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - Spec: api.NodeSpec{ - ExternalID: "external", - }, - }, - "invalid-labels": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Labels: invalidSelector, - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - Spec: api.NodeSpec{ - ExternalID: "external", - }, - }, - "missing-external-id": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Labels: validSelector, - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("10"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - }, - } - for k, v := range errorCases { - errs := ValidateNode(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - field := errs[i].Field - expectedFields := map[string]bool{ - "metadata.name": true, - "metadata.labels": true, - "metadata.annotations": true, - "metadata.namespace": true, - "spec.externalID": true, - } - if expectedFields[field] == false { - t.Errorf("%s: missing prefix for: %v", k, errs[i]) - } - } - } -} - -func TestValidateNodeUpdate(t *testing.T) { - tests := []struct { - oldNode api.Node - node api.Node - valid bool - }{ - {api.Node{}, api.Node{}, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}}, - api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "bar"}, - }, false}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar"}, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "foo"}, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - PodCIDR: "", - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - PodCIDR: "192.168.0.0/16", - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - PodCIDR: "192.123.0.0/16", - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - PodCIDR: "192.168.0.0/16", - }, - }, false}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: resource.MustParse("10000"), - api.ResourceMemory: resource.MustParse("100"), - }, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - }, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "foo"}, - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: resource.MustParse("10000"), - api.ResourceMemory: resource.MustParse("100"), - }, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "fooobaz"}, - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - }, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "foo"}, - }, - Status: api.NodeStatus{ - Addresses: []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: "1.2.3.4"}, - }, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "fooobaz"}, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"Foo": "baz"}, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - Unschedulable: false, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - Unschedulable: true, - }, - }, true}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - Unschedulable: false, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Status: api.NodeStatus{ - Addresses: []api.NodeAddress{ - {Type: api.NodeExternalIP, Address: "1.1.1.1"}, - {Type: api.NodeExternalIP, Address: "1.1.1.1"}, - }, - }, - }, false}, - {api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - Unschedulable: false, - }, - }, api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Status: api.NodeStatus{ - Addresses: []api.NodeAddress{ - {Type: api.NodeExternalIP, Address: "1.1.1.1"}, - {Type: api.NodeInternalIP, Address: "10.1.1.1"}, - }, - }, - }, true}, - } - for i, test := range tests { - test.oldNode.ObjectMeta.ResourceVersion = "1" - test.node.ObjectMeta.ResourceVersion = "1" - errs := ValidateNodeUpdate(&test.node, &test.oldNode) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNode.ObjectMeta, test.node.ObjectMeta) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateServiceUpdate(t *testing.T) { - testCases := []struct { - name string - tweakSvc func(oldSvc, newSvc *api.Service) // given basic valid services, each test case can customize them - numErrs int - }{ - { - name: "no change", - tweakSvc: func(oldSvc, newSvc *api.Service) { - // do nothing - }, - numErrs: 0, - }, - { - name: "change name", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Name += "2" - }, - numErrs: 1, - }, - { - name: "change namespace", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Namespace += "2" - }, - numErrs: 1, - }, - { - name: "change label valid", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Labels["key"] = "other-value" - }, - numErrs: 0, - }, - { - name: "add label", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Labels["key2"] = "value2" - }, - numErrs: 0, - }, - { - name: "change cluster IP", - tweakSvc: func(oldSvc, newSvc *api.Service) { - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "8.6.7.5" - }, - numErrs: 1, - }, - { - name: "remove cluster IP", - tweakSvc: func(oldSvc, newSvc *api.Service) { - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "" - }, - numErrs: 1, - }, - { - name: "change affinity", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Spec.SessionAffinity = "ClientIP" - }, - numErrs: 0, - }, - { - name: "remove affinity", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Spec.SessionAffinity = "" - }, - numErrs: 1, - }, - { - name: "change type", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Spec.Type = api.ServiceTypeLoadBalancer - }, - numErrs: 0, - }, - { - name: "remove type", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Spec.Type = "" - }, - numErrs: 1, - }, - { - name: "change type -> nodeport", - tweakSvc: func(oldSvc, newSvc *api.Service) { - newSvc.Spec.Type = api.ServiceTypeNodePort - }, - numErrs: 0, - }, - } - - for _, tc := range testCases { - oldSvc := makeValidService() - newSvc := makeValidService() - tc.tweakSvc(&oldSvc, &newSvc) - errs := ValidateServiceUpdate(&newSvc, &oldSvc) - if len(errs) != tc.numErrs { - t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate()) - } - } -} - -func TestValidateResourceNames(t *testing.T) { - table := []struct { - input string - success bool - }{ - {"memory", true}, - {"cpu", true}, - {"network", false}, - {"disk", false}, - {"", false}, - {".", false}, - {"..", false}, - {"my.favorite.app.co/12345", true}, - {"my.favorite.app.co/_12345", false}, - {"my.favorite.app.co/12345_", false}, - {"kubernetes.io/..", false}, - {"kubernetes.io/" + strings.Repeat("a", 63), true}, - {"kubernetes.io/" + strings.Repeat("a", 64), false}, - {"kubernetes.io//", false}, - {"kubernetes.io", false}, - {"kubernetes.io/will/not/work/", false}, - } - for k, item := range table { - err := validateResourceName(item.input, field.NewPath("field")) - if len(err) != 0 && item.success { - t.Errorf("expected no failure for input %q", item.input) - } else if len(err) == 0 && !item.success { - t.Errorf("expected failure for input %q", item.input) - for i := range err { - detail := err[i].Detail - if detail != "" && detail != qualifiedNameErrorMsg { - t.Errorf("%d: expected error detail either empty or %s, got %s", k, qualifiedNameErrorMsg, detail) - } - } - } - } -} - -func getResourceList(cpu, memory string) api.ResourceList { - res := api.ResourceList{} - if cpu != "" { - res[api.ResourceCPU] = resource.MustParse(cpu) - } - if memory != "" { - res[api.ResourceMemory] = resource.MustParse(memory) - } - return res -} - -func TestValidateLimitRange(t *testing.T) { - successCases := []struct { - name string - spec api.LimitRangeSpec - }{ - { - name: "all-fields-valid", - spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: getResourceList("100m", "10000Mi"), - Min: getResourceList("5m", "100Mi"), - MaxLimitRequestRatio: getResourceList("10", ""), - }, - { - Type: api.LimitTypeContainer, - Max: getResourceList("100m", "10000Mi"), - Min: getResourceList("5m", "100Mi"), - Default: getResourceList("50m", "500Mi"), - DefaultRequest: getResourceList("10m", "200Mi"), - MaxLimitRequestRatio: getResourceList("10", ""), - }, - }, - }, - }, - { - name: "all-fields-valid-big-numbers", - spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypeContainer, - Max: getResourceList("100m", "10000T"), - Min: getResourceList("5m", "100Mi"), - Default: getResourceList("50m", "500Mi"), - DefaultRequest: getResourceList("10m", "200Mi"), - MaxLimitRequestRatio: getResourceList("10", ""), - }, - }, - }, - }, - } - - for _, successCase := range successCases { - limitRange := &api.LimitRange{ObjectMeta: api.ObjectMeta{Name: successCase.name, Namespace: "foo"}, Spec: successCase.spec} - if errs := ValidateLimitRange(limitRange); len(errs) != 0 { - t.Errorf("Case %v, unexpected error: %v", successCase.name, errs) - } - } - - errorCases := map[string]struct { - R api.LimitRange - D string - }{ - "zero-length-name": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "", Namespace: "foo"}, Spec: api.LimitRangeSpec{}}, - "name or generateName is required", - }, - "zero-length-namespace": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: ""}, Spec: api.LimitRangeSpec{}}, - "", - }, - "invalid-name": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: api.LimitRangeSpec{}}, - DNSSubdomainErrorMsg, - }, - "invalid-namespace": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: api.LimitRangeSpec{}}, - DNS1123LabelErrorMsg, - }, - "duplicate-limit-type": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: getResourceList("100m", "10000m"), - Min: getResourceList("0m", "100m"), - }, - { - Type: api.LimitTypePod, - Min: getResourceList("0m", "100m"), - }, - }, - }}, - "", - }, - "default-limit-type-pod": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: getResourceList("100m", "10000m"), - Min: getResourceList("0m", "100m"), - Default: getResourceList("10m", "100m"), - }, - }, - }}, - "may not be specified when `type` is 'Pod'", - }, - "default-request-limit-type-pod": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: getResourceList("100m", "10000m"), - Min: getResourceList("0m", "100m"), - DefaultRequest: getResourceList("10m", "100m"), - }, - }, - }}, - "may not be specified when `type` is 'Pod'", - }, - "min value 100m is greater than max value 10m": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: getResourceList("10m", ""), - Min: getResourceList("100m", ""), - }, - }, - }}, - "min value 100m is greater than max value 10m", - }, - "invalid spec default outside range": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypeContainer, - Max: getResourceList("1", ""), - Min: getResourceList("100m", ""), - Default: getResourceList("2000m", ""), - }, - }, - }}, - "default value 2 is greater than max value 1", - }, - "invalid spec defaultrequest outside range": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypeContainer, - Max: getResourceList("1", ""), - Min: getResourceList("100m", ""), - DefaultRequest: getResourceList("2000m", ""), - }, - }, - }}, - "default request value 2 is greater than max value 1", - }, - "invalid spec defaultrequest more than default": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypeContainer, - Max: getResourceList("2", ""), - Min: getResourceList("100m", ""), - Default: getResourceList("500m", ""), - DefaultRequest: getResourceList("800m", ""), - }, - }, - }}, - "default request value 800m is greater than default limit value 500m", - }, - "invalid spec maxLimitRequestRatio less than 1": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - MaxLimitRequestRatio: getResourceList("800m", ""), - }, - }, - }}, - "ratio 800m is less than 1", - }, - "invalid spec maxLimitRequestRatio greater than max/min": { - api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypeContainer, - Max: getResourceList("", "2Gi"), - Min: getResourceList("", "512Mi"), - MaxLimitRequestRatio: getResourceList("", "10"), - }, - }, - }}, - "ratio 10 is greater than max/min = 4.000000", - }, - } - - for k, v := range errorCases { - errs := ValidateLimitRange(&v.R) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - detail := errs[i].Detail - if detail != v.D { - t.Errorf("[%s]: expected error detail either empty or %q, got %q", k, v.D, detail) - } - } - } - -} - -func TestValidateResourceQuota(t *testing.T) { - spec := api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - api.ResourcePods: resource.MustParse("10"), - api.ResourceServices: resource.MustParse("0"), - api.ResourceReplicationControllers: resource.MustParse("10"), - api.ResourceQuotas: resource.MustParse("10"), - }, - } - - negativeSpec := api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("-100"), - api.ResourceMemory: resource.MustParse("-10000"), - api.ResourcePods: resource.MustParse("-10"), - api.ResourceServices: resource.MustParse("-10"), - api.ResourceReplicationControllers: resource.MustParse("-10"), - api.ResourceQuotas: resource.MustParse("-10"), - }, - } - - fractionalComputeSpec := api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100m"), - }, - } - - fractionalPodSpec := api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourcePods: resource.MustParse(".1"), - api.ResourceServices: resource.MustParse(".5"), - api.ResourceReplicationControllers: resource.MustParse("1.25"), - api.ResourceQuotas: resource.MustParse("2.5"), - }, - } - - successCases := []api.ResourceQuota{ - { - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: spec, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: fractionalComputeSpec, - }, - } - - for _, successCase := range successCases { - if errs := ValidateResourceQuota(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]struct { - R api.ResourceQuota - D string - }{ - "zero-length Name": { - api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "", Namespace: "foo"}, Spec: spec}, - "name or generateName is required", - }, - "zero-length Namespace": { - api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: ""}, Spec: spec}, - "", - }, - "invalid Name": { - api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: spec}, - DNSSubdomainErrorMsg, - }, - "invalid Namespace": { - api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: spec}, - DNS1123LabelErrorMsg, - }, - "negative-limits": { - api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: negativeSpec}, - isNegativeErrorMsg, - }, - "fractional-api-resource": { - api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: fractionalPodSpec}, - isNotIntegerErrorMsg, - }, - } - for k, v := range errorCases { - errs := ValidateResourceQuota(&v.R) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - if errs[i].Detail != v.D { - t.Errorf("[%s]: expected error detail either empty or %s, got %s", k, v.D, errs[i].Detail) - } - } - } -} - -func TestValidateNamespace(t *testing.T) { - validLabels := map[string]string{"a": "b"} - invalidLabels := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - successCases := []api.Namespace{ - { - ObjectMeta: api.ObjectMeta{Name: "abc", Labels: validLabels}, - }, - { - ObjectMeta: api.ObjectMeta{Name: "abc-123"}, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"example.com/something", "example.com/other"}, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateNamespace(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]struct { - R api.Namespace - D string - }{ - "zero-length name": { - api.Namespace{ObjectMeta: api.ObjectMeta{Name: ""}}, - "", - }, - "defined-namespace": { - api.Namespace{ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: "makesnosense"}}, - "", - }, - "invalid-labels": { - api.Namespace{ObjectMeta: api.ObjectMeta{Name: "abc", Labels: invalidLabels}}, - "", - }, - } - for k, v := range errorCases { - errs := ValidateNamespace(&v.R) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func TestValidateNamespaceFinalizeUpdate(t *testing.T) { - tests := []struct { - oldNamespace api.Namespace - namespace api.Namespace - valid bool - }{ - {api.Namespace{}, api.Namespace{}, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}}, - api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"Foo"}, - }, - }, false}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"foo.com/bar"}, - }, - }, - api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"foo.com/bar", "what.com/bar"}, - }, - }, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "fooemptyfinalizer"}, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"foo.com/bar"}, - }, - }, - api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "fooemptyfinalizer"}, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"", "foo.com/bar", "what.com/bar"}, - }, - }, false}, - } - for i, test := range tests { - test.namespace.ObjectMeta.ResourceVersion = "1" - test.oldNamespace.ObjectMeta.ResourceVersion = "1" - errs := ValidateNamespaceFinalizeUpdate(&test.namespace, &test.oldNamespace) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNamespace, test.namespace) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateNamespaceStatusUpdate(t *testing.T) { - now := unversioned.Now() - - tests := []struct { - oldNamespace api.Namespace - namespace api.Namespace - valid bool - }{ - {api.Namespace{}, api.Namespace{ - Status: api.NamespaceStatus{ - Phase: api.NamespaceActive, - }, - }, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}}, - api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - DeletionTimestamp: &now}, - Status: api.NamespaceStatus{ - Phase: api.NamespaceTerminating, - }, - }, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}}, - api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}, - Status: api.NamespaceStatus{ - Phase: api.NamespaceTerminating, - }, - }, false}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo"}}, - api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "bar"}, - Status: api.NamespaceStatus{ - Phase: api.NamespaceTerminating, - }, - }, false}, - } - for i, test := range tests { - test.namespace.ObjectMeta.ResourceVersion = "1" - test.oldNamespace.ObjectMeta.ResourceVersion = "1" - errs := ValidateNamespaceStatusUpdate(&test.namespace, &test.oldNamespace) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateNamespaceUpdate(t *testing.T) { - tests := []struct { - oldNamespace api.Namespace - namespace api.Namespace - valid bool - }{ - {api.Namespace{}, api.Namespace{}, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo1"}}, - api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "bar1"}, - }, false}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo2", - Labels: map[string]string{"foo": "bar"}, - }, - }, api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo2", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo3", - }, - }, api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo3", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo4", - Labels: map[string]string{"bar": "foo"}, - }, - }, api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo4", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo5", - Labels: map[string]string{"foo": "baz"}, - }, - }, api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo5", - Labels: map[string]string{"Foo": "baz"}, - }, - }, true}, - {api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo6", - Labels: map[string]string{"foo": "baz"}, - }, - }, api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo6", - Labels: map[string]string{"Foo": "baz"}, - }, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{"kubernetes"}, - }, - Status: api.NamespaceStatus{ - Phase: api.NamespaceTerminating, - }, - }, true}, - } - for i, test := range tests { - test.namespace.ObjectMeta.ResourceVersion = "1" - test.oldNamespace.ObjectMeta.ResourceVersion = "1" - errs := ValidateNamespaceUpdate(&test.namespace, &test.oldNamespace) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateSecret(t *testing.T) { - // Opaque secret validation - validSecret := func() api.Secret { - return api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, - Data: map[string][]byte{ - "data-1": []byte("bar"), - }, - } - } - - var ( - emptyName = validSecret() - invalidName = validSecret() - emptyNs = validSecret() - invalidNs = validSecret() - overMaxSize = validSecret() - invalidKey = validSecret() - leadingDotKey = validSecret() - dotKey = validSecret() - doubleDotKey = validSecret() - ) - - emptyName.Name = "" - invalidName.Name = "NoUppercaseOrSpecialCharsLike=Equals" - emptyNs.Namespace = "" - invalidNs.Namespace = "NoUppercaseOrSpecialCharsLike=Equals" - overMaxSize.Data = map[string][]byte{ - "over": make([]byte, api.MaxSecretSize+1), - } - invalidKey.Data["a..b"] = []byte("whoops") - leadingDotKey.Data[".key"] = []byte("bar") - dotKey.Data["."] = []byte("bar") - doubleDotKey.Data[".."] = []byte("bar") - - // kubernetes.io/service-account-token secret validation - validServiceAccountTokenSecret := func() api.Secret { - return api.Secret{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Annotations: map[string]string{ - api.ServiceAccountNameKey: "foo", - }, - }, - Type: api.SecretTypeServiceAccountToken, - Data: map[string][]byte{ - "data-1": []byte("bar"), - }, - } - } - - var ( - emptyTokenAnnotation = validServiceAccountTokenSecret() - missingTokenAnnotation = validServiceAccountTokenSecret() - missingTokenAnnotations = validServiceAccountTokenSecret() - ) - emptyTokenAnnotation.Annotations[api.ServiceAccountNameKey] = "" - delete(missingTokenAnnotation.Annotations, api.ServiceAccountNameKey) - missingTokenAnnotations.Annotations = nil - - tests := map[string]struct { - secret api.Secret - valid bool - }{ - "valid": {validSecret(), true}, - "empty name": {emptyName, false}, - "invalid name": {invalidName, false}, - "empty namespace": {emptyNs, false}, - "invalid namespace": {invalidNs, false}, - "over max size": {overMaxSize, false}, - "invalid key": {invalidKey, false}, - "valid service-account-token secret": {validServiceAccountTokenSecret(), true}, - "empty service-account-token annotation": {emptyTokenAnnotation, false}, - "missing service-account-token annotation": {missingTokenAnnotation, false}, - "missing service-account-token annotations": {missingTokenAnnotations, false}, - "leading dot key": {leadingDotKey, true}, - "dot key": {dotKey, false}, - "double dot key": {doubleDotKey, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateDockerConfigSecret(t *testing.T) { - validDockerSecret := func() api.Secret { - return api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: api.SecretTypeDockercfg, - Data: map[string][]byte{ - api.DockerConfigKey: []byte(`{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}`), - }, - } - } - validDockerSecret2 := func() api.Secret { - return api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: api.SecretTypeDockerConfigJson, - Data: map[string][]byte{ - api.DockerConfigJsonKey: []byte(`{"auths":{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}}`), - }, - } - } - - var ( - missingDockerConfigKey = validDockerSecret() - emptyDockerConfigKey = validDockerSecret() - invalidDockerConfigKey = validDockerSecret() - missingDockerConfigKey2 = validDockerSecret2() - emptyDockerConfigKey2 = validDockerSecret2() - invalidDockerConfigKey2 = validDockerSecret2() - ) - - delete(missingDockerConfigKey.Data, api.DockerConfigKey) - emptyDockerConfigKey.Data[api.DockerConfigKey] = []byte("") - invalidDockerConfigKey.Data[api.DockerConfigKey] = []byte("bad") - delete(missingDockerConfigKey2.Data, api.DockerConfigJsonKey) - emptyDockerConfigKey2.Data[api.DockerConfigJsonKey] = []byte("") - invalidDockerConfigKey2.Data[api.DockerConfigJsonKey] = []byte("bad") - - tests := map[string]struct { - secret api.Secret - valid bool - }{ - "valid dockercfg": {validDockerSecret(), true}, - "missing dockercfg": {missingDockerConfigKey, false}, - "empty dockercfg": {emptyDockerConfigKey, false}, - "invalid dockercfg": {invalidDockerConfigKey, false}, - "valid config.json": {validDockerSecret2(), true}, - "missing config.json": {missingDockerConfigKey2, false}, - "empty config.json": {emptyDockerConfigKey2, false}, - "invalid config.json": {invalidDockerConfigKey2, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateBasicAuthSecret(t *testing.T) { - validBasicAuthSecret := func() api.Secret { - return api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: api.SecretTypeBasicAuth, - Data: map[string][]byte{ - api.BasicAuthUsernameKey: []byte("username"), - api.BasicAuthPasswordKey: []byte("password"), - }, - } - } - - var ( - missingBasicAuthUsernamePasswordKeys = validBasicAuthSecret() - // invalidBasicAuthUsernamePasswordKey = validBasicAuthSecret() - // emptyBasicAuthUsernameKey = validBasicAuthSecret() - // emptyBasicAuthPasswordKey = validBasicAuthSecret() - ) - - delete(missingBasicAuthUsernamePasswordKeys.Data, api.BasicAuthUsernameKey) - delete(missingBasicAuthUsernamePasswordKeys.Data, api.BasicAuthPasswordKey) - - // invalidBasicAuthUsernamePasswordKey.Data[api.BasicAuthUsernameKey] = []byte("bad") - // invalidBasicAuthUsernamePasswordKey.Data[api.BasicAuthPasswordKey] = []byte("bad") - - // emptyBasicAuthUsernameKey.Data[api.BasicAuthUsernameKey] = []byte("") - // emptyBasicAuthPasswordKey.Data[api.BasicAuthPasswordKey] = []byte("") - - tests := map[string]struct { - secret api.Secret - valid bool - }{ - "valid": {validBasicAuthSecret(), true}, - "missing username and password": {missingBasicAuthUsernamePasswordKeys, false}, - // "invalid username and password": {invalidBasicAuthUsernamePasswordKey, false}, - // "empty username": {emptyBasicAuthUsernameKey, false}, - // "empty password": {emptyBasicAuthPasswordKey, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateSSHAuthSecret(t *testing.T) { - validSSHAuthSecret := func() api.Secret { - return api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: api.SecretTypeSSHAuth, - Data: map[string][]byte{ - api.SSHAuthPrivateKey: []byte("foo-bar-baz"), - }, - } - } - - missingSSHAuthPrivateKey := validSSHAuthSecret() - - delete(missingSSHAuthPrivateKey.Data, api.SSHAuthPrivateKey) - - tests := map[string]struct { - secret api.Secret - valid bool - }{ - "valid": {validSSHAuthSecret(), true}, - "missing private key": {missingSSHAuthPrivateKey, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateEndpoints(t *testing.T) { - successCases := map[string]api.Endpoints{ - "simple endpoint": { - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}, {IP: "10.10.2.2"}}, - Ports: []api.EndpointPort{{Name: "a", Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}}, - }, - { - Addresses: []api.EndpointAddress{{IP: "10.10.3.3"}}, - Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}, {Name: "b", Port: 76, Protocol: "TCP"}}, - }, - }, - }, - "empty subsets": { - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - }, - "no name required for singleton port": { - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []api.EndpointPort{{Port: 8675, Protocol: "TCP"}}, - }, - }, - }, - } - - for k, v := range successCases { - if errs := ValidateEndpoints(&v); len(errs) != 0 { - t.Errorf("Expected success for %s, got %v", k, errs) - } - } - - errorCases := map[string]struct { - endpoints api.Endpoints - errorType field.ErrorType - errorDetail string - }{ - "missing namespace": { - endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "mysvc"}}, - errorType: "FieldValueRequired", - }, - "missing name": { - endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Namespace: "namespace"}}, - errorType: "FieldValueRequired", - }, - "invalid namespace": { - endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "no@#invalid.;chars\"allowed"}}, - errorType: "FieldValueInvalid", - errorDetail: DNS1123LabelErrorMsg, - }, - "invalid name": { - endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "-_Invliad^&Characters", Namespace: "namespace"}}, - errorType: "FieldValueInvalid", - errorDetail: DNSSubdomainErrorMsg, - }, - "empty addresses": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueRequired", - }, - "empty ports": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.3.3"}}, - }, - }, - }, - errorType: "FieldValueRequired", - }, - "invalid IP": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "2001:0db8:85a3:0042:1000:8a2e:0370:7334"}}, - Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "must be a valid IPv4 address", - }, - "Multiple ports, one without name": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []api.EndpointPort{{Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueRequired", - }, - "Invalid port number": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []api.EndpointPort{{Name: "a", Port: 66000, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: PortRangeErrorMsg, - }, - "Invalid protocol": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "Protocol"}}, - }, - }, - }, - errorType: "FieldValueNotSupported", - }, - "Address missing IP": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{}}, - Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "must be a valid IPv4 address", - }, - "Port missing number": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []api.EndpointPort{{Name: "a", Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: PortRangeErrorMsg, - }, - "Port missing protocol": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []api.EndpointPort{{Name: "a", Port: 93}}, - }, - }, - }, - errorType: "FieldValueRequired", - }, - "Address is loopback": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}}, - Ports: []api.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "loopback", - }, - "Address is link-local": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "169.254.169.254"}}, - Ports: []api.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "link-local", - }, - "Address is link-local multicast": { - endpoints: api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []api.EndpointSubset{ - { - Addresses: []api.EndpointAddress{{IP: "224.0.0.1"}}, - Ports: []api.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "link-local multicast", - }, - } - - for k, v := range errorCases { - if errs := ValidateEndpoints(&v.endpoints); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) { - t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs) - } - } -} - -func TestValidateTLSSecret(t *testing.T) { - successCases := map[string]api.Secret{ - "emtpy certificate chain": { - ObjectMeta: api.ObjectMeta{Name: "tls-cert", Namespace: "namespace"}, - Data: map[string][]byte{ - api.TLSCertKey: []byte("public key"), - api.TLSPrivateKeyKey: []byte("private key"), - }, - }, - } - for k, v := range successCases { - if errs := ValidateSecret(&v); len(errs) != 0 { - t.Errorf("Expected success for %s, got %v", k, errs) - } - } - errorCases := map[string]struct { - secrets api.Secret - errorType field.ErrorType - errorDetail string - }{ - "missing public key": { - secrets: api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "tls-cert"}, - Data: map[string][]byte{ - api.TLSCertKey: []byte("public key"), - }, - }, - errorType: "FieldValueRequired", - }, - "missing private key": { - secrets: api.Secret{ - ObjectMeta: api.ObjectMeta{Name: "tls-cert"}, - Data: map[string][]byte{ - api.TLSCertKey: []byte("public key"), - }, - }, - errorType: "FieldValueRequired", - }, - } - for k, v := range errorCases { - if errs := ValidateSecret(&v.secrets); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) { - t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs) - } - } -} - -func TestValidateSecurityContext(t *testing.T) { - priv := false - var runAsUser int64 = 1 - fullValidSC := func() *api.SecurityContext { - return &api.SecurityContext{ - Privileged: &priv, - Capabilities: &api.Capabilities{ - Add: []api.Capability{"foo"}, - Drop: []api.Capability{"bar"}, - }, - SELinuxOptions: &api.SELinuxOptions{ - User: "user", - Role: "role", - Type: "type", - Level: "level", - }, - RunAsUser: &runAsUser, - } - } - - //setup data - allSettings := fullValidSC() - noCaps := fullValidSC() - noCaps.Capabilities = nil - - noSELinux := fullValidSC() - noSELinux.SELinuxOptions = nil - - noPrivRequest := fullValidSC() - noPrivRequest.Privileged = nil - - noRunAsUser := fullValidSC() - noRunAsUser.RunAsUser = nil - - successCases := map[string]struct { - sc *api.SecurityContext - }{ - "all settings": {allSettings}, - "no capabilities": {noCaps}, - "no selinux": {noSELinux}, - "no priv request": {noPrivRequest}, - "no run as user": {noRunAsUser}, - } - for k, v := range successCases { - if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) != 0 { - t.Errorf("[%s] Expected success, got %v", k, errs) - } - } - - privRequestWithGlobalDeny := fullValidSC() - requestPrivileged := true - privRequestWithGlobalDeny.Privileged = &requestPrivileged - - negativeRunAsUser := fullValidSC() - var negativeUser int64 = -1 - negativeRunAsUser.RunAsUser = &negativeUser - - errorCases := map[string]struct { - sc *api.SecurityContext - errorType field.ErrorType - errorDetail string - }{ - "request privileged when capabilities forbids": { - sc: privRequestWithGlobalDeny, - errorType: "FieldValueForbidden", - errorDetail: "disallowed by policy", - }, - "negative RunAsUser": { - sc: negativeRunAsUser, - errorType: "FieldValueInvalid", - errorDetail: isNegativeErrorMsg, - }, - } - for k, v := range errorCases { - if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) { - t.Errorf("[%s] Expected error type %q with detail %q, got %v", k, v.errorType, v.errorDetail, errs) - } - } -} - -func fakeValidSecurityContext(priv bool) *api.SecurityContext { - return &api.SecurityContext{ - Privileged: &priv, - } -} - -func TestValidPodLogOptions(t *testing.T) { - now := unversioned.Now() - negative := int64(-1) - zero := int64(0) - positive := int64(1) - tests := []struct { - opt api.PodLogOptions - errs int - }{ - {api.PodLogOptions{}, 0}, - {api.PodLogOptions{Previous: true}, 0}, - {api.PodLogOptions{Follow: true}, 0}, - {api.PodLogOptions{TailLines: &zero}, 0}, - {api.PodLogOptions{TailLines: &negative}, 1}, - {api.PodLogOptions{TailLines: &positive}, 0}, - {api.PodLogOptions{LimitBytes: &zero}, 1}, - {api.PodLogOptions{LimitBytes: &negative}, 1}, - {api.PodLogOptions{LimitBytes: &positive}, 0}, - {api.PodLogOptions{SinceSeconds: &negative}, 1}, - {api.PodLogOptions{SinceSeconds: &positive}, 0}, - {api.PodLogOptions{SinceSeconds: &zero}, 1}, - {api.PodLogOptions{SinceTime: &now}, 0}, - } - for i, test := range tests { - errs := ValidatePodLogOptions(&test.opt) - if test.errs != len(errs) { - t.Errorf("%d: Unexpected errors: %v", i, errs) - } - } -} - -func TestValidateConfigMap(t *testing.T) { - newConfigMap := func(name, namespace string, data map[string]string) api.ConfigMap { - return api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Data: data, - } - } - - var ( - validConfigMap = newConfigMap("validname", "validns", map[string]string{"key": "value"}) - maxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 253): "value"}) - - emptyName = newConfigMap("", "validns", nil) - invalidName = newConfigMap("NoUppercaseOrSpecialCharsLike=Equals", "validns", nil) - emptyNs = newConfigMap("validname", "", nil) - invalidNs = newConfigMap("validname", "NoUppercaseOrSpecialCharsLike=Equals", nil) - invalidKey = newConfigMap("validname", "validns", map[string]string{"a..b": "value"}) - leadingDotKey = newConfigMap("validname", "validns", map[string]string{".ab": "value"}) - dotKey = newConfigMap("validname", "validns", map[string]string{".": "value"}) - doubleDotKey = newConfigMap("validname", "validns", map[string]string{"..": "value"}) - overMaxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 254): "value"}) - overMaxSize = newConfigMap("validname", "validns", map[string]string{"key": strings.Repeat("a", api.MaxSecretSize+1)}) - ) - - tests := map[string]struct { - cfg api.ConfigMap - isValid bool - }{ - "valid": {validConfigMap, true}, - "max key length": {maxKeyLength, true}, - "leading dot key": {leadingDotKey, true}, - "empty name": {emptyName, false}, - "invalid name": {invalidName, false}, - "invalid key": {invalidKey, false}, - "empty namespace": {emptyNs, false}, - "invalid namespace": {invalidNs, false}, - "dot key": {dotKey, false}, - "double dot key": {doubleDotKey, false}, - "over max key length": {overMaxKeyLength, false}, - "over max size": {overMaxSize, false}, - } - - for name, tc := range tests { - errs := ValidateConfigMap(&tc.cfg) - if tc.isValid && len(errs) > 0 { - t.Errorf("%v: unexpected error: %v", name, errs) - } - if !tc.isValid && len(errs) == 0 { - t.Errorf("%v: unexpected non-error", name) - } - } -} - -func TestValidateConfigMapUpdate(t *testing.T) { - newConfigMap := func(version, name, namespace string, data map[string]string) api.ConfigMap { - return api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: namespace, - ResourceVersion: version, - }, - Data: data, - } - } - - var ( - validConfigMap = newConfigMap("1", "validname", "validns", map[string]string{"key": "value"}) - noVersion = newConfigMap("", "validname", "validns", map[string]string{"key": "value"}) - ) - - cases := []struct { - name string - newCfg api.ConfigMap - oldCfg api.ConfigMap - isValid bool - }{ - { - name: "valid", - newCfg: validConfigMap, - oldCfg: validConfigMap, - isValid: true, - }, - { - name: "invalid", - newCfg: noVersion, - oldCfg: validConfigMap, - isValid: false, - }, - } - - for _, tc := range cases { - errs := ValidateConfigMapUpdate(&tc.newCfg, &tc.oldCfg) - if tc.isValid && len(errs) > 0 { - t.Errorf("%v: unexpected error: %v", tc.name, errs) - } - if !tc.isValid && len(errs) == 0 { - t.Errorf("%v: unexpected non-error", tc.name) - } - } -} - -func TestValidateHasLabel(t *testing.T) { - successCase := api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Labels: map[string]string{ - "other": "blah", - "foo": "bar", - }, - } - if errs := ValidateHasLabel(successCase, field.NewPath("field"), "foo", "bar"); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - missingCase := api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Labels: map[string]string{ - "other": "blah", - }, - } - if errs := ValidateHasLabel(missingCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 { - t.Errorf("expected failure") - } - - wrongValueCase := api.ObjectMeta{ - Name: "123", - Namespace: "ns", - Labels: map[string]string{ - "other": "blah", - "foo": "notbar", - }, - } - if errs := ValidateHasLabel(wrongValueCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 { - t.Errorf("expected failure") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go index 6baef8f91..8903fd3a5 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go @@ -24,8 +24,11 @@ import ( "strings" "github.com/golang/glog" + + "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apimachinery" + "k8s.io/kubernetes/pkg/util/sets" ) var ( @@ -43,8 +46,8 @@ var ( // envRequestedVersions represents the versions requested via the // KUBE_API_VERSIONS environment variable. The install package of each group // checks this list before add their versions to the latest package and - // Scheme. - envRequestedVersions = map[unversioned.GroupVersion]struct{}{} + // Scheme. This list is small and order matters, so represent as a slice + envRequestedVersions = []unversioned.GroupVersion{} ) func init() { @@ -58,7 +61,7 @@ func init() { glog.Fatalf("invalid api version: %s in KUBE_API_VERSIONS: %s.", version, os.Getenv("KUBE_API_VERSIONS")) } - envRequestedVersions[gv] = struct{}{} + envRequestedVersions = append(envRequestedVersions, gv) } } } @@ -104,8 +107,12 @@ func IsAllowedVersion(v unversioned.GroupVersion) bool { if len(envRequestedVersions) == 0 { return true } - _, found := envRequestedVersions[v] - return found + for _, envGV := range envRequestedVersions { + if v == envGV { + return true + } + } + return false } // IsEnabledVersion returns if a version is enabled. @@ -167,6 +174,80 @@ func GroupOrDie(group string) *apimachinery.GroupMeta { return &groupMetaCopy } +// RESTMapper returns a union RESTMapper of all known types with priorities chosen in the following order: +// 1. if KUBE_API_VERSIONS is specified, then KUBE_API_VERSIONS in order, OR +// 1. legacy kube group preferred version, extensions preferred version, metrics perferred version, legacy +// kube any version, extensions any version, metrics any version, all other groups alphabetical preferred version, +// all other groups alphabetical. +func RESTMapper(versionPatterns ...unversioned.GroupVersion) meta.RESTMapper { + unionMapper := meta.MultiRESTMapper{} + for enabledVersion := range enabledVersions { + groupMeta := groupMetaMap[enabledVersion.Group] + unionMapper = append(unionMapper, groupMeta.RESTMapper) + } + + if len(versionPatterns) != 0 { + resourcePriority := []unversioned.GroupVersionResource{} + kindPriority := []unversioned.GroupVersionKind{} + for _, versionPriority := range versionPatterns { + resourcePriority = append(resourcePriority, versionPriority.WithResource(meta.AnyResource)) + kindPriority = append(kindPriority, versionPriority.WithKind(meta.AnyKind)) + } + + return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority} + } + + if len(envRequestedVersions) != 0 { + resourcePriority := []unversioned.GroupVersionResource{} + kindPriority := []unversioned.GroupVersionKind{} + + for _, versionPriority := range envRequestedVersions { + resourcePriority = append(resourcePriority, versionPriority.WithResource(meta.AnyResource)) + kindPriority = append(kindPriority, versionPriority.WithKind(meta.AnyKind)) + } + + return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority} + } + + prioritizedGroups := []string{"", "extensions", "metrics"} + resourcePriority, kindPriority := prioritiesForGroups(prioritizedGroups...) + + prioritizedGroupsSet := sets.NewString(prioritizedGroups...) + remainingGroups := sets.String{} + for enabledVersion := range enabledVersions { + if !prioritizedGroupsSet.Has(enabledVersion.Group) { + remainingGroups.Insert(enabledVersion.Group) + } + } + + remainingResourcePriority, remainingKindPriority := prioritiesForGroups(remainingGroups.List()...) + resourcePriority = append(resourcePriority, remainingResourcePriority...) + kindPriority = append(kindPriority, remainingKindPriority...) + + return meta.PriorityRESTMapper{Delegate: unionMapper, ResourcePriority: resourcePriority, KindPriority: kindPriority} +} + +// prioritiesForGroups returns the resource and kind priorities for a PriorityRESTMapper, preferring the preferred version of each group first, +// then any non-preferred version of the group second. +func prioritiesForGroups(groups ...string) ([]unversioned.GroupVersionResource, []unversioned.GroupVersionKind) { + resourcePriority := []unversioned.GroupVersionResource{} + kindPriority := []unversioned.GroupVersionKind{} + + for _, group := range groups { + availableVersions := EnabledVersionsForGroup(group) + if len(availableVersions) > 0 { + resourcePriority = append(resourcePriority, availableVersions[0].WithResource(meta.AnyResource)) + kindPriority = append(kindPriority, availableVersions[0].WithKind(meta.AnyKind)) + } + } + for _, group := range groups { + resourcePriority = append(resourcePriority, unversioned.GroupVersionResource{Group: group, Version: meta.AnyVersion, Resource: meta.AnyResource}) + kindPriority = append(kindPriority, unversioned.GroupVersionKind{Group: group, Version: meta.AnyVersion, Kind: meta.AnyKind}) + } + + return resourcePriority, kindPriority +} + // AllPreferredGroupVersions returns the preferred versions of all registered // groups in the form of "group1/version1,group2/version2,..." func AllPreferredGroupVersions() string { @@ -185,7 +266,7 @@ func AllPreferredGroupVersions() string { // the KUBE_API_VERSIONS environment variable, but not enabled. func ValidateEnvRequestedVersions() []unversioned.GroupVersion { var missingVersions []unversioned.GroupVersion - for v := range envRequestedVersions { + for _, v := range envRequestedVersions { if _, found := enabledVersions[v]; !found { missingVersions = append(missingVersions, v) } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apimachinery/registered/registered_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apimachinery/registered/registered_test.go deleted file mode 100644 index e7466fcc2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apimachinery/registered/registered_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package registered - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apimachinery" -) - -func TestAllPreferredGroupVersions(t *testing.T) { - testCases := []struct { - groupMetas []apimachinery.GroupMeta - expect string - }{ - { - groupMetas: []apimachinery.GroupMeta{ - { - GroupVersion: unversioned.GroupVersion{"group1", "v1"}, - }, - { - GroupVersion: unversioned.GroupVersion{"group2", "v2"}, - }, - { - GroupVersion: unversioned.GroupVersion{"", "v1"}, - }, - }, - expect: "group1/v1,group2/v2,v1", - }, - { - groupMetas: []apimachinery.GroupMeta{ - { - GroupVersion: unversioned.GroupVersion{"", "v1"}, - }, - }, - expect: "v1", - }, - { - groupMetas: []apimachinery.GroupMeta{}, - expect: "", - }, - } - for _, testCase := range testCases { - for _, groupMeta := range testCase.groupMetas { - RegisterGroup(groupMeta) - } - output := AllPreferredGroupVersions() - if testCase.expect != output { - t.Errorf("Error. expect: %s, got: %s", testCase.expect, output) - } - reset() - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go index 681e962ed..d9910ef14 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go @@ -16,7 +16,7 @@ limitations under the License. package v1beta1 -// This file contains a collection of methods that can be used from go-resful to +// 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 // diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/validation/validation.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/validation/validation.go deleted file mode 100644 index 11a548f41..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/validation/validation.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package validation - -import ( - authorizationapi "k8s.io/kubernetes/pkg/apis/authorization" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -func ValidateSubjectAccessReviewSpec(spec authorizationapi.SubjectAccessReviewSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if spec.ResourceAttributes != nil && spec.NonResourceAttributes != nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("nonResourceAttributes"), spec.NonResourceAttributes, `cannot be specified in combination with resourceAttributes`)) - } - if spec.ResourceAttributes == nil && spec.NonResourceAttributes == nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("resourceAttributes"), spec.NonResourceAttributes, `exactly one of nonResourceAttributes or resourceAttributes must be specified`)) - } - if len(spec.User) == 0 && len(spec.Groups) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("user"), spec.User, `at least one of user or group must be specified`)) - } - - return allErrs -} - -func ValidateSelfSubjectAccessReviewSpec(spec authorizationapi.SelfSubjectAccessReviewSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if spec.ResourceAttributes != nil && spec.NonResourceAttributes != nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("nonResourceAttributes"), spec.NonResourceAttributes, `cannot be specified in combination with resourceAttributes`)) - } - if spec.ResourceAttributes == nil && spec.NonResourceAttributes == nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("resourceAttributes"), spec.NonResourceAttributes, `exactly one of nonResourceAttributes or resourceAttributes must be specified`)) - } - - return allErrs -} - -func ValidateSubjectAccessReview(sar *authorizationapi.SubjectAccessReview) field.ErrorList { - allErrs := ValidateSubjectAccessReviewSpec(sar.Spec, field.NewPath("spec")) - return allErrs -} - -func ValidateSelfSubjectAccessReview(sar *authorizationapi.SelfSubjectAccessReview) field.ErrorList { - allErrs := ValidateSelfSubjectAccessReviewSpec(sar.Spec, field.NewPath("spec")) - return allErrs -} - -func ValidateLocalSubjectAccessReview(sar *authorizationapi.LocalSubjectAccessReview) field.ErrorList { - allErrs := ValidateSubjectAccessReviewSpec(sar.Spec, field.NewPath("spec")) - return allErrs -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/validation/validation_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/validation/validation_test.go deleted file mode 100644 index c2776c404..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/authorization/validation/validation_test.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package validation - -import ( - "strings" - "testing" - - authorizationapi "k8s.io/kubernetes/pkg/apis/authorization" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -func TestValidateSARSpec(t *testing.T) { - successCases := []authorizationapi.SubjectAccessReviewSpec{ - {ResourceAttributes: &authorizationapi.ResourceAttributes{}, User: "me"}, - {NonResourceAttributes: &authorizationapi.NonResourceAttributes{}, Groups: []string{"my-group"}}, - } - for _, successCase := range successCases { - if errs := ValidateSubjectAccessReviewSpec(successCase, field.NewPath("spec")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []struct { - name string - obj authorizationapi.SubjectAccessReviewSpec - msg string - }{ - { - name: "neither request", - obj: authorizationapi.SubjectAccessReviewSpec{User: "me"}, - msg: "exactly one of nonResourceAttributes or resourceAttributes must be specified", - }, - { - name: "both requests", - obj: authorizationapi.SubjectAccessReviewSpec{ - ResourceAttributes: &authorizationapi.ResourceAttributes{}, - NonResourceAttributes: &authorizationapi.NonResourceAttributes{}, - User: "me", - }, - msg: "cannot be specified in combination with resourceAttributes", - }, - { - name: "no subject", - obj: authorizationapi.SubjectAccessReviewSpec{ - ResourceAttributes: &authorizationapi.ResourceAttributes{}, - }, - msg: `spec.user: Invalid value: "": at least one of user or group must be specified`, - }, - } - - for _, c := range errorCases { - errs := ValidateSubjectAccessReviewSpec(c.obj, field.NewPath("spec")) - if len(errs) == 0 { - t.Errorf("%s: expected failure for %q", c.name, c.msg) - } else if !strings.Contains(errs[0].Error(), c.msg) { - t.Errorf("%s: unexpected error: %q, expected: %q", c.name, errs[0], c.msg) - } - - errs = ValidateSubjectAccessReview(&authorizationapi.SubjectAccessReview{Spec: c.obj}) - if len(errs) == 0 { - t.Errorf("%s: expected failure for %q", c.name, c.msg) - } else if !strings.Contains(errs[0].Error(), c.msg) { - t.Errorf("%s: unexpected error: %q, expected: %q", c.name, errs[0], c.msg) - } - errs = ValidateLocalSubjectAccessReview(&authorizationapi.LocalSubjectAccessReview{Spec: c.obj}) - if len(errs) == 0 { - t.Errorf("%s: expected failure for %q", c.name, c.msg) - } else if !strings.Contains(errs[0].Error(), c.msg) { - t.Errorf("%s: unexpected error: %q, expected: %q", c.name, errs[0], c.msg) - } - - } -} - -func TestValidateSelfSAR(t *testing.T) { - successCases := []authorizationapi.SelfSubjectAccessReviewSpec{ - {ResourceAttributes: &authorizationapi.ResourceAttributes{}}, - } - for _, successCase := range successCases { - if errs := ValidateSelfSubjectAccessReviewSpec(successCase, field.NewPath("spec")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []struct { - name string - obj authorizationapi.SelfSubjectAccessReviewSpec - msg string - }{ - { - name: "neither request", - obj: authorizationapi.SelfSubjectAccessReviewSpec{}, - msg: "exactly one of nonResourceAttributes or resourceAttributes must be specified", - }, - { - name: "both requests", - obj: authorizationapi.SelfSubjectAccessReviewSpec{ - ResourceAttributes: &authorizationapi.ResourceAttributes{}, - NonResourceAttributes: &authorizationapi.NonResourceAttributes{}, - }, - msg: "cannot be specified in combination with resourceAttributes", - }, - } - - for _, c := range errorCases { - errs := ValidateSelfSubjectAccessReviewSpec(c.obj, field.NewPath("spec")) - if len(errs) == 0 { - t.Errorf("%s: expected failure for %q", c.name, c.msg) - } else if !strings.Contains(errs[0].Error(), c.msg) { - t.Errorf("%s: unexpected error: %q, expected: %q", c.name, errs[0], c.msg) - } - - errs = ValidateSelfSubjectAccessReview(&authorizationapi.SelfSubjectAccessReview{Spec: c.obj}) - if len(errs) == 0 { - t.Errorf("%s: expected failure for %q", c.name, c.msg) - } else if !strings.Contains(errs[0].Error(), c.msg) { - t.Errorf("%s: unexpected error: %q, expected: %q", c.name, errs[0], c.msg) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/register.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/register.go index 519e8f6be..dfc86f24d 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/register.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/register.go @@ -47,8 +47,11 @@ func AddToScheme(scheme *runtime.Scheme) { // Adds the list of known types to api.Scheme. func addKnownTypes(scheme *runtime.Scheme) { scheme.AddKnownTypes(SchemeGroupVersion, + &Scale{}, &extensions.HorizontalPodAutoscaler{}, &extensions.HorizontalPodAutoscalerList{}, &api.ListOptions{}, ) } + +func (obj *Scale) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/types.generated.go new file mode 100644 index 000000000..7302ebca6 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/types.generated.go @@ -0,0 +1,794 @@ +/* +Copyright 2015 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. +*/ + +// ************************************************************ +// DO NOT EDIT. +// THIS FILE IS AUTO-GENERATED BY codecgen. +// ************************************************************ + +package autoscaling + +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 *Scale) 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 *Scale) 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 *Scale) 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 = ScaleSpec{} + } else { + yyv5 := &x.Spec + yyv5.CodecDecodeSelf(d) + } + case "status": + if r.TryDecodeAsNil() { + x.Status = ScaleStatus{} + } 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 *Scale) 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 = ScaleSpec{} + } 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 = ScaleStatus{} + } 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 *ScaleSpec) 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.Replicas != 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] { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("replicas")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *ScaleSpec) 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 *ScaleSpec) 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 "replicas": + if r.TryDecodeAsNil() { + x.Replicas = 0 + } else { + x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *ScaleSpec) 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() { + x.Replicas = 0 + } else { + x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) + } + 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 *ScaleStatus) 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[1] = x.Selector != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("replicas")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Selector)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("selector")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Selector)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *ScaleStatus) 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 *ScaleStatus) 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 "replicas": + if r.TryDecodeAsNil() { + x.Replicas = 0 + } else { + x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) + } + case "selector": + if r.TryDecodeAsNil() { + x.Selector = "" + } else { + x.Selector = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *ScaleStatus) 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.Replicas = 0 + } else { + x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) + } + 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.Selector = "" + } else { + x.Selector = string(r.DecodeString()) + } + 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) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/types.go new file mode 100644 index 000000000..99080a8a6 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/types.go @@ -0,0 +1,53 @@ +/* +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. +*/ + +package autoscaling + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/unversioned" +) + +// 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.2/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.2/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.2/docs/devel/api-conventions.md#spec-and-status. Read-only. + Status ScaleStatus `json:"status,omitempty"` +} + +// ScaleSpec describes the attributes of a scale subresource. +type ScaleSpec struct { + // desired number of instances for the scaled object. + Replicas int `json:"replicas,omitempty"` +} + +// ScaleStatus represents the current status of a scale subresource. +type ScaleStatus struct { + // actual number of observed instances of the scaled object. + Replicas int `json:"replicas"` + + // 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.2/docs/user-guide/labels.md#label-selectors + Selector string `json:"selector,omitempty"` +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/conversion_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/conversion_generated.go index 40eed3525..f55d38fd9 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/conversion_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/conversion_generated.go @@ -24,6 +24,7 @@ import ( api "k8s.io/kubernetes/pkg/api" unversioned "k8s.io/kubernetes/pkg/api/unversioned" v1 "k8s.io/kubernetes/pkg/api/v1" + autoscaling "k8s.io/kubernetes/pkg/apis/autoscaling" extensions "k8s.io/kubernetes/pkg/apis/extensions" conversion "k8s.io/kubernetes/pkg/conversion" ) @@ -132,6 +133,54 @@ func Convert_v1_ObjectMeta_To_api_ObjectMeta(in *v1.ObjectMeta, out *api.ObjectM return autoConvert_v1_ObjectMeta_To_api_ObjectMeta(in, out, s) } +func autoConvert_autoscaling_Scale_To_v1_Scale(in *autoscaling.Scale, out *Scale, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*autoscaling.Scale))(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_autoscaling_ScaleSpec_To_v1_ScaleSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_autoscaling_ScaleStatus_To_v1_ScaleStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_autoscaling_Scale_To_v1_Scale(in *autoscaling.Scale, out *Scale, s conversion.Scope) error { + return autoConvert_autoscaling_Scale_To_v1_Scale(in, out, s) +} + +func autoConvert_autoscaling_ScaleSpec_To_v1_ScaleSpec(in *autoscaling.ScaleSpec, out *ScaleSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*autoscaling.ScaleSpec))(in) + } + out.Replicas = int32(in.Replicas) + return nil +} + +func Convert_autoscaling_ScaleSpec_To_v1_ScaleSpec(in *autoscaling.ScaleSpec, out *ScaleSpec, s conversion.Scope) error { + return autoConvert_autoscaling_ScaleSpec_To_v1_ScaleSpec(in, out, s) +} + +func autoConvert_autoscaling_ScaleStatus_To_v1_ScaleStatus(in *autoscaling.ScaleStatus, out *ScaleStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*autoscaling.ScaleStatus))(in) + } + out.Replicas = int32(in.Replicas) + out.Selector = in.Selector + return nil +} + +func Convert_autoscaling_ScaleStatus_To_v1_ScaleStatus(in *autoscaling.ScaleStatus, out *ScaleStatus, s conversion.Scope) error { + return autoConvert_autoscaling_ScaleStatus_To_v1_ScaleStatus(in, out, s) +} + func autoConvert_v1_HorizontalPodAutoscaler_To_extensions_HorizontalPodAutoscaler(in *HorizontalPodAutoscaler, out *extensions.HorizontalPodAutoscaler, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*HorizontalPodAutoscaler))(in) @@ -232,6 +281,54 @@ func Convert_v1_HorizontalPodAutoscalerStatus_To_extensions_HorizontalPodAutosca return autoConvert_v1_HorizontalPodAutoscalerStatus_To_extensions_HorizontalPodAutoscalerStatus(in, out, s) } +func autoConvert_v1_Scale_To_autoscaling_Scale(in *Scale, out *autoscaling.Scale, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*Scale))(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_ScaleSpec_To_autoscaling_ScaleSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1_ScaleStatus_To_autoscaling_ScaleStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_v1_Scale_To_autoscaling_Scale(in *Scale, out *autoscaling.Scale, s conversion.Scope) error { + return autoConvert_v1_Scale_To_autoscaling_Scale(in, out, s) +} + +func autoConvert_v1_ScaleSpec_To_autoscaling_ScaleSpec(in *ScaleSpec, out *autoscaling.ScaleSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*ScaleSpec))(in) + } + out.Replicas = int(in.Replicas) + return nil +} + +func Convert_v1_ScaleSpec_To_autoscaling_ScaleSpec(in *ScaleSpec, out *autoscaling.ScaleSpec, s conversion.Scope) error { + return autoConvert_v1_ScaleSpec_To_autoscaling_ScaleSpec(in, out, s) +} + +func autoConvert_v1_ScaleStatus_To_autoscaling_ScaleStatus(in *ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*ScaleStatus))(in) + } + out.Replicas = int(in.Replicas) + out.Selector = in.Selector + return nil +} + +func Convert_v1_ScaleStatus_To_autoscaling_ScaleStatus(in *ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error { + return autoConvert_v1_ScaleStatus_To_autoscaling_ScaleStatus(in, out, s) +} + func autoConvert_extensions_HorizontalPodAutoscaler_To_v1_HorizontalPodAutoscaler(in *extensions.HorizontalPodAutoscaler, out *HorizontalPodAutoscaler, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.HorizontalPodAutoscaler))(in) @@ -335,6 +432,9 @@ func Convert_extensions_HorizontalPodAutoscalerStatus_To_v1_HorizontalPodAutosca func init() { err := api.Scheme.AddGeneratedConversionFuncs( autoConvert_api_ObjectMeta_To_v1_ObjectMeta, + autoConvert_autoscaling_ScaleSpec_To_v1_ScaleSpec, + autoConvert_autoscaling_ScaleStatus_To_v1_ScaleStatus, + autoConvert_autoscaling_Scale_To_v1_Scale, autoConvert_extensions_HorizontalPodAutoscalerList_To_v1_HorizontalPodAutoscalerList, autoConvert_extensions_HorizontalPodAutoscalerSpec_To_v1_HorizontalPodAutoscalerSpec, autoConvert_extensions_HorizontalPodAutoscalerStatus_To_v1_HorizontalPodAutoscalerStatus, @@ -344,6 +444,9 @@ func init() { autoConvert_v1_HorizontalPodAutoscalerStatus_To_extensions_HorizontalPodAutoscalerStatus, autoConvert_v1_HorizontalPodAutoscaler_To_extensions_HorizontalPodAutoscaler, autoConvert_v1_ObjectMeta_To_api_ObjectMeta, + autoConvert_v1_ScaleSpec_To_autoscaling_ScaleSpec, + autoConvert_v1_ScaleStatus_To_autoscaling_ScaleStatus, + autoConvert_v1_Scale_To_autoscaling_Scale, ) if err != nil { // If one of the conversion functions is malformed, detect it immediately. diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/deep_copy_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/deep_copy_generated.go index e2c8d6fb4..a71749abb 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/deep_copy_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/deep_copy_generated.go @@ -181,6 +181,33 @@ func deepCopy_v1_HorizontalPodAutoscalerStatus(in HorizontalPodAutoscalerStatus, return nil } +func deepCopy_v1_Scale(in Scale, out *Scale, c *conversion.Cloner) error { + if err := 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_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 +} + func init() { err := api.Scheme.AddGeneratedDeepCopyFuncs( deepCopy_unversioned_ListMeta, @@ -192,6 +219,9 @@ func init() { deepCopy_v1_HorizontalPodAutoscalerList, deepCopy_v1_HorizontalPodAutoscalerSpec, deepCopy_v1_HorizontalPodAutoscalerStatus, + deepCopy_v1_Scale, + deepCopy_v1_ScaleSpec, + deepCopy_v1_ScaleStatus, ) if err != nil { // if one of the deep copy functions is malformed, detect it immediately. diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go index 1209a4f9b..5af7611c5 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go @@ -39,9 +39,11 @@ func addKnownTypes(scheme *runtime.Scheme) { scheme.AddKnownTypes(SchemeGroupVersion, &HorizontalPodAutoscaler{}, &HorizontalPodAutoscalerList{}, + &Scale{}, &v1.ListOptions{}, ) } func (obj *HorizontalPodAutoscaler) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *HorizontalPodAutoscalerList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *Scale) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go index 43d2dbc5a..1e5a195c2 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go @@ -1817,6 +1817,728 @@ func (x *HorizontalPodAutoscalerList) codecDecodeSelfFromArray(l int, d *codec19 z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } +func (x *Scale) 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 *Scale) 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 *Scale) 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 = ScaleSpec{} + } else { + yyv5 := &x.Spec + yyv5.CodecDecodeSelf(d) + } + case "status": + if r.TryDecodeAsNil() { + x.Status = ScaleStatus{} + } 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 *Scale) 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 = ScaleSpec{} + } 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 = ScaleStatus{} + } 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 *ScaleSpec) 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.Replicas != 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] { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("replicas")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *ScaleSpec) 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 *ScaleSpec) 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 "replicas": + if r.TryDecodeAsNil() { + x.Replicas = 0 + } else { + x.Replicas = int32(r.DecodeInt(32)) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *ScaleSpec) 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() { + x.Replicas = 0 + } else { + x.Replicas = int32(r.DecodeInt(32)) + } + 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 *ScaleStatus) 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[1] = x.Selector != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("replicas")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeInt(int64(x.Replicas)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Selector)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("selector")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Selector)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *ScaleStatus) 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 *ScaleStatus) 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 "replicas": + if r.TryDecodeAsNil() { + x.Replicas = 0 + } else { + x.Replicas = int32(r.DecodeInt(32)) + } + case "selector": + if r.TryDecodeAsNil() { + x.Selector = "" + } else { + x.Selector = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *ScaleStatus) 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.Replicas = 0 + } else { + x.Replicas = int32(r.DecodeInt(32)) + } + 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.Selector = "" + } else { + x.Selector = string(r.DecodeString()) + } + 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 codecSelfer1234) encSliceHorizontalPodAutoscaler(v []HorizontalPodAutoscaler, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go index 6ad1d61af..20b96728d 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go @@ -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/HEAD/docs/devel/api-conventions.md#types-kinds" + // Kind of the referent; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds" Kind string `json:"kind"` - // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names Name string `json:"name"` // API version of the referent APIVersion string `json:"apiVersion,omitempty"` @@ -41,6 +41,7 @@ type HorizontalPodAutoscalerSpec struct { // upper limit for the number of pods that can be set by the autoscaler; cannot be smaller than MinReplicas. MaxReplicas int32 `json:"maxReplicas"` // target average CPU utilization (represented as a percentage of requested CPU) over all the pods; + // if not specified the default autoscaling policy will be used. TargetCPUUtilizationPercentage *int32 `json:"targetCPUUtilizationPercentage,omitempty"` } @@ -67,10 +68,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/HEAD/docs/devel/api-conventions.md#metadata + // Standard object metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty"` - // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Spec HorizontalPodAutoscalerSpec `json:"spec,omitempty"` // current information about the autoscaler. @@ -86,3 +87,34 @@ type HorizontalPodAutoscalerList struct { // list of horizontal pod autoscaler objects. Items []HorizontalPodAutoscaler `json:"items"` } + +// 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.2/docs/devel/api-conventions.md#metadata. + v1.ObjectMeta `json:"metadata,omitempty"` + + // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status. Read-only. + Status ScaleStatus `json:"status,omitempty"` +} + +// ScaleSpec describes the attributes of a scale subresource. +type ScaleSpec struct { + // desired number of instances for the scaled object. + Replicas int32 `json:"replicas,omitempty"` +} + +// ScaleStatus represents the current status of a scale subresource. +type ScaleStatus struct { + // actual number of observed instances of the scaled object. + Replicas int32 `json:"replicas"` + + // 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.2/docs/user-guide/labels.md#label-selectors + Selector string `json:"selector,omitempty"` +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go index ccec779f2..537dafba4 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go @@ -16,7 +16,7 @@ limitations under the License. package v1 -// This file contains a collection of methods that can be used from go-resful to +// 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 // @@ -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/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", + "kind": "Kind of the referent; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds\"", + "name": "Name of the referent; More info: http://releases.k8s.io/release-1.2/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/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.", + "metadata": "Standard object metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "behaviour of autoscaler. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status.", "status": "current information about the autoscaler.", } @@ -64,7 +64,7 @@ var map_HorizontalPodAutoscalerSpec = map[string]string{ "scaleTargetRef": "reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption and will set the desired number of pods by using its Scale subresource.", "minReplicas": "lower limit for the number of pods that can be set by the autoscaler, default 1.", "maxReplicas": "upper limit for the number of pods that can be set by the autoscaler; cannot be smaller than MinReplicas.", - "targetCPUUtilizationPercentage": "target average CPU utilization (represented as a percentage of requested CPU) over all the pods;", + "targetCPUUtilizationPercentage": "target average CPU utilization (represented as a percentage of requested CPU) over all the pods; if not specified the default autoscaling policy will be used.", } func (HorizontalPodAutoscalerSpec) SwaggerDoc() map[string]string { @@ -84,4 +84,34 @@ func (HorizontalPodAutoscalerStatus) SwaggerDoc() map[string]string { return map_HorizontalPodAutoscalerStatus } +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.2/docs/devel/api-conventions.md#metadata.", + "spec": "defines the behavior of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status.", + "status": "current status of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Read-only.", +} + +func (Scale) SwaggerDoc() map[string]string { + return map_Scale +} + +var map_ScaleSpec = map[string]string{ + "": "ScaleSpec describes the attributes of a scale subresource.", + "replicas": "desired number of instances for the scaled object.", +} + +func (ScaleSpec) SwaggerDoc() map[string]string { + return map_ScaleSpec +} + +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.2/docs/user-guide/labels.md#label-selectors", +} + +func (ScaleStatus) SwaggerDoc() map[string]string { + return map_ScaleStatus +} + // AUTO-GENERATED FUNCTIONS END HERE diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/term.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/deep_copy_generated.go similarity index 64% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/term.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/deep_copy_generated.go index 9db85fe4b..55d346a61 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/term.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/deep_copy_generated.go @@ -1,5 +1,3 @@ -// +build !windows - /* Copyright 2015 The Kubernetes Authors All rights reserved. @@ -16,12 +14,16 @@ See the License for the specific language governing permissions and limitations under the License. */ -package editor +// DO NOT EDIT. THIS FILE IS AUTO-GENERATED BY $KUBEROOT/hack/update-generated-deep-copies.sh. -import ( - "os" - "syscall" -) +package batch -// childSignals are the allowed signals that can be sent to children in Unix variant OS's -var childSignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT} +import api "k8s.io/kubernetes/pkg/api" + +func init() { + err := api.Scheme.AddGeneratedDeepCopyFuncs() + if err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/install/install.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/install/install.go new file mode 100644 index 000000000..830020a93 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/install/install.go @@ -0,0 +1,129 @@ +/* +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. +*/ + +// Package install installs the batch 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/batch" + "k8s.io/kubernetes/pkg/apis/batch/v1" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/util/sets" +) + +const importPrefix = "k8s.io/kubernetes/pkg/apis/batch" + +var accessor = meta.NewAccessor() + +// availableVersions lists all known external versions for this group from most preferred to least preferred +var availableVersions = []unversioned.GroupVersion{v1.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", batch.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 there. +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() + + 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 v1.SchemeGroupVersion: + return &meta.VersionInterfaces{ + ObjectConvertor: api.Scheme, + MetadataAccessor: accessor, + }, nil + default: + g, _ := registered.Group(batch.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 + batch.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 v1.SchemeGroupVersion: + v1.AddToScheme(api.Scheme) + } + } +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/register.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/register.go new file mode 100644 index 000000000..a302fe751 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/register.go @@ -0,0 +1,54 @@ +/* +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. +*/ + +package batch + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/runtime" +) + +// GroupName is the group name use in this package +const GroupName = "batch" + +// 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, + &extensions.Job{}, + &extensions.JobList{}, + &api.ListOptions{}, + ) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/conversion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/conversion.go new file mode 100644 index 000000000..c1a77ee8e --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/conversion.go @@ -0,0 +1,63 @@ +/* +Copyright 2015 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. +*/ + +package v1 + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api" + v1 "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/conversion" + "k8s.io/kubernetes/pkg/runtime" +) + +func addConversionFuncs(scheme *runtime.Scheme) { + // Add non-generated conversion functions + err := scheme.AddConversionFuncs( + Convert_api_PodSpec_To_v1_PodSpec, + Convert_v1_PodSpec_To_api_PodSpec, + ) + if err != nil { + // If one of the conversion functions is malformed, detect it immediately. + panic(err) + } + + err = api.Scheme.AddFieldLabelConversionFunc("batch/v1", "Job", + func(label, value string) (string, string, error) { + switch label { + case "metadata.name", "metadata.namespace", "status.successful": + return label, value, nil + default: + return "", "", fmt.Errorf("field label not supported: %s", label) + } + }) + if err != nil { + // If one of the conversion functions is malformed, detect it immediately. + panic(err) + } +} + +// The following two PodSpec conversions functions where copied from pkg/api/conversion.go +// for the generated functions to work properly. +// This should be fixed: https://github.com/kubernetes/kubernetes/issues/12977 +func Convert_api_PodSpec_To_v1_PodSpec(in *api.PodSpec, out *v1.PodSpec, s conversion.Scope) error { + return v1.Convert_api_PodSpec_To_v1_PodSpec(in, out, s) +} + +func Convert_v1_PodSpec_To_api_PodSpec(in *v1.PodSpec, out *api.PodSpec, s conversion.Scope) error { + return v1.Convert_v1_PodSpec_To_api_PodSpec(in, out, s) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/conversion_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/conversion_generated.go new file mode 100644 index 000000000..9a7b4876f --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/conversion_generated.go @@ -0,0 +1,3065 @@ +/* +Copyright 2015 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. +*/ + +// DO NOT EDIT. THIS FILE IS AUTO-GENERATED BY $KUBEROOT/hack/update-generated-conversions.sh + +package v1 + +import ( + reflect "reflect" + + 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" + extensions "k8s.io/kubernetes/pkg/apis/extensions" + conversion "k8s.io/kubernetes/pkg/conversion" +) + +func autoConvert_api_AWSElasticBlockStoreVolumeSource_To_v1_AWSElasticBlockStoreVolumeSource(in *api.AWSElasticBlockStoreVolumeSource, out *v1.AWSElasticBlockStoreVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.AWSElasticBlockStoreVolumeSource))(in) + } + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.Partition = int32(in.Partition) + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_AWSElasticBlockStoreVolumeSource_To_v1_AWSElasticBlockStoreVolumeSource(in *api.AWSElasticBlockStoreVolumeSource, out *v1.AWSElasticBlockStoreVolumeSource, s conversion.Scope) error { + return autoConvert_api_AWSElasticBlockStoreVolumeSource_To_v1_AWSElasticBlockStoreVolumeSource(in, out, s) +} + +func autoConvert_api_AzureFileVolumeSource_To_v1_AzureFileVolumeSource(in *api.AzureFileVolumeSource, out *v1.AzureFileVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.AzureFileVolumeSource))(in) + } + out.SecretName = in.SecretName + out.ShareName = in.ShareName + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_AzureFileVolumeSource_To_v1_AzureFileVolumeSource(in *api.AzureFileVolumeSource, out *v1.AzureFileVolumeSource, s conversion.Scope) error { + return autoConvert_api_AzureFileVolumeSource_To_v1_AzureFileVolumeSource(in, out, s) +} + +func autoConvert_api_Capabilities_To_v1_Capabilities(in *api.Capabilities, out *v1.Capabilities, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.Capabilities))(in) + } + if in.Add != nil { + out.Add = make([]v1.Capability, len(in.Add)) + for i := range in.Add { + out.Add[i] = v1.Capability(in.Add[i]) + } + } else { + out.Add = nil + } + if in.Drop != nil { + out.Drop = make([]v1.Capability, len(in.Drop)) + for i := range in.Drop { + out.Drop[i] = v1.Capability(in.Drop[i]) + } + } else { + out.Drop = nil + } + return nil +} + +func Convert_api_Capabilities_To_v1_Capabilities(in *api.Capabilities, out *v1.Capabilities, s conversion.Scope) error { + return autoConvert_api_Capabilities_To_v1_Capabilities(in, out, s) +} + +func autoConvert_api_CephFSVolumeSource_To_v1_CephFSVolumeSource(in *api.CephFSVolumeSource, out *v1.CephFSVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.CephFSVolumeSource))(in) + } + if in.Monitors != nil { + out.Monitors = make([]string, len(in.Monitors)) + for i := range in.Monitors { + out.Monitors[i] = in.Monitors[i] + } + } else { + out.Monitors = nil + } + out.Path = in.Path + out.User = in.User + out.SecretFile = in.SecretFile + // unable to generate simple pointer conversion for api.LocalObjectReference -> v1.LocalObjectReference + if in.SecretRef != nil { + out.SecretRef = new(v1.LocalObjectReference) + if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(in.SecretRef, out.SecretRef, s); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_CephFSVolumeSource_To_v1_CephFSVolumeSource(in *api.CephFSVolumeSource, out *v1.CephFSVolumeSource, s conversion.Scope) error { + return autoConvert_api_CephFSVolumeSource_To_v1_CephFSVolumeSource(in, out, s) +} + +func autoConvert_api_CinderVolumeSource_To_v1_CinderVolumeSource(in *api.CinderVolumeSource, out *v1.CinderVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.CinderVolumeSource))(in) + } + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_CinderVolumeSource_To_v1_CinderVolumeSource(in *api.CinderVolumeSource, out *v1.CinderVolumeSource, s conversion.Scope) error { + return autoConvert_api_CinderVolumeSource_To_v1_CinderVolumeSource(in, out, s) +} + +func autoConvert_api_ConfigMapKeySelector_To_v1_ConfigMapKeySelector(in *api.ConfigMapKeySelector, out *v1.ConfigMapKeySelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ConfigMapKeySelector))(in) + } + if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(&in.LocalObjectReference, &out.LocalObjectReference, s); err != nil { + return err + } + out.Key = in.Key + return nil +} + +func Convert_api_ConfigMapKeySelector_To_v1_ConfigMapKeySelector(in *api.ConfigMapKeySelector, out *v1.ConfigMapKeySelector, s conversion.Scope) error { + return autoConvert_api_ConfigMapKeySelector_To_v1_ConfigMapKeySelector(in, out, s) +} + +func autoConvert_api_ConfigMapVolumeSource_To_v1_ConfigMapVolumeSource(in *api.ConfigMapVolumeSource, out *v1.ConfigMapVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ConfigMapVolumeSource))(in) + } + if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(&in.LocalObjectReference, &out.LocalObjectReference, s); err != nil { + return err + } + if in.Items != nil { + out.Items = make([]v1.KeyToPath, len(in.Items)) + for i := range in.Items { + if err := Convert_api_KeyToPath_To_v1_KeyToPath(&in.Items[i], &out.Items[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_api_ConfigMapVolumeSource_To_v1_ConfigMapVolumeSource(in *api.ConfigMapVolumeSource, out *v1.ConfigMapVolumeSource, s conversion.Scope) error { + return autoConvert_api_ConfigMapVolumeSource_To_v1_ConfigMapVolumeSource(in, out, s) +} + +func autoConvert_api_Container_To_v1_Container(in *api.Container, out *v1.Container, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.Container))(in) + } + out.Name = in.Name + out.Image = in.Image + if in.Command != nil { + out.Command = make([]string, len(in.Command)) + for i := range in.Command { + out.Command[i] = in.Command[i] + } + } else { + out.Command = nil + } + if in.Args != nil { + out.Args = make([]string, len(in.Args)) + for i := range in.Args { + out.Args[i] = in.Args[i] + } + } else { + out.Args = nil + } + out.WorkingDir = in.WorkingDir + if in.Ports != nil { + out.Ports = make([]v1.ContainerPort, len(in.Ports)) + for i := range in.Ports { + if err := Convert_api_ContainerPort_To_v1_ContainerPort(&in.Ports[i], &out.Ports[i], s); err != nil { + return err + } + } + } else { + out.Ports = nil + } + if in.Env != nil { + out.Env = make([]v1.EnvVar, len(in.Env)) + for i := range in.Env { + if err := Convert_api_EnvVar_To_v1_EnvVar(&in.Env[i], &out.Env[i], s); err != nil { + return err + } + } + } else { + out.Env = nil + } + if err := Convert_api_ResourceRequirements_To_v1_ResourceRequirements(&in.Resources, &out.Resources, s); err != nil { + return err + } + if in.VolumeMounts != nil { + out.VolumeMounts = make([]v1.VolumeMount, len(in.VolumeMounts)) + for i := range in.VolumeMounts { + if err := Convert_api_VolumeMount_To_v1_VolumeMount(&in.VolumeMounts[i], &out.VolumeMounts[i], s); err != nil { + return err + } + } + } else { + out.VolumeMounts = nil + } + // unable to generate simple pointer conversion for api.Probe -> v1.Probe + if in.LivenessProbe != nil { + out.LivenessProbe = new(v1.Probe) + if err := Convert_api_Probe_To_v1_Probe(in.LivenessProbe, out.LivenessProbe, s); err != nil { + return err + } + } else { + out.LivenessProbe = nil + } + // unable to generate simple pointer conversion for api.Probe -> v1.Probe + if in.ReadinessProbe != nil { + out.ReadinessProbe = new(v1.Probe) + if err := Convert_api_Probe_To_v1_Probe(in.ReadinessProbe, out.ReadinessProbe, s); err != nil { + return err + } + } else { + out.ReadinessProbe = nil + } + // unable to generate simple pointer conversion for api.Lifecycle -> v1.Lifecycle + if in.Lifecycle != nil { + out.Lifecycle = new(v1.Lifecycle) + if err := Convert_api_Lifecycle_To_v1_Lifecycle(in.Lifecycle, out.Lifecycle, s); err != nil { + return err + } + } else { + out.Lifecycle = nil + } + out.TerminationMessagePath = in.TerminationMessagePath + out.ImagePullPolicy = v1.PullPolicy(in.ImagePullPolicy) + // unable to generate simple pointer conversion for api.SecurityContext -> v1.SecurityContext + if in.SecurityContext != nil { + out.SecurityContext = new(v1.SecurityContext) + if err := Convert_api_SecurityContext_To_v1_SecurityContext(in.SecurityContext, out.SecurityContext, s); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + out.Stdin = in.Stdin + out.StdinOnce = in.StdinOnce + out.TTY = in.TTY + return nil +} + +func Convert_api_Container_To_v1_Container(in *api.Container, out *v1.Container, s conversion.Scope) error { + return autoConvert_api_Container_To_v1_Container(in, out, s) +} + +func autoConvert_api_ContainerPort_To_v1_ContainerPort(in *api.ContainerPort, out *v1.ContainerPort, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ContainerPort))(in) + } + out.Name = in.Name + out.HostPort = int32(in.HostPort) + out.ContainerPort = int32(in.ContainerPort) + out.Protocol = v1.Protocol(in.Protocol) + out.HostIP = in.HostIP + return nil +} + +func Convert_api_ContainerPort_To_v1_ContainerPort(in *api.ContainerPort, out *v1.ContainerPort, s conversion.Scope) error { + return autoConvert_api_ContainerPort_To_v1_ContainerPort(in, out, s) +} + +func autoConvert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(in *api.DownwardAPIVolumeFile, out *v1.DownwardAPIVolumeFile, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.DownwardAPIVolumeFile))(in) + } + out.Path = in.Path + if err := Convert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil { + return err + } + return nil +} + +func Convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(in *api.DownwardAPIVolumeFile, out *v1.DownwardAPIVolumeFile, s conversion.Scope) error { + return autoConvert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(in, out, s) +} + +func autoConvert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in *api.DownwardAPIVolumeSource, out *v1.DownwardAPIVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.DownwardAPIVolumeSource))(in) + } + if in.Items != nil { + out.Items = make([]v1.DownwardAPIVolumeFile, len(in.Items)) + for i := range in.Items { + if err := Convert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile(&in.Items[i], &out.Items[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in *api.DownwardAPIVolumeSource, out *v1.DownwardAPIVolumeSource, s conversion.Scope) error { + return autoConvert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in, out, s) +} + +func autoConvert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in *api.EmptyDirVolumeSource, out *v1.EmptyDirVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.EmptyDirVolumeSource))(in) + } + out.Medium = v1.StorageMedium(in.Medium) + return nil +} + +func Convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in *api.EmptyDirVolumeSource, out *v1.EmptyDirVolumeSource, s conversion.Scope) error { + return autoConvert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in, out, s) +} + +func autoConvert_api_EnvVar_To_v1_EnvVar(in *api.EnvVar, out *v1.EnvVar, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.EnvVar))(in) + } + out.Name = in.Name + out.Value = in.Value + // unable to generate simple pointer conversion for api.EnvVarSource -> v1.EnvVarSource + if in.ValueFrom != nil { + out.ValueFrom = new(v1.EnvVarSource) + if err := Convert_api_EnvVarSource_To_v1_EnvVarSource(in.ValueFrom, out.ValueFrom, s); err != nil { + return err + } + } else { + out.ValueFrom = nil + } + return nil +} + +func Convert_api_EnvVar_To_v1_EnvVar(in *api.EnvVar, out *v1.EnvVar, s conversion.Scope) error { + return autoConvert_api_EnvVar_To_v1_EnvVar(in, out, s) +} + +func autoConvert_api_EnvVarSource_To_v1_EnvVarSource(in *api.EnvVarSource, out *v1.EnvVarSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.EnvVarSource))(in) + } + // unable to generate simple pointer conversion for api.ObjectFieldSelector -> v1.ObjectFieldSelector + if in.FieldRef != nil { + out.FieldRef = new(v1.ObjectFieldSelector) + if err := Convert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(in.FieldRef, out.FieldRef, s); err != nil { + return err + } + } else { + out.FieldRef = nil + } + // unable to generate simple pointer conversion for api.ConfigMapKeySelector -> v1.ConfigMapKeySelector + if in.ConfigMapKeyRef != nil { + out.ConfigMapKeyRef = new(v1.ConfigMapKeySelector) + if err := Convert_api_ConfigMapKeySelector_To_v1_ConfigMapKeySelector(in.ConfigMapKeyRef, out.ConfigMapKeyRef, s); err != nil { + return err + } + } else { + out.ConfigMapKeyRef = nil + } + // unable to generate simple pointer conversion for api.SecretKeySelector -> v1.SecretKeySelector + if in.SecretKeyRef != nil { + out.SecretKeyRef = new(v1.SecretKeySelector) + if err := Convert_api_SecretKeySelector_To_v1_SecretKeySelector(in.SecretKeyRef, out.SecretKeyRef, s); err != nil { + return err + } + } else { + out.SecretKeyRef = nil + } + return nil +} + +func Convert_api_EnvVarSource_To_v1_EnvVarSource(in *api.EnvVarSource, out *v1.EnvVarSource, s conversion.Scope) error { + return autoConvert_api_EnvVarSource_To_v1_EnvVarSource(in, out, s) +} + +func autoConvert_api_ExecAction_To_v1_ExecAction(in *api.ExecAction, out *v1.ExecAction, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ExecAction))(in) + } + if in.Command != nil { + out.Command = make([]string, len(in.Command)) + for i := range in.Command { + out.Command[i] = in.Command[i] + } + } else { + out.Command = nil + } + return nil +} + +func Convert_api_ExecAction_To_v1_ExecAction(in *api.ExecAction, out *v1.ExecAction, s conversion.Scope) error { + return autoConvert_api_ExecAction_To_v1_ExecAction(in, out, s) +} + +func autoConvert_api_FCVolumeSource_To_v1_FCVolumeSource(in *api.FCVolumeSource, out *v1.FCVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.FCVolumeSource))(in) + } + if in.TargetWWNs != nil { + out.TargetWWNs = make([]string, len(in.TargetWWNs)) + for i := range in.TargetWWNs { + out.TargetWWNs[i] = in.TargetWWNs[i] + } + } else { + out.TargetWWNs = nil + } + if in.Lun != nil { + out.Lun = new(int32) + *out.Lun = int32(*in.Lun) + } else { + out.Lun = nil + } + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_FCVolumeSource_To_v1_FCVolumeSource(in *api.FCVolumeSource, out *v1.FCVolumeSource, s conversion.Scope) error { + return autoConvert_api_FCVolumeSource_To_v1_FCVolumeSource(in, out, s) +} + +func autoConvert_api_FlexVolumeSource_To_v1_FlexVolumeSource(in *api.FlexVolumeSource, out *v1.FlexVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.FlexVolumeSource))(in) + } + out.Driver = in.Driver + out.FSType = in.FSType + // unable to generate simple pointer conversion for api.LocalObjectReference -> v1.LocalObjectReference + if in.SecretRef != nil { + out.SecretRef = new(v1.LocalObjectReference) + if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(in.SecretRef, out.SecretRef, s); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + if in.Options != nil { + out.Options = make(map[string]string) + for key, val := range in.Options { + out.Options[key] = val + } + } else { + out.Options = nil + } + return nil +} + +func Convert_api_FlexVolumeSource_To_v1_FlexVolumeSource(in *api.FlexVolumeSource, out *v1.FlexVolumeSource, s conversion.Scope) error { + return autoConvert_api_FlexVolumeSource_To_v1_FlexVolumeSource(in, out, s) +} + +func autoConvert_api_FlockerVolumeSource_To_v1_FlockerVolumeSource(in *api.FlockerVolumeSource, out *v1.FlockerVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.FlockerVolumeSource))(in) + } + out.DatasetName = in.DatasetName + return nil +} + +func Convert_api_FlockerVolumeSource_To_v1_FlockerVolumeSource(in *api.FlockerVolumeSource, out *v1.FlockerVolumeSource, s conversion.Scope) error { + return autoConvert_api_FlockerVolumeSource_To_v1_FlockerVolumeSource(in, out, s) +} + +func autoConvert_api_GCEPersistentDiskVolumeSource_To_v1_GCEPersistentDiskVolumeSource(in *api.GCEPersistentDiskVolumeSource, out *v1.GCEPersistentDiskVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.GCEPersistentDiskVolumeSource))(in) + } + out.PDName = in.PDName + out.FSType = in.FSType + out.Partition = int32(in.Partition) + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_GCEPersistentDiskVolumeSource_To_v1_GCEPersistentDiskVolumeSource(in *api.GCEPersistentDiskVolumeSource, out *v1.GCEPersistentDiskVolumeSource, s conversion.Scope) error { + return autoConvert_api_GCEPersistentDiskVolumeSource_To_v1_GCEPersistentDiskVolumeSource(in, out, s) +} + +func autoConvert_api_GitRepoVolumeSource_To_v1_GitRepoVolumeSource(in *api.GitRepoVolumeSource, out *v1.GitRepoVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.GitRepoVolumeSource))(in) + } + out.Repository = in.Repository + out.Revision = in.Revision + out.Directory = in.Directory + return nil +} + +func Convert_api_GitRepoVolumeSource_To_v1_GitRepoVolumeSource(in *api.GitRepoVolumeSource, out *v1.GitRepoVolumeSource, s conversion.Scope) error { + return autoConvert_api_GitRepoVolumeSource_To_v1_GitRepoVolumeSource(in, out, s) +} + +func autoConvert_api_GlusterfsVolumeSource_To_v1_GlusterfsVolumeSource(in *api.GlusterfsVolumeSource, out *v1.GlusterfsVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.GlusterfsVolumeSource))(in) + } + out.EndpointsName = in.EndpointsName + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_GlusterfsVolumeSource_To_v1_GlusterfsVolumeSource(in *api.GlusterfsVolumeSource, out *v1.GlusterfsVolumeSource, s conversion.Scope) error { + return autoConvert_api_GlusterfsVolumeSource_To_v1_GlusterfsVolumeSource(in, out, s) +} + +func autoConvert_api_HTTPGetAction_To_v1_HTTPGetAction(in *api.HTTPGetAction, out *v1.HTTPGetAction, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.HTTPGetAction))(in) + } + out.Path = in.Path + if err := api.Convert_intstr_IntOrString_To_intstr_IntOrString(&in.Port, &out.Port, s); err != nil { + return err + } + out.Host = in.Host + out.Scheme = v1.URIScheme(in.Scheme) + if in.HTTPHeaders != nil { + out.HTTPHeaders = make([]v1.HTTPHeader, len(in.HTTPHeaders)) + for i := range in.HTTPHeaders { + if err := Convert_api_HTTPHeader_To_v1_HTTPHeader(&in.HTTPHeaders[i], &out.HTTPHeaders[i], s); err != nil { + return err + } + } + } else { + out.HTTPHeaders = nil + } + return nil +} + +func Convert_api_HTTPGetAction_To_v1_HTTPGetAction(in *api.HTTPGetAction, out *v1.HTTPGetAction, s conversion.Scope) error { + return autoConvert_api_HTTPGetAction_To_v1_HTTPGetAction(in, out, s) +} + +func autoConvert_api_HTTPHeader_To_v1_HTTPHeader(in *api.HTTPHeader, out *v1.HTTPHeader, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.HTTPHeader))(in) + } + out.Name = in.Name + out.Value = in.Value + return nil +} + +func Convert_api_HTTPHeader_To_v1_HTTPHeader(in *api.HTTPHeader, out *v1.HTTPHeader, s conversion.Scope) error { + return autoConvert_api_HTTPHeader_To_v1_HTTPHeader(in, out, s) +} + +func autoConvert_api_Handler_To_v1_Handler(in *api.Handler, out *v1.Handler, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.Handler))(in) + } + // unable to generate simple pointer conversion for api.ExecAction -> v1.ExecAction + if in.Exec != nil { + out.Exec = new(v1.ExecAction) + if err := Convert_api_ExecAction_To_v1_ExecAction(in.Exec, out.Exec, s); err != nil { + return err + } + } else { + out.Exec = nil + } + // unable to generate simple pointer conversion for api.HTTPGetAction -> v1.HTTPGetAction + if in.HTTPGet != nil { + out.HTTPGet = new(v1.HTTPGetAction) + if err := Convert_api_HTTPGetAction_To_v1_HTTPGetAction(in.HTTPGet, out.HTTPGet, s); err != nil { + return err + } + } else { + out.HTTPGet = nil + } + // unable to generate simple pointer conversion for api.TCPSocketAction -> v1.TCPSocketAction + if in.TCPSocket != nil { + out.TCPSocket = new(v1.TCPSocketAction) + if err := Convert_api_TCPSocketAction_To_v1_TCPSocketAction(in.TCPSocket, out.TCPSocket, s); err != nil { + return err + } + } else { + out.TCPSocket = nil + } + return nil +} + +func Convert_api_Handler_To_v1_Handler(in *api.Handler, out *v1.Handler, s conversion.Scope) error { + return autoConvert_api_Handler_To_v1_Handler(in, out, s) +} + +func autoConvert_api_HostPathVolumeSource_To_v1_HostPathVolumeSource(in *api.HostPathVolumeSource, out *v1.HostPathVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.HostPathVolumeSource))(in) + } + out.Path = in.Path + return nil +} + +func Convert_api_HostPathVolumeSource_To_v1_HostPathVolumeSource(in *api.HostPathVolumeSource, out *v1.HostPathVolumeSource, s conversion.Scope) error { + return autoConvert_api_HostPathVolumeSource_To_v1_HostPathVolumeSource(in, out, s) +} + +func autoConvert_api_ISCSIVolumeSource_To_v1_ISCSIVolumeSource(in *api.ISCSIVolumeSource, out *v1.ISCSIVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ISCSIVolumeSource))(in) + } + out.TargetPortal = in.TargetPortal + out.IQN = in.IQN + out.Lun = int32(in.Lun) + out.ISCSIInterface = in.ISCSIInterface + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_ISCSIVolumeSource_To_v1_ISCSIVolumeSource(in *api.ISCSIVolumeSource, out *v1.ISCSIVolumeSource, s conversion.Scope) error { + return autoConvert_api_ISCSIVolumeSource_To_v1_ISCSIVolumeSource(in, out, s) +} + +func autoConvert_api_KeyToPath_To_v1_KeyToPath(in *api.KeyToPath, out *v1.KeyToPath, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.KeyToPath))(in) + } + out.Key = in.Key + out.Path = in.Path + return nil +} + +func Convert_api_KeyToPath_To_v1_KeyToPath(in *api.KeyToPath, out *v1.KeyToPath, s conversion.Scope) error { + return autoConvert_api_KeyToPath_To_v1_KeyToPath(in, out, s) +} + +func autoConvert_api_Lifecycle_To_v1_Lifecycle(in *api.Lifecycle, out *v1.Lifecycle, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.Lifecycle))(in) + } + // unable to generate simple pointer conversion for api.Handler -> v1.Handler + if in.PostStart != nil { + out.PostStart = new(v1.Handler) + if err := Convert_api_Handler_To_v1_Handler(in.PostStart, out.PostStart, s); err != nil { + return err + } + } else { + out.PostStart = nil + } + // unable to generate simple pointer conversion for api.Handler -> v1.Handler + if in.PreStop != nil { + out.PreStop = new(v1.Handler) + if err := Convert_api_Handler_To_v1_Handler(in.PreStop, out.PreStop, s); err != nil { + return err + } + } else { + out.PreStop = nil + } + return nil +} + +func Convert_api_Lifecycle_To_v1_Lifecycle(in *api.Lifecycle, out *v1.Lifecycle, s conversion.Scope) error { + return autoConvert_api_Lifecycle_To_v1_Lifecycle(in, out, s) +} + +func autoConvert_api_LocalObjectReference_To_v1_LocalObjectReference(in *api.LocalObjectReference, out *v1.LocalObjectReference, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.LocalObjectReference))(in) + } + out.Name = in.Name + return nil +} + +func Convert_api_LocalObjectReference_To_v1_LocalObjectReference(in *api.LocalObjectReference, out *v1.LocalObjectReference, s conversion.Scope) error { + return autoConvert_api_LocalObjectReference_To_v1_LocalObjectReference(in, out, s) +} + +func autoConvert_api_NFSVolumeSource_To_v1_NFSVolumeSource(in *api.NFSVolumeSource, out *v1.NFSVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.NFSVolumeSource))(in) + } + out.Server = in.Server + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_NFSVolumeSource_To_v1_NFSVolumeSource(in *api.NFSVolumeSource, out *v1.NFSVolumeSource, s conversion.Scope) error { + return autoConvert_api_NFSVolumeSource_To_v1_NFSVolumeSource(in, out, s) +} + +func autoConvert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(in *api.ObjectFieldSelector, out *v1.ObjectFieldSelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ObjectFieldSelector))(in) + } + out.APIVersion = in.APIVersion + out.FieldPath = in.FieldPath + return nil +} + +func Convert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(in *api.ObjectFieldSelector, out *v1.ObjectFieldSelector, s conversion.Scope) error { + return autoConvert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector(in, out, s) +} + +func autoConvert_api_ObjectMeta_To_v1_ObjectMeta(in *api.ObjectMeta, out *v1.ObjectMeta, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ObjectMeta))(in) + } + 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 := api.Convert_unversioned_Time_To_unversioned_Time(&in.CreationTimestamp, &out.CreationTimestamp, s); err != nil { + return err + } + // unable to generate simple pointer conversion for unversioned.Time -> unversioned.Time + if in.DeletionTimestamp != nil { + out.DeletionTimestamp = new(unversioned.Time) + if err := api.Convert_unversioned_Time_To_unversioned_Time(in.DeletionTimestamp, out.DeletionTimestamp, s); err != nil { + return err + } + } else { + out.DeletionTimestamp = nil + } + if in.DeletionGracePeriodSeconds != nil { + out.DeletionGracePeriodSeconds = new(int64) + *out.DeletionGracePeriodSeconds = *in.DeletionGracePeriodSeconds + } else { + out.DeletionGracePeriodSeconds = nil + } + if in.Labels != nil { + out.Labels = make(map[string]string) + for key, val := range in.Labels { + out.Labels[key] = val + } + } else { + out.Labels = nil + } + if in.Annotations != nil { + out.Annotations = make(map[string]string) + for key, val := range in.Annotations { + out.Annotations[key] = val + } + } else { + out.Annotations = nil + } + return nil +} + +func Convert_api_ObjectMeta_To_v1_ObjectMeta(in *api.ObjectMeta, out *v1.ObjectMeta, s conversion.Scope) error { + return autoConvert_api_ObjectMeta_To_v1_ObjectMeta(in, out, s) +} + +func autoConvert_api_PersistentVolumeClaimVolumeSource_To_v1_PersistentVolumeClaimVolumeSource(in *api.PersistentVolumeClaimVolumeSource, out *v1.PersistentVolumeClaimVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.PersistentVolumeClaimVolumeSource))(in) + } + out.ClaimName = in.ClaimName + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_PersistentVolumeClaimVolumeSource_To_v1_PersistentVolumeClaimVolumeSource(in *api.PersistentVolumeClaimVolumeSource, out *v1.PersistentVolumeClaimVolumeSource, s conversion.Scope) error { + return autoConvert_api_PersistentVolumeClaimVolumeSource_To_v1_PersistentVolumeClaimVolumeSource(in, out, s) +} + +func autoConvert_api_PodSpec_To_v1_PodSpec(in *api.PodSpec, out *v1.PodSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.PodSpec))(in) + } + if in.Volumes != nil { + out.Volumes = make([]v1.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.Containers != nil { + out.Containers = make([]v1.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 + } + out.RestartPolicy = v1.RestartPolicy(in.RestartPolicy) + if in.TerminationGracePeriodSeconds != nil { + out.TerminationGracePeriodSeconds = new(int64) + *out.TerminationGracePeriodSeconds = *in.TerminationGracePeriodSeconds + } else { + out.TerminationGracePeriodSeconds = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + out.DNSPolicy = v1.DNSPolicy(in.DNSPolicy) + if in.NodeSelector != nil { + out.NodeSelector = make(map[string]string) + for key, val := range in.NodeSelector { + out.NodeSelector[key] = val + } + } else { + out.NodeSelector = nil + } + out.ServiceAccountName = in.ServiceAccountName + out.NodeName = in.NodeName + // unable to generate simple pointer conversion for api.PodSecurityContext -> v1.PodSecurityContext + if in.SecurityContext != nil { + if err := s.Convert(&in.SecurityContext, &out.SecurityContext, 0); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + if in.ImagePullSecrets != nil { + out.ImagePullSecrets = make([]v1.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 + } + return nil +} + +func autoConvert_api_PodTemplateSpec_To_v1_PodTemplateSpec(in *api.PodTemplateSpec, out *v1.PodTemplateSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.PodTemplateSpec))(in) + } + if err := Convert_api_ObjectMeta_To_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, s); err != nil { + return err + } + if err := Convert_api_PodSpec_To_v1_PodSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +func Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(in *api.PodTemplateSpec, out *v1.PodTemplateSpec, s conversion.Scope) error { + return autoConvert_api_PodTemplateSpec_To_v1_PodTemplateSpec(in, out, s) +} + +func autoConvert_api_Probe_To_v1_Probe(in *api.Probe, out *v1.Probe, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.Probe))(in) + } + if err := Convert_api_Handler_To_v1_Handler(&in.Handler, &out.Handler, s); err != nil { + return err + } + out.InitialDelaySeconds = int32(in.InitialDelaySeconds) + out.TimeoutSeconds = int32(in.TimeoutSeconds) + out.PeriodSeconds = int32(in.PeriodSeconds) + out.SuccessThreshold = int32(in.SuccessThreshold) + out.FailureThreshold = int32(in.FailureThreshold) + return nil +} + +func Convert_api_Probe_To_v1_Probe(in *api.Probe, out *v1.Probe, s conversion.Scope) error { + return autoConvert_api_Probe_To_v1_Probe(in, out, s) +} + +func autoConvert_api_RBDVolumeSource_To_v1_RBDVolumeSource(in *api.RBDVolumeSource, out *v1.RBDVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.RBDVolumeSource))(in) + } + if in.CephMonitors != nil { + out.CephMonitors = make([]string, len(in.CephMonitors)) + for i := range in.CephMonitors { + out.CephMonitors[i] = in.CephMonitors[i] + } + } else { + out.CephMonitors = nil + } + out.RBDImage = in.RBDImage + out.FSType = in.FSType + out.RBDPool = in.RBDPool + out.RadosUser = in.RadosUser + out.Keyring = in.Keyring + // unable to generate simple pointer conversion for api.LocalObjectReference -> v1.LocalObjectReference + if in.SecretRef != nil { + out.SecretRef = new(v1.LocalObjectReference) + if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(in.SecretRef, out.SecretRef, s); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_api_RBDVolumeSource_To_v1_RBDVolumeSource(in *api.RBDVolumeSource, out *v1.RBDVolumeSource, s conversion.Scope) error { + return autoConvert_api_RBDVolumeSource_To_v1_RBDVolumeSource(in, out, s) +} + +func autoConvert_api_ResourceRequirements_To_v1_ResourceRequirements(in *api.ResourceRequirements, out *v1.ResourceRequirements, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.ResourceRequirements))(in) + } + if in.Limits != nil { + out.Limits = make(v1.ResourceList) + for key, val := range in.Limits { + newVal := resource.Quantity{} + if err := api.Convert_resource_Quantity_To_resource_Quantity(&val, &newVal, s); err != nil { + return err + } + out.Limits[v1.ResourceName(key)] = newVal + } + } else { + out.Limits = nil + } + if in.Requests != nil { + out.Requests = make(v1.ResourceList) + for key, val := range in.Requests { + newVal := resource.Quantity{} + if err := api.Convert_resource_Quantity_To_resource_Quantity(&val, &newVal, s); err != nil { + return err + } + out.Requests[v1.ResourceName(key)] = newVal + } + } else { + out.Requests = nil + } + return nil +} + +func Convert_api_ResourceRequirements_To_v1_ResourceRequirements(in *api.ResourceRequirements, out *v1.ResourceRequirements, s conversion.Scope) error { + return autoConvert_api_ResourceRequirements_To_v1_ResourceRequirements(in, out, s) +} + +func autoConvert_api_SELinuxOptions_To_v1_SELinuxOptions(in *api.SELinuxOptions, out *v1.SELinuxOptions, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.SELinuxOptions))(in) + } + out.User = in.User + out.Role = in.Role + out.Type = in.Type + out.Level = in.Level + return nil +} + +func Convert_api_SELinuxOptions_To_v1_SELinuxOptions(in *api.SELinuxOptions, out *v1.SELinuxOptions, s conversion.Scope) error { + return autoConvert_api_SELinuxOptions_To_v1_SELinuxOptions(in, out, s) +} + +func autoConvert_api_SecretKeySelector_To_v1_SecretKeySelector(in *api.SecretKeySelector, out *v1.SecretKeySelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.SecretKeySelector))(in) + } + if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(&in.LocalObjectReference, &out.LocalObjectReference, s); err != nil { + return err + } + out.Key = in.Key + return nil +} + +func Convert_api_SecretKeySelector_To_v1_SecretKeySelector(in *api.SecretKeySelector, out *v1.SecretKeySelector, s conversion.Scope) error { + return autoConvert_api_SecretKeySelector_To_v1_SecretKeySelector(in, out, s) +} + +func autoConvert_api_SecretVolumeSource_To_v1_SecretVolumeSource(in *api.SecretVolumeSource, out *v1.SecretVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.SecretVolumeSource))(in) + } + out.SecretName = in.SecretName + return nil +} + +func Convert_api_SecretVolumeSource_To_v1_SecretVolumeSource(in *api.SecretVolumeSource, out *v1.SecretVolumeSource, s conversion.Scope) error { + return autoConvert_api_SecretVolumeSource_To_v1_SecretVolumeSource(in, out, s) +} + +func autoConvert_api_SecurityContext_To_v1_SecurityContext(in *api.SecurityContext, out *v1.SecurityContext, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.SecurityContext))(in) + } + // unable to generate simple pointer conversion for api.Capabilities -> v1.Capabilities + if in.Capabilities != nil { + out.Capabilities = new(v1.Capabilities) + if err := Convert_api_Capabilities_To_v1_Capabilities(in.Capabilities, out.Capabilities, s); err != nil { + return err + } + } else { + out.Capabilities = nil + } + if in.Privileged != nil { + out.Privileged = new(bool) + *out.Privileged = *in.Privileged + } else { + out.Privileged = nil + } + // unable to generate simple pointer conversion for api.SELinuxOptions -> v1.SELinuxOptions + if in.SELinuxOptions != nil { + out.SELinuxOptions = new(v1.SELinuxOptions) + if err := Convert_api_SELinuxOptions_To_v1_SELinuxOptions(in.SELinuxOptions, out.SELinuxOptions, s); err != nil { + return err + } + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + out.RunAsUser = new(int64) + *out.RunAsUser = *in.RunAsUser + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + out.RunAsNonRoot = new(bool) + *out.RunAsNonRoot = *in.RunAsNonRoot + } else { + out.RunAsNonRoot = nil + } + if in.ReadOnlyRootFilesystem != nil { + out.ReadOnlyRootFilesystem = new(bool) + *out.ReadOnlyRootFilesystem = *in.ReadOnlyRootFilesystem + } else { + out.ReadOnlyRootFilesystem = nil + } + return nil +} + +func Convert_api_SecurityContext_To_v1_SecurityContext(in *api.SecurityContext, out *v1.SecurityContext, s conversion.Scope) error { + return autoConvert_api_SecurityContext_To_v1_SecurityContext(in, out, s) +} + +func autoConvert_api_TCPSocketAction_To_v1_TCPSocketAction(in *api.TCPSocketAction, out *v1.TCPSocketAction, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.TCPSocketAction))(in) + } + if err := api.Convert_intstr_IntOrString_To_intstr_IntOrString(&in.Port, &out.Port, s); err != nil { + return err + } + return nil +} + +func Convert_api_TCPSocketAction_To_v1_TCPSocketAction(in *api.TCPSocketAction, out *v1.TCPSocketAction, s conversion.Scope) error { + return autoConvert_api_TCPSocketAction_To_v1_TCPSocketAction(in, out, s) +} + +func autoConvert_api_Volume_To_v1_Volume(in *api.Volume, out *v1.Volume, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.Volume))(in) + } + out.Name = in.Name + if err := Convert_api_VolumeSource_To_v1_VolumeSource(&in.VolumeSource, &out.VolumeSource, s); err != nil { + return err + } + return nil +} + +func Convert_api_Volume_To_v1_Volume(in *api.Volume, out *v1.Volume, s conversion.Scope) error { + return autoConvert_api_Volume_To_v1_Volume(in, out, s) +} + +func autoConvert_api_VolumeMount_To_v1_VolumeMount(in *api.VolumeMount, out *v1.VolumeMount, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.VolumeMount))(in) + } + out.Name = in.Name + out.ReadOnly = in.ReadOnly + out.MountPath = in.MountPath + return nil +} + +func Convert_api_VolumeMount_To_v1_VolumeMount(in *api.VolumeMount, out *v1.VolumeMount, s conversion.Scope) error { + return autoConvert_api_VolumeMount_To_v1_VolumeMount(in, out, s) +} + +func autoConvert_api_VolumeSource_To_v1_VolumeSource(in *api.VolumeSource, out *v1.VolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*api.VolumeSource))(in) + } + // unable to generate simple pointer conversion for api.HostPathVolumeSource -> v1.HostPathVolumeSource + if in.HostPath != nil { + out.HostPath = new(v1.HostPathVolumeSource) + if err := Convert_api_HostPathVolumeSource_To_v1_HostPathVolumeSource(in.HostPath, out.HostPath, s); err != nil { + return err + } + } else { + out.HostPath = nil + } + // unable to generate simple pointer conversion for api.EmptyDirVolumeSource -> v1.EmptyDirVolumeSource + if in.EmptyDir != nil { + out.EmptyDir = new(v1.EmptyDirVolumeSource) + if err := Convert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource(in.EmptyDir, out.EmptyDir, s); err != nil { + return err + } + } else { + out.EmptyDir = nil + } + // unable to generate simple pointer conversion for api.GCEPersistentDiskVolumeSource -> v1.GCEPersistentDiskVolumeSource + if in.GCEPersistentDisk != nil { + out.GCEPersistentDisk = new(v1.GCEPersistentDiskVolumeSource) + if err := Convert_api_GCEPersistentDiskVolumeSource_To_v1_GCEPersistentDiskVolumeSource(in.GCEPersistentDisk, out.GCEPersistentDisk, s); err != nil { + return err + } + } else { + out.GCEPersistentDisk = nil + } + // unable to generate simple pointer conversion for api.AWSElasticBlockStoreVolumeSource -> v1.AWSElasticBlockStoreVolumeSource + if in.AWSElasticBlockStore != nil { + out.AWSElasticBlockStore = new(v1.AWSElasticBlockStoreVolumeSource) + if err := Convert_api_AWSElasticBlockStoreVolumeSource_To_v1_AWSElasticBlockStoreVolumeSource(in.AWSElasticBlockStore, out.AWSElasticBlockStore, s); err != nil { + return err + } + } else { + out.AWSElasticBlockStore = nil + } + // unable to generate simple pointer conversion for api.GitRepoVolumeSource -> v1.GitRepoVolumeSource + if in.GitRepo != nil { + out.GitRepo = new(v1.GitRepoVolumeSource) + if err := Convert_api_GitRepoVolumeSource_To_v1_GitRepoVolumeSource(in.GitRepo, out.GitRepo, s); err != nil { + return err + } + } else { + out.GitRepo = nil + } + // unable to generate simple pointer conversion for api.SecretVolumeSource -> v1.SecretVolumeSource + if in.Secret != nil { + out.Secret = new(v1.SecretVolumeSource) + if err := Convert_api_SecretVolumeSource_To_v1_SecretVolumeSource(in.Secret, out.Secret, s); err != nil { + return err + } + } else { + out.Secret = nil + } + // unable to generate simple pointer conversion for api.NFSVolumeSource -> v1.NFSVolumeSource + if in.NFS != nil { + out.NFS = new(v1.NFSVolumeSource) + if err := Convert_api_NFSVolumeSource_To_v1_NFSVolumeSource(in.NFS, out.NFS, s); err != nil { + return err + } + } else { + out.NFS = nil + } + // unable to generate simple pointer conversion for api.ISCSIVolumeSource -> v1.ISCSIVolumeSource + if in.ISCSI != nil { + out.ISCSI = new(v1.ISCSIVolumeSource) + if err := Convert_api_ISCSIVolumeSource_To_v1_ISCSIVolumeSource(in.ISCSI, out.ISCSI, s); err != nil { + return err + } + } else { + out.ISCSI = nil + } + // unable to generate simple pointer conversion for api.GlusterfsVolumeSource -> v1.GlusterfsVolumeSource + if in.Glusterfs != nil { + out.Glusterfs = new(v1.GlusterfsVolumeSource) + if err := Convert_api_GlusterfsVolumeSource_To_v1_GlusterfsVolumeSource(in.Glusterfs, out.Glusterfs, s); err != nil { + return err + } + } else { + out.Glusterfs = nil + } + // unable to generate simple pointer conversion for api.PersistentVolumeClaimVolumeSource -> v1.PersistentVolumeClaimVolumeSource + if in.PersistentVolumeClaim != nil { + out.PersistentVolumeClaim = new(v1.PersistentVolumeClaimVolumeSource) + if err := Convert_api_PersistentVolumeClaimVolumeSource_To_v1_PersistentVolumeClaimVolumeSource(in.PersistentVolumeClaim, out.PersistentVolumeClaim, s); err != nil { + return err + } + } else { + out.PersistentVolumeClaim = nil + } + // unable to generate simple pointer conversion for api.RBDVolumeSource -> v1.RBDVolumeSource + if in.RBD != nil { + out.RBD = new(v1.RBDVolumeSource) + if err := Convert_api_RBDVolumeSource_To_v1_RBDVolumeSource(in.RBD, out.RBD, s); err != nil { + return err + } + } else { + out.RBD = nil + } + // unable to generate simple pointer conversion for api.FlexVolumeSource -> v1.FlexVolumeSource + if in.FlexVolume != nil { + out.FlexVolume = new(v1.FlexVolumeSource) + if err := Convert_api_FlexVolumeSource_To_v1_FlexVolumeSource(in.FlexVolume, out.FlexVolume, s); err != nil { + return err + } + } else { + out.FlexVolume = nil + } + // unable to generate simple pointer conversion for api.CinderVolumeSource -> v1.CinderVolumeSource + if in.Cinder != nil { + out.Cinder = new(v1.CinderVolumeSource) + if err := Convert_api_CinderVolumeSource_To_v1_CinderVolumeSource(in.Cinder, out.Cinder, s); err != nil { + return err + } + } else { + out.Cinder = nil + } + // unable to generate simple pointer conversion for api.CephFSVolumeSource -> v1.CephFSVolumeSource + if in.CephFS != nil { + out.CephFS = new(v1.CephFSVolumeSource) + if err := Convert_api_CephFSVolumeSource_To_v1_CephFSVolumeSource(in.CephFS, out.CephFS, s); err != nil { + return err + } + } else { + out.CephFS = nil + } + // unable to generate simple pointer conversion for api.FlockerVolumeSource -> v1.FlockerVolumeSource + if in.Flocker != nil { + out.Flocker = new(v1.FlockerVolumeSource) + if err := Convert_api_FlockerVolumeSource_To_v1_FlockerVolumeSource(in.Flocker, out.Flocker, s); err != nil { + return err + } + } else { + out.Flocker = nil + } + // unable to generate simple pointer conversion for api.DownwardAPIVolumeSource -> v1.DownwardAPIVolumeSource + if in.DownwardAPI != nil { + out.DownwardAPI = new(v1.DownwardAPIVolumeSource) + if err := Convert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource(in.DownwardAPI, out.DownwardAPI, s); err != nil { + return err + } + } else { + out.DownwardAPI = nil + } + // unable to generate simple pointer conversion for api.FCVolumeSource -> v1.FCVolumeSource + if in.FC != nil { + out.FC = new(v1.FCVolumeSource) + if err := Convert_api_FCVolumeSource_To_v1_FCVolumeSource(in.FC, out.FC, s); err != nil { + return err + } + } else { + out.FC = nil + } + // unable to generate simple pointer conversion for api.AzureFileVolumeSource -> v1.AzureFileVolumeSource + if in.AzureFile != nil { + out.AzureFile = new(v1.AzureFileVolumeSource) + if err := Convert_api_AzureFileVolumeSource_To_v1_AzureFileVolumeSource(in.AzureFile, out.AzureFile, s); err != nil { + return err + } + } else { + out.AzureFile = nil + } + // unable to generate simple pointer conversion for api.ConfigMapVolumeSource -> v1.ConfigMapVolumeSource + if in.ConfigMap != nil { + out.ConfigMap = new(v1.ConfigMapVolumeSource) + if err := Convert_api_ConfigMapVolumeSource_To_v1_ConfigMapVolumeSource(in.ConfigMap, out.ConfigMap, s); err != nil { + return err + } + } else { + out.ConfigMap = nil + } + return nil +} + +func Convert_api_VolumeSource_To_v1_VolumeSource(in *api.VolumeSource, out *v1.VolumeSource, s conversion.Scope) error { + return autoConvert_api_VolumeSource_To_v1_VolumeSource(in, out, s) +} + +func autoConvert_unversioned_LabelSelector_To_v1_LabelSelector(in *unversioned.LabelSelector, out *LabelSelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*unversioned.LabelSelector))(in) + } + if in.MatchLabels != nil { + out.MatchLabels = make(map[string]string) + for key, val := range in.MatchLabels { + out.MatchLabels[key] = val + } + } else { + out.MatchLabels = nil + } + if in.MatchExpressions != nil { + out.MatchExpressions = make([]LabelSelectorRequirement, len(in.MatchExpressions)) + for i := range in.MatchExpressions { + if err := Convert_unversioned_LabelSelectorRequirement_To_v1_LabelSelectorRequirement(&in.MatchExpressions[i], &out.MatchExpressions[i], s); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil +} + +func Convert_unversioned_LabelSelector_To_v1_LabelSelector(in *unversioned.LabelSelector, out *LabelSelector, s conversion.Scope) error { + return autoConvert_unversioned_LabelSelector_To_v1_LabelSelector(in, out, s) +} + +func autoConvert_unversioned_LabelSelectorRequirement_To_v1_LabelSelectorRequirement(in *unversioned.LabelSelectorRequirement, out *LabelSelectorRequirement, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*unversioned.LabelSelectorRequirement))(in) + } + out.Key = in.Key + out.Operator = LabelSelectorOperator(in.Operator) + if in.Values != nil { + out.Values = make([]string, len(in.Values)) + for i := range in.Values { + out.Values[i] = in.Values[i] + } + } else { + out.Values = nil + } + return nil +} + +func Convert_unversioned_LabelSelectorRequirement_To_v1_LabelSelectorRequirement(in *unversioned.LabelSelectorRequirement, out *LabelSelectorRequirement, s conversion.Scope) error { + return autoConvert_unversioned_LabelSelectorRequirement_To_v1_LabelSelectorRequirement(in, out, s) +} + +func autoConvert_v1_AWSElasticBlockStoreVolumeSource_To_api_AWSElasticBlockStoreVolumeSource(in *v1.AWSElasticBlockStoreVolumeSource, out *api.AWSElasticBlockStoreVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.AWSElasticBlockStoreVolumeSource))(in) + } + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.Partition = int(in.Partition) + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_AWSElasticBlockStoreVolumeSource_To_api_AWSElasticBlockStoreVolumeSource(in *v1.AWSElasticBlockStoreVolumeSource, out *api.AWSElasticBlockStoreVolumeSource, s conversion.Scope) error { + return autoConvert_v1_AWSElasticBlockStoreVolumeSource_To_api_AWSElasticBlockStoreVolumeSource(in, out, s) +} + +func autoConvert_v1_AzureFileVolumeSource_To_api_AzureFileVolumeSource(in *v1.AzureFileVolumeSource, out *api.AzureFileVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.AzureFileVolumeSource))(in) + } + out.SecretName = in.SecretName + out.ShareName = in.ShareName + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_AzureFileVolumeSource_To_api_AzureFileVolumeSource(in *v1.AzureFileVolumeSource, out *api.AzureFileVolumeSource, s conversion.Scope) error { + return autoConvert_v1_AzureFileVolumeSource_To_api_AzureFileVolumeSource(in, out, s) +} + +func autoConvert_v1_Capabilities_To_api_Capabilities(in *v1.Capabilities, out *api.Capabilities, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.Capabilities))(in) + } + if in.Add != nil { + out.Add = make([]api.Capability, len(in.Add)) + for i := range in.Add { + out.Add[i] = api.Capability(in.Add[i]) + } + } else { + out.Add = nil + } + if in.Drop != nil { + out.Drop = make([]api.Capability, len(in.Drop)) + for i := range in.Drop { + out.Drop[i] = api.Capability(in.Drop[i]) + } + } else { + out.Drop = nil + } + return nil +} + +func Convert_v1_Capabilities_To_api_Capabilities(in *v1.Capabilities, out *api.Capabilities, s conversion.Scope) error { + return autoConvert_v1_Capabilities_To_api_Capabilities(in, out, s) +} + +func autoConvert_v1_CephFSVolumeSource_To_api_CephFSVolumeSource(in *v1.CephFSVolumeSource, out *api.CephFSVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.CephFSVolumeSource))(in) + } + if in.Monitors != nil { + out.Monitors = make([]string, len(in.Monitors)) + for i := range in.Monitors { + out.Monitors[i] = in.Monitors[i] + } + } else { + out.Monitors = nil + } + out.Path = in.Path + out.User = in.User + out.SecretFile = in.SecretFile + // unable to generate simple pointer conversion for v1.LocalObjectReference -> api.LocalObjectReference + if in.SecretRef != nil { + out.SecretRef = new(api.LocalObjectReference) + if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(in.SecretRef, out.SecretRef, s); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_CephFSVolumeSource_To_api_CephFSVolumeSource(in *v1.CephFSVolumeSource, out *api.CephFSVolumeSource, s conversion.Scope) error { + return autoConvert_v1_CephFSVolumeSource_To_api_CephFSVolumeSource(in, out, s) +} + +func autoConvert_v1_CinderVolumeSource_To_api_CinderVolumeSource(in *v1.CinderVolumeSource, out *api.CinderVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.CinderVolumeSource))(in) + } + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_CinderVolumeSource_To_api_CinderVolumeSource(in *v1.CinderVolumeSource, out *api.CinderVolumeSource, s conversion.Scope) error { + return autoConvert_v1_CinderVolumeSource_To_api_CinderVolumeSource(in, out, s) +} + +func autoConvert_v1_ConfigMapKeySelector_To_api_ConfigMapKeySelector(in *v1.ConfigMapKeySelector, out *api.ConfigMapKeySelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ConfigMapKeySelector))(in) + } + if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(&in.LocalObjectReference, &out.LocalObjectReference, s); err != nil { + return err + } + out.Key = in.Key + return nil +} + +func Convert_v1_ConfigMapKeySelector_To_api_ConfigMapKeySelector(in *v1.ConfigMapKeySelector, out *api.ConfigMapKeySelector, s conversion.Scope) error { + return autoConvert_v1_ConfigMapKeySelector_To_api_ConfigMapKeySelector(in, out, s) +} + +func autoConvert_v1_ConfigMapVolumeSource_To_api_ConfigMapVolumeSource(in *v1.ConfigMapVolumeSource, out *api.ConfigMapVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ConfigMapVolumeSource))(in) + } + if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(&in.LocalObjectReference, &out.LocalObjectReference, s); err != nil { + return err + } + if in.Items != nil { + out.Items = make([]api.KeyToPath, len(in.Items)) + for i := range in.Items { + if err := Convert_v1_KeyToPath_To_api_KeyToPath(&in.Items[i], &out.Items[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_v1_ConfigMapVolumeSource_To_api_ConfigMapVolumeSource(in *v1.ConfigMapVolumeSource, out *api.ConfigMapVolumeSource, s conversion.Scope) error { + return autoConvert_v1_ConfigMapVolumeSource_To_api_ConfigMapVolumeSource(in, out, s) +} + +func autoConvert_v1_Container_To_api_Container(in *v1.Container, out *api.Container, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.Container))(in) + } + out.Name = in.Name + out.Image = in.Image + if in.Command != nil { + out.Command = make([]string, len(in.Command)) + for i := range in.Command { + out.Command[i] = in.Command[i] + } + } else { + out.Command = nil + } + if in.Args != nil { + out.Args = make([]string, len(in.Args)) + for i := range in.Args { + out.Args[i] = in.Args[i] + } + } else { + out.Args = nil + } + out.WorkingDir = in.WorkingDir + if in.Ports != nil { + out.Ports = make([]api.ContainerPort, len(in.Ports)) + for i := range in.Ports { + if err := Convert_v1_ContainerPort_To_api_ContainerPort(&in.Ports[i], &out.Ports[i], s); err != nil { + return err + } + } + } else { + out.Ports = nil + } + if in.Env != nil { + out.Env = make([]api.EnvVar, len(in.Env)) + for i := range in.Env { + if err := Convert_v1_EnvVar_To_api_EnvVar(&in.Env[i], &out.Env[i], s); err != nil { + return err + } + } + } else { + out.Env = nil + } + if err := Convert_v1_ResourceRequirements_To_api_ResourceRequirements(&in.Resources, &out.Resources, s); err != nil { + return err + } + if in.VolumeMounts != nil { + out.VolumeMounts = make([]api.VolumeMount, len(in.VolumeMounts)) + for i := range in.VolumeMounts { + if err := Convert_v1_VolumeMount_To_api_VolumeMount(&in.VolumeMounts[i], &out.VolumeMounts[i], s); err != nil { + return err + } + } + } else { + out.VolumeMounts = nil + } + // unable to generate simple pointer conversion for v1.Probe -> api.Probe + if in.LivenessProbe != nil { + out.LivenessProbe = new(api.Probe) + if err := Convert_v1_Probe_To_api_Probe(in.LivenessProbe, out.LivenessProbe, s); err != nil { + return err + } + } else { + out.LivenessProbe = nil + } + // unable to generate simple pointer conversion for v1.Probe -> api.Probe + if in.ReadinessProbe != nil { + out.ReadinessProbe = new(api.Probe) + if err := Convert_v1_Probe_To_api_Probe(in.ReadinessProbe, out.ReadinessProbe, s); err != nil { + return err + } + } else { + out.ReadinessProbe = nil + } + // unable to generate simple pointer conversion for v1.Lifecycle -> api.Lifecycle + if in.Lifecycle != nil { + out.Lifecycle = new(api.Lifecycle) + if err := Convert_v1_Lifecycle_To_api_Lifecycle(in.Lifecycle, out.Lifecycle, s); err != nil { + return err + } + } else { + out.Lifecycle = nil + } + out.TerminationMessagePath = in.TerminationMessagePath + out.ImagePullPolicy = api.PullPolicy(in.ImagePullPolicy) + // unable to generate simple pointer conversion for v1.SecurityContext -> api.SecurityContext + if in.SecurityContext != nil { + out.SecurityContext = new(api.SecurityContext) + if err := Convert_v1_SecurityContext_To_api_SecurityContext(in.SecurityContext, out.SecurityContext, s); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + out.Stdin = in.Stdin + out.StdinOnce = in.StdinOnce + out.TTY = in.TTY + return nil +} + +func Convert_v1_Container_To_api_Container(in *v1.Container, out *api.Container, s conversion.Scope) error { + return autoConvert_v1_Container_To_api_Container(in, out, s) +} + +func autoConvert_v1_ContainerPort_To_api_ContainerPort(in *v1.ContainerPort, out *api.ContainerPort, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ContainerPort))(in) + } + out.Name = in.Name + out.HostPort = int(in.HostPort) + out.ContainerPort = int(in.ContainerPort) + out.Protocol = api.Protocol(in.Protocol) + out.HostIP = in.HostIP + return nil +} + +func Convert_v1_ContainerPort_To_api_ContainerPort(in *v1.ContainerPort, out *api.ContainerPort, s conversion.Scope) error { + return autoConvert_v1_ContainerPort_To_api_ContainerPort(in, out, s) +} + +func autoConvert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(in *v1.DownwardAPIVolumeFile, out *api.DownwardAPIVolumeFile, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.DownwardAPIVolumeFile))(in) + } + out.Path = in.Path + if err := Convert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(&in.FieldRef, &out.FieldRef, s); err != nil { + return err + } + return nil +} + +func Convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(in *v1.DownwardAPIVolumeFile, out *api.DownwardAPIVolumeFile, s conversion.Scope) error { + return autoConvert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(in, out, s) +} + +func autoConvert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in *v1.DownwardAPIVolumeSource, out *api.DownwardAPIVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.DownwardAPIVolumeSource))(in) + } + if in.Items != nil { + out.Items = make([]api.DownwardAPIVolumeFile, len(in.Items)) + for i := range in.Items { + if err := Convert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile(&in.Items[i], &out.Items[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in *v1.DownwardAPIVolumeSource, out *api.DownwardAPIVolumeSource, s conversion.Scope) error { + return autoConvert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in, out, s) +} + +func autoConvert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in *v1.EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.EmptyDirVolumeSource))(in) + } + out.Medium = api.StorageMedium(in.Medium) + return nil +} + +func Convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in *v1.EmptyDirVolumeSource, out *api.EmptyDirVolumeSource, s conversion.Scope) error { + return autoConvert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in, out, s) +} + +func autoConvert_v1_EnvVar_To_api_EnvVar(in *v1.EnvVar, out *api.EnvVar, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.EnvVar))(in) + } + out.Name = in.Name + out.Value = in.Value + // unable to generate simple pointer conversion for v1.EnvVarSource -> api.EnvVarSource + if in.ValueFrom != nil { + out.ValueFrom = new(api.EnvVarSource) + if err := Convert_v1_EnvVarSource_To_api_EnvVarSource(in.ValueFrom, out.ValueFrom, s); err != nil { + return err + } + } else { + out.ValueFrom = nil + } + return nil +} + +func Convert_v1_EnvVar_To_api_EnvVar(in *v1.EnvVar, out *api.EnvVar, s conversion.Scope) error { + return autoConvert_v1_EnvVar_To_api_EnvVar(in, out, s) +} + +func autoConvert_v1_EnvVarSource_To_api_EnvVarSource(in *v1.EnvVarSource, out *api.EnvVarSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.EnvVarSource))(in) + } + // unable to generate simple pointer conversion for v1.ObjectFieldSelector -> api.ObjectFieldSelector + if in.FieldRef != nil { + out.FieldRef = new(api.ObjectFieldSelector) + if err := Convert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(in.FieldRef, out.FieldRef, s); err != nil { + return err + } + } else { + out.FieldRef = nil + } + // unable to generate simple pointer conversion for v1.ConfigMapKeySelector -> api.ConfigMapKeySelector + if in.ConfigMapKeyRef != nil { + out.ConfigMapKeyRef = new(api.ConfigMapKeySelector) + if err := Convert_v1_ConfigMapKeySelector_To_api_ConfigMapKeySelector(in.ConfigMapKeyRef, out.ConfigMapKeyRef, s); err != nil { + return err + } + } else { + out.ConfigMapKeyRef = nil + } + // unable to generate simple pointer conversion for v1.SecretKeySelector -> api.SecretKeySelector + if in.SecretKeyRef != nil { + out.SecretKeyRef = new(api.SecretKeySelector) + if err := Convert_v1_SecretKeySelector_To_api_SecretKeySelector(in.SecretKeyRef, out.SecretKeyRef, s); err != nil { + return err + } + } else { + out.SecretKeyRef = nil + } + return nil +} + +func Convert_v1_EnvVarSource_To_api_EnvVarSource(in *v1.EnvVarSource, out *api.EnvVarSource, s conversion.Scope) error { + return autoConvert_v1_EnvVarSource_To_api_EnvVarSource(in, out, s) +} + +func autoConvert_v1_ExecAction_To_api_ExecAction(in *v1.ExecAction, out *api.ExecAction, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ExecAction))(in) + } + if in.Command != nil { + out.Command = make([]string, len(in.Command)) + for i := range in.Command { + out.Command[i] = in.Command[i] + } + } else { + out.Command = nil + } + return nil +} + +func Convert_v1_ExecAction_To_api_ExecAction(in *v1.ExecAction, out *api.ExecAction, s conversion.Scope) error { + return autoConvert_v1_ExecAction_To_api_ExecAction(in, out, s) +} + +func autoConvert_v1_FCVolumeSource_To_api_FCVolumeSource(in *v1.FCVolumeSource, out *api.FCVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.FCVolumeSource))(in) + } + if in.TargetWWNs != nil { + out.TargetWWNs = make([]string, len(in.TargetWWNs)) + for i := range in.TargetWWNs { + out.TargetWWNs[i] = in.TargetWWNs[i] + } + } else { + out.TargetWWNs = nil + } + if in.Lun != nil { + out.Lun = new(int) + *out.Lun = int(*in.Lun) + } else { + out.Lun = nil + } + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_FCVolumeSource_To_api_FCVolumeSource(in *v1.FCVolumeSource, out *api.FCVolumeSource, s conversion.Scope) error { + return autoConvert_v1_FCVolumeSource_To_api_FCVolumeSource(in, out, s) +} + +func autoConvert_v1_FlexVolumeSource_To_api_FlexVolumeSource(in *v1.FlexVolumeSource, out *api.FlexVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.FlexVolumeSource))(in) + } + out.Driver = in.Driver + out.FSType = in.FSType + // unable to generate simple pointer conversion for v1.LocalObjectReference -> api.LocalObjectReference + if in.SecretRef != nil { + out.SecretRef = new(api.LocalObjectReference) + if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(in.SecretRef, out.SecretRef, s); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + if in.Options != nil { + out.Options = make(map[string]string) + for key, val := range in.Options { + out.Options[key] = val + } + } else { + out.Options = nil + } + return nil +} + +func Convert_v1_FlexVolumeSource_To_api_FlexVolumeSource(in *v1.FlexVolumeSource, out *api.FlexVolumeSource, s conversion.Scope) error { + return autoConvert_v1_FlexVolumeSource_To_api_FlexVolumeSource(in, out, s) +} + +func autoConvert_v1_FlockerVolumeSource_To_api_FlockerVolumeSource(in *v1.FlockerVolumeSource, out *api.FlockerVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.FlockerVolumeSource))(in) + } + out.DatasetName = in.DatasetName + return nil +} + +func Convert_v1_FlockerVolumeSource_To_api_FlockerVolumeSource(in *v1.FlockerVolumeSource, out *api.FlockerVolumeSource, s conversion.Scope) error { + return autoConvert_v1_FlockerVolumeSource_To_api_FlockerVolumeSource(in, out, s) +} + +func autoConvert_v1_GCEPersistentDiskVolumeSource_To_api_GCEPersistentDiskVolumeSource(in *v1.GCEPersistentDiskVolumeSource, out *api.GCEPersistentDiskVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.GCEPersistentDiskVolumeSource))(in) + } + out.PDName = in.PDName + out.FSType = in.FSType + out.Partition = int(in.Partition) + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_GCEPersistentDiskVolumeSource_To_api_GCEPersistentDiskVolumeSource(in *v1.GCEPersistentDiskVolumeSource, out *api.GCEPersistentDiskVolumeSource, s conversion.Scope) error { + return autoConvert_v1_GCEPersistentDiskVolumeSource_To_api_GCEPersistentDiskVolumeSource(in, out, s) +} + +func autoConvert_v1_GitRepoVolumeSource_To_api_GitRepoVolumeSource(in *v1.GitRepoVolumeSource, out *api.GitRepoVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.GitRepoVolumeSource))(in) + } + out.Repository = in.Repository + out.Revision = in.Revision + out.Directory = in.Directory + return nil +} + +func Convert_v1_GitRepoVolumeSource_To_api_GitRepoVolumeSource(in *v1.GitRepoVolumeSource, out *api.GitRepoVolumeSource, s conversion.Scope) error { + return autoConvert_v1_GitRepoVolumeSource_To_api_GitRepoVolumeSource(in, out, s) +} + +func autoConvert_v1_GlusterfsVolumeSource_To_api_GlusterfsVolumeSource(in *v1.GlusterfsVolumeSource, out *api.GlusterfsVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.GlusterfsVolumeSource))(in) + } + out.EndpointsName = in.EndpointsName + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_GlusterfsVolumeSource_To_api_GlusterfsVolumeSource(in *v1.GlusterfsVolumeSource, out *api.GlusterfsVolumeSource, s conversion.Scope) error { + return autoConvert_v1_GlusterfsVolumeSource_To_api_GlusterfsVolumeSource(in, out, s) +} + +func autoConvert_v1_HTTPGetAction_To_api_HTTPGetAction(in *v1.HTTPGetAction, out *api.HTTPGetAction, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.HTTPGetAction))(in) + } + out.Path = in.Path + if err := api.Convert_intstr_IntOrString_To_intstr_IntOrString(&in.Port, &out.Port, s); err != nil { + return err + } + out.Host = in.Host + out.Scheme = api.URIScheme(in.Scheme) + if in.HTTPHeaders != nil { + out.HTTPHeaders = make([]api.HTTPHeader, len(in.HTTPHeaders)) + for i := range in.HTTPHeaders { + if err := Convert_v1_HTTPHeader_To_api_HTTPHeader(&in.HTTPHeaders[i], &out.HTTPHeaders[i], s); err != nil { + return err + } + } + } else { + out.HTTPHeaders = nil + } + return nil +} + +func Convert_v1_HTTPGetAction_To_api_HTTPGetAction(in *v1.HTTPGetAction, out *api.HTTPGetAction, s conversion.Scope) error { + return autoConvert_v1_HTTPGetAction_To_api_HTTPGetAction(in, out, s) +} + +func autoConvert_v1_HTTPHeader_To_api_HTTPHeader(in *v1.HTTPHeader, out *api.HTTPHeader, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.HTTPHeader))(in) + } + out.Name = in.Name + out.Value = in.Value + return nil +} + +func Convert_v1_HTTPHeader_To_api_HTTPHeader(in *v1.HTTPHeader, out *api.HTTPHeader, s conversion.Scope) error { + return autoConvert_v1_HTTPHeader_To_api_HTTPHeader(in, out, s) +} + +func autoConvert_v1_Handler_To_api_Handler(in *v1.Handler, out *api.Handler, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.Handler))(in) + } + // unable to generate simple pointer conversion for v1.ExecAction -> api.ExecAction + if in.Exec != nil { + out.Exec = new(api.ExecAction) + if err := Convert_v1_ExecAction_To_api_ExecAction(in.Exec, out.Exec, s); err != nil { + return err + } + } else { + out.Exec = nil + } + // unable to generate simple pointer conversion for v1.HTTPGetAction -> api.HTTPGetAction + if in.HTTPGet != nil { + out.HTTPGet = new(api.HTTPGetAction) + if err := Convert_v1_HTTPGetAction_To_api_HTTPGetAction(in.HTTPGet, out.HTTPGet, s); err != nil { + return err + } + } else { + out.HTTPGet = nil + } + // unable to generate simple pointer conversion for v1.TCPSocketAction -> api.TCPSocketAction + if in.TCPSocket != nil { + out.TCPSocket = new(api.TCPSocketAction) + if err := Convert_v1_TCPSocketAction_To_api_TCPSocketAction(in.TCPSocket, out.TCPSocket, s); err != nil { + return err + } + } else { + out.TCPSocket = nil + } + return nil +} + +func Convert_v1_Handler_To_api_Handler(in *v1.Handler, out *api.Handler, s conversion.Scope) error { + return autoConvert_v1_Handler_To_api_Handler(in, out, s) +} + +func autoConvert_v1_HostPathVolumeSource_To_api_HostPathVolumeSource(in *v1.HostPathVolumeSource, out *api.HostPathVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.HostPathVolumeSource))(in) + } + out.Path = in.Path + return nil +} + +func Convert_v1_HostPathVolumeSource_To_api_HostPathVolumeSource(in *v1.HostPathVolumeSource, out *api.HostPathVolumeSource, s conversion.Scope) error { + return autoConvert_v1_HostPathVolumeSource_To_api_HostPathVolumeSource(in, out, s) +} + +func autoConvert_v1_ISCSIVolumeSource_To_api_ISCSIVolumeSource(in *v1.ISCSIVolumeSource, out *api.ISCSIVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ISCSIVolumeSource))(in) + } + out.TargetPortal = in.TargetPortal + out.IQN = in.IQN + out.Lun = int(in.Lun) + out.ISCSIInterface = in.ISCSIInterface + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_ISCSIVolumeSource_To_api_ISCSIVolumeSource(in *v1.ISCSIVolumeSource, out *api.ISCSIVolumeSource, s conversion.Scope) error { + return autoConvert_v1_ISCSIVolumeSource_To_api_ISCSIVolumeSource(in, out, s) +} + +func autoConvert_v1_KeyToPath_To_api_KeyToPath(in *v1.KeyToPath, out *api.KeyToPath, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.KeyToPath))(in) + } + out.Key = in.Key + out.Path = in.Path + return nil +} + +func Convert_v1_KeyToPath_To_api_KeyToPath(in *v1.KeyToPath, out *api.KeyToPath, s conversion.Scope) error { + return autoConvert_v1_KeyToPath_To_api_KeyToPath(in, out, s) +} + +func autoConvert_v1_Lifecycle_To_api_Lifecycle(in *v1.Lifecycle, out *api.Lifecycle, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.Lifecycle))(in) + } + // unable to generate simple pointer conversion for v1.Handler -> api.Handler + if in.PostStart != nil { + out.PostStart = new(api.Handler) + if err := Convert_v1_Handler_To_api_Handler(in.PostStart, out.PostStart, s); err != nil { + return err + } + } else { + out.PostStart = nil + } + // unable to generate simple pointer conversion for v1.Handler -> api.Handler + if in.PreStop != nil { + out.PreStop = new(api.Handler) + if err := Convert_v1_Handler_To_api_Handler(in.PreStop, out.PreStop, s); err != nil { + return err + } + } else { + out.PreStop = nil + } + return nil +} + +func Convert_v1_Lifecycle_To_api_Lifecycle(in *v1.Lifecycle, out *api.Lifecycle, s conversion.Scope) error { + return autoConvert_v1_Lifecycle_To_api_Lifecycle(in, out, s) +} + +func autoConvert_v1_LocalObjectReference_To_api_LocalObjectReference(in *v1.LocalObjectReference, out *api.LocalObjectReference, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.LocalObjectReference))(in) + } + out.Name = in.Name + return nil +} + +func Convert_v1_LocalObjectReference_To_api_LocalObjectReference(in *v1.LocalObjectReference, out *api.LocalObjectReference, s conversion.Scope) error { + return autoConvert_v1_LocalObjectReference_To_api_LocalObjectReference(in, out, s) +} + +func autoConvert_v1_NFSVolumeSource_To_api_NFSVolumeSource(in *v1.NFSVolumeSource, out *api.NFSVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.NFSVolumeSource))(in) + } + out.Server = in.Server + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_NFSVolumeSource_To_api_NFSVolumeSource(in *v1.NFSVolumeSource, out *api.NFSVolumeSource, s conversion.Scope) error { + return autoConvert_v1_NFSVolumeSource_To_api_NFSVolumeSource(in, out, s) +} + +func autoConvert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(in *v1.ObjectFieldSelector, out *api.ObjectFieldSelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ObjectFieldSelector))(in) + } + out.APIVersion = in.APIVersion + out.FieldPath = in.FieldPath + return nil +} + +func Convert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(in *v1.ObjectFieldSelector, out *api.ObjectFieldSelector, s conversion.Scope) error { + return autoConvert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector(in, out, s) +} + +func autoConvert_v1_ObjectMeta_To_api_ObjectMeta(in *v1.ObjectMeta, out *api.ObjectMeta, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ObjectMeta))(in) + } + 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 := api.Convert_unversioned_Time_To_unversioned_Time(&in.CreationTimestamp, &out.CreationTimestamp, s); err != nil { + return err + } + // unable to generate simple pointer conversion for unversioned.Time -> unversioned.Time + if in.DeletionTimestamp != nil { + out.DeletionTimestamp = new(unversioned.Time) + if err := api.Convert_unversioned_Time_To_unversioned_Time(in.DeletionTimestamp, out.DeletionTimestamp, s); err != nil { + return err + } + } else { + out.DeletionTimestamp = nil + } + if in.DeletionGracePeriodSeconds != nil { + out.DeletionGracePeriodSeconds = new(int64) + *out.DeletionGracePeriodSeconds = *in.DeletionGracePeriodSeconds + } else { + out.DeletionGracePeriodSeconds = nil + } + if in.Labels != nil { + out.Labels = make(map[string]string) + for key, val := range in.Labels { + out.Labels[key] = val + } + } else { + out.Labels = nil + } + if in.Annotations != nil { + out.Annotations = make(map[string]string) + for key, val := range in.Annotations { + out.Annotations[key] = val + } + } else { + out.Annotations = nil + } + return nil +} + +func Convert_v1_ObjectMeta_To_api_ObjectMeta(in *v1.ObjectMeta, out *api.ObjectMeta, s conversion.Scope) error { + return autoConvert_v1_ObjectMeta_To_api_ObjectMeta(in, out, s) +} + +func autoConvert_v1_PersistentVolumeClaimVolumeSource_To_api_PersistentVolumeClaimVolumeSource(in *v1.PersistentVolumeClaimVolumeSource, out *api.PersistentVolumeClaimVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.PersistentVolumeClaimVolumeSource))(in) + } + out.ClaimName = in.ClaimName + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_PersistentVolumeClaimVolumeSource_To_api_PersistentVolumeClaimVolumeSource(in *v1.PersistentVolumeClaimVolumeSource, out *api.PersistentVolumeClaimVolumeSource, s conversion.Scope) error { + return autoConvert_v1_PersistentVolumeClaimVolumeSource_To_api_PersistentVolumeClaimVolumeSource(in, out, s) +} + +func autoConvert_v1_PodSpec_To_api_PodSpec(in *v1.PodSpec, out *api.PodSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.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.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 + } + out.RestartPolicy = api.RestartPolicy(in.RestartPolicy) + if in.TerminationGracePeriodSeconds != nil { + out.TerminationGracePeriodSeconds = new(int64) + *out.TerminationGracePeriodSeconds = *in.TerminationGracePeriodSeconds + } else { + out.TerminationGracePeriodSeconds = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + out.DNSPolicy = api.DNSPolicy(in.DNSPolicy) + if in.NodeSelector != nil { + out.NodeSelector = make(map[string]string) + for key, val := range in.NodeSelector { + out.NodeSelector[key] = val + } + } else { + out.NodeSelector = nil + } + out.ServiceAccountName = in.ServiceAccountName + // in.DeprecatedServiceAccount has no peer in out + out.NodeName = in.NodeName + // in.HostNetwork has no peer in out + // in.HostPID has no peer in out + // in.HostIPC has no peer in out + // unable to generate simple pointer conversion for v1.PodSecurityContext -> api.PodSecurityContext + if in.SecurityContext != nil { + if err := s.Convert(&in.SecurityContext, &out.SecurityContext, 0); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + 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 + } + return nil +} + +func autoConvert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in *v1.PodTemplateSpec, out *api.PodTemplateSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.PodTemplateSpec))(in) + } + if err := Convert_v1_ObjectMeta_To_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, s); err != nil { + return err + } + if err := Convert_v1_PodSpec_To_api_PodSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + return nil +} + +func Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in *v1.PodTemplateSpec, out *api.PodTemplateSpec, s conversion.Scope) error { + return autoConvert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in, out, s) +} + +func autoConvert_v1_Probe_To_api_Probe(in *v1.Probe, out *api.Probe, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.Probe))(in) + } + if err := Convert_v1_Handler_To_api_Handler(&in.Handler, &out.Handler, s); err != nil { + return err + } + out.InitialDelaySeconds = int(in.InitialDelaySeconds) + out.TimeoutSeconds = int(in.TimeoutSeconds) + out.PeriodSeconds = int(in.PeriodSeconds) + out.SuccessThreshold = int(in.SuccessThreshold) + out.FailureThreshold = int(in.FailureThreshold) + return nil +} + +func Convert_v1_Probe_To_api_Probe(in *v1.Probe, out *api.Probe, s conversion.Scope) error { + return autoConvert_v1_Probe_To_api_Probe(in, out, s) +} + +func autoConvert_v1_RBDVolumeSource_To_api_RBDVolumeSource(in *v1.RBDVolumeSource, out *api.RBDVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.RBDVolumeSource))(in) + } + if in.CephMonitors != nil { + out.CephMonitors = make([]string, len(in.CephMonitors)) + for i := range in.CephMonitors { + out.CephMonitors[i] = in.CephMonitors[i] + } + } else { + out.CephMonitors = nil + } + out.RBDImage = in.RBDImage + out.FSType = in.FSType + out.RBDPool = in.RBDPool + out.RadosUser = in.RadosUser + out.Keyring = in.Keyring + // unable to generate simple pointer conversion for v1.LocalObjectReference -> api.LocalObjectReference + if in.SecretRef != nil { + out.SecretRef = new(api.LocalObjectReference) + if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(in.SecretRef, out.SecretRef, s); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil +} + +func Convert_v1_RBDVolumeSource_To_api_RBDVolumeSource(in *v1.RBDVolumeSource, out *api.RBDVolumeSource, s conversion.Scope) error { + return autoConvert_v1_RBDVolumeSource_To_api_RBDVolumeSource(in, out, s) +} + +func autoConvert_v1_ResourceRequirements_To_api_ResourceRequirements(in *v1.ResourceRequirements, out *api.ResourceRequirements, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.ResourceRequirements))(in) + } + if in.Limits != nil { + out.Limits = make(api.ResourceList) + for key, val := range in.Limits { + newVal := resource.Quantity{} + if err := api.Convert_resource_Quantity_To_resource_Quantity(&val, &newVal, s); err != nil { + return err + } + out.Limits[api.ResourceName(key)] = newVal + } + } else { + out.Limits = nil + } + if in.Requests != nil { + out.Requests = make(api.ResourceList) + for key, val := range in.Requests { + newVal := resource.Quantity{} + if err := api.Convert_resource_Quantity_To_resource_Quantity(&val, &newVal, s); err != nil { + return err + } + out.Requests[api.ResourceName(key)] = newVal + } + } else { + out.Requests = nil + } + return nil +} + +func Convert_v1_ResourceRequirements_To_api_ResourceRequirements(in *v1.ResourceRequirements, out *api.ResourceRequirements, s conversion.Scope) error { + return autoConvert_v1_ResourceRequirements_To_api_ResourceRequirements(in, out, s) +} + +func autoConvert_v1_SELinuxOptions_To_api_SELinuxOptions(in *v1.SELinuxOptions, out *api.SELinuxOptions, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.SELinuxOptions))(in) + } + out.User = in.User + out.Role = in.Role + out.Type = in.Type + out.Level = in.Level + return nil +} + +func Convert_v1_SELinuxOptions_To_api_SELinuxOptions(in *v1.SELinuxOptions, out *api.SELinuxOptions, s conversion.Scope) error { + return autoConvert_v1_SELinuxOptions_To_api_SELinuxOptions(in, out, s) +} + +func autoConvert_v1_SecretKeySelector_To_api_SecretKeySelector(in *v1.SecretKeySelector, out *api.SecretKeySelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.SecretKeySelector))(in) + } + if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(&in.LocalObjectReference, &out.LocalObjectReference, s); err != nil { + return err + } + out.Key = in.Key + return nil +} + +func Convert_v1_SecretKeySelector_To_api_SecretKeySelector(in *v1.SecretKeySelector, out *api.SecretKeySelector, s conversion.Scope) error { + return autoConvert_v1_SecretKeySelector_To_api_SecretKeySelector(in, out, s) +} + +func autoConvert_v1_SecretVolumeSource_To_api_SecretVolumeSource(in *v1.SecretVolumeSource, out *api.SecretVolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.SecretVolumeSource))(in) + } + out.SecretName = in.SecretName + return nil +} + +func Convert_v1_SecretVolumeSource_To_api_SecretVolumeSource(in *v1.SecretVolumeSource, out *api.SecretVolumeSource, s conversion.Scope) error { + return autoConvert_v1_SecretVolumeSource_To_api_SecretVolumeSource(in, out, s) +} + +func autoConvert_v1_SecurityContext_To_api_SecurityContext(in *v1.SecurityContext, out *api.SecurityContext, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.SecurityContext))(in) + } + // unable to generate simple pointer conversion for v1.Capabilities -> api.Capabilities + if in.Capabilities != nil { + out.Capabilities = new(api.Capabilities) + if err := Convert_v1_Capabilities_To_api_Capabilities(in.Capabilities, out.Capabilities, s); err != nil { + return err + } + } else { + out.Capabilities = nil + } + if in.Privileged != nil { + out.Privileged = new(bool) + *out.Privileged = *in.Privileged + } else { + out.Privileged = nil + } + // unable to generate simple pointer conversion for v1.SELinuxOptions -> api.SELinuxOptions + if in.SELinuxOptions != nil { + out.SELinuxOptions = new(api.SELinuxOptions) + if err := Convert_v1_SELinuxOptions_To_api_SELinuxOptions(in.SELinuxOptions, out.SELinuxOptions, s); err != nil { + return err + } + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + out.RunAsUser = new(int64) + *out.RunAsUser = *in.RunAsUser + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + out.RunAsNonRoot = new(bool) + *out.RunAsNonRoot = *in.RunAsNonRoot + } else { + out.RunAsNonRoot = nil + } + if in.ReadOnlyRootFilesystem != nil { + out.ReadOnlyRootFilesystem = new(bool) + *out.ReadOnlyRootFilesystem = *in.ReadOnlyRootFilesystem + } else { + out.ReadOnlyRootFilesystem = nil + } + return nil +} + +func Convert_v1_SecurityContext_To_api_SecurityContext(in *v1.SecurityContext, out *api.SecurityContext, s conversion.Scope) error { + return autoConvert_v1_SecurityContext_To_api_SecurityContext(in, out, s) +} + +func autoConvert_v1_TCPSocketAction_To_api_TCPSocketAction(in *v1.TCPSocketAction, out *api.TCPSocketAction, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.TCPSocketAction))(in) + } + if err := api.Convert_intstr_IntOrString_To_intstr_IntOrString(&in.Port, &out.Port, s); err != nil { + return err + } + return nil +} + +func Convert_v1_TCPSocketAction_To_api_TCPSocketAction(in *v1.TCPSocketAction, out *api.TCPSocketAction, s conversion.Scope) error { + return autoConvert_v1_TCPSocketAction_To_api_TCPSocketAction(in, out, s) +} + +func autoConvert_v1_Volume_To_api_Volume(in *v1.Volume, out *api.Volume, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.Volume))(in) + } + out.Name = in.Name + if err := Convert_v1_VolumeSource_To_api_VolumeSource(&in.VolumeSource, &out.VolumeSource, s); err != nil { + return err + } + return nil +} + +func Convert_v1_Volume_To_api_Volume(in *v1.Volume, out *api.Volume, s conversion.Scope) error { + return autoConvert_v1_Volume_To_api_Volume(in, out, s) +} + +func autoConvert_v1_VolumeMount_To_api_VolumeMount(in *v1.VolumeMount, out *api.VolumeMount, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.VolumeMount))(in) + } + out.Name = in.Name + out.ReadOnly = in.ReadOnly + out.MountPath = in.MountPath + return nil +} + +func Convert_v1_VolumeMount_To_api_VolumeMount(in *v1.VolumeMount, out *api.VolumeMount, s conversion.Scope) error { + return autoConvert_v1_VolumeMount_To_api_VolumeMount(in, out, s) +} + +func autoConvert_v1_VolumeSource_To_api_VolumeSource(in *v1.VolumeSource, out *api.VolumeSource, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*v1.VolumeSource))(in) + } + // unable to generate simple pointer conversion for v1.HostPathVolumeSource -> api.HostPathVolumeSource + if in.HostPath != nil { + out.HostPath = new(api.HostPathVolumeSource) + if err := Convert_v1_HostPathVolumeSource_To_api_HostPathVolumeSource(in.HostPath, out.HostPath, s); err != nil { + return err + } + } else { + out.HostPath = nil + } + // unable to generate simple pointer conversion for v1.EmptyDirVolumeSource -> api.EmptyDirVolumeSource + if in.EmptyDir != nil { + out.EmptyDir = new(api.EmptyDirVolumeSource) + if err := Convert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource(in.EmptyDir, out.EmptyDir, s); err != nil { + return err + } + } else { + out.EmptyDir = nil + } + // unable to generate simple pointer conversion for v1.GCEPersistentDiskVolumeSource -> api.GCEPersistentDiskVolumeSource + if in.GCEPersistentDisk != nil { + out.GCEPersistentDisk = new(api.GCEPersistentDiskVolumeSource) + if err := Convert_v1_GCEPersistentDiskVolumeSource_To_api_GCEPersistentDiskVolumeSource(in.GCEPersistentDisk, out.GCEPersistentDisk, s); err != nil { + return err + } + } else { + out.GCEPersistentDisk = nil + } + // unable to generate simple pointer conversion for v1.AWSElasticBlockStoreVolumeSource -> api.AWSElasticBlockStoreVolumeSource + if in.AWSElasticBlockStore != nil { + out.AWSElasticBlockStore = new(api.AWSElasticBlockStoreVolumeSource) + if err := Convert_v1_AWSElasticBlockStoreVolumeSource_To_api_AWSElasticBlockStoreVolumeSource(in.AWSElasticBlockStore, out.AWSElasticBlockStore, s); err != nil { + return err + } + } else { + out.AWSElasticBlockStore = nil + } + // unable to generate simple pointer conversion for v1.GitRepoVolumeSource -> api.GitRepoVolumeSource + if in.GitRepo != nil { + out.GitRepo = new(api.GitRepoVolumeSource) + if err := Convert_v1_GitRepoVolumeSource_To_api_GitRepoVolumeSource(in.GitRepo, out.GitRepo, s); err != nil { + return err + } + } else { + out.GitRepo = nil + } + // unable to generate simple pointer conversion for v1.SecretVolumeSource -> api.SecretVolumeSource + if in.Secret != nil { + out.Secret = new(api.SecretVolumeSource) + if err := Convert_v1_SecretVolumeSource_To_api_SecretVolumeSource(in.Secret, out.Secret, s); err != nil { + return err + } + } else { + out.Secret = nil + } + // unable to generate simple pointer conversion for v1.NFSVolumeSource -> api.NFSVolumeSource + if in.NFS != nil { + out.NFS = new(api.NFSVolumeSource) + if err := Convert_v1_NFSVolumeSource_To_api_NFSVolumeSource(in.NFS, out.NFS, s); err != nil { + return err + } + } else { + out.NFS = nil + } + // unable to generate simple pointer conversion for v1.ISCSIVolumeSource -> api.ISCSIVolumeSource + if in.ISCSI != nil { + out.ISCSI = new(api.ISCSIVolumeSource) + if err := Convert_v1_ISCSIVolumeSource_To_api_ISCSIVolumeSource(in.ISCSI, out.ISCSI, s); err != nil { + return err + } + } else { + out.ISCSI = nil + } + // unable to generate simple pointer conversion for v1.GlusterfsVolumeSource -> api.GlusterfsVolumeSource + if in.Glusterfs != nil { + out.Glusterfs = new(api.GlusterfsVolumeSource) + if err := Convert_v1_GlusterfsVolumeSource_To_api_GlusterfsVolumeSource(in.Glusterfs, out.Glusterfs, s); err != nil { + return err + } + } else { + out.Glusterfs = nil + } + // unable to generate simple pointer conversion for v1.PersistentVolumeClaimVolumeSource -> api.PersistentVolumeClaimVolumeSource + if in.PersistentVolumeClaim != nil { + out.PersistentVolumeClaim = new(api.PersistentVolumeClaimVolumeSource) + if err := Convert_v1_PersistentVolumeClaimVolumeSource_To_api_PersistentVolumeClaimVolumeSource(in.PersistentVolumeClaim, out.PersistentVolumeClaim, s); err != nil { + return err + } + } else { + out.PersistentVolumeClaim = nil + } + // unable to generate simple pointer conversion for v1.RBDVolumeSource -> api.RBDVolumeSource + if in.RBD != nil { + out.RBD = new(api.RBDVolumeSource) + if err := Convert_v1_RBDVolumeSource_To_api_RBDVolumeSource(in.RBD, out.RBD, s); err != nil { + return err + } + } else { + out.RBD = nil + } + // unable to generate simple pointer conversion for v1.FlexVolumeSource -> api.FlexVolumeSource + if in.FlexVolume != nil { + out.FlexVolume = new(api.FlexVolumeSource) + if err := Convert_v1_FlexVolumeSource_To_api_FlexVolumeSource(in.FlexVolume, out.FlexVolume, s); err != nil { + return err + } + } else { + out.FlexVolume = nil + } + // unable to generate simple pointer conversion for v1.CinderVolumeSource -> api.CinderVolumeSource + if in.Cinder != nil { + out.Cinder = new(api.CinderVolumeSource) + if err := Convert_v1_CinderVolumeSource_To_api_CinderVolumeSource(in.Cinder, out.Cinder, s); err != nil { + return err + } + } else { + out.Cinder = nil + } + // unable to generate simple pointer conversion for v1.CephFSVolumeSource -> api.CephFSVolumeSource + if in.CephFS != nil { + out.CephFS = new(api.CephFSVolumeSource) + if err := Convert_v1_CephFSVolumeSource_To_api_CephFSVolumeSource(in.CephFS, out.CephFS, s); err != nil { + return err + } + } else { + out.CephFS = nil + } + // unable to generate simple pointer conversion for v1.FlockerVolumeSource -> api.FlockerVolumeSource + if in.Flocker != nil { + out.Flocker = new(api.FlockerVolumeSource) + if err := Convert_v1_FlockerVolumeSource_To_api_FlockerVolumeSource(in.Flocker, out.Flocker, s); err != nil { + return err + } + } else { + out.Flocker = nil + } + // unable to generate simple pointer conversion for v1.DownwardAPIVolumeSource -> api.DownwardAPIVolumeSource + if in.DownwardAPI != nil { + out.DownwardAPI = new(api.DownwardAPIVolumeSource) + if err := Convert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource(in.DownwardAPI, out.DownwardAPI, s); err != nil { + return err + } + } else { + out.DownwardAPI = nil + } + // unable to generate simple pointer conversion for v1.FCVolumeSource -> api.FCVolumeSource + if in.FC != nil { + out.FC = new(api.FCVolumeSource) + if err := Convert_v1_FCVolumeSource_To_api_FCVolumeSource(in.FC, out.FC, s); err != nil { + return err + } + } else { + out.FC = nil + } + // unable to generate simple pointer conversion for v1.AzureFileVolumeSource -> api.AzureFileVolumeSource + if in.AzureFile != nil { + out.AzureFile = new(api.AzureFileVolumeSource) + if err := Convert_v1_AzureFileVolumeSource_To_api_AzureFileVolumeSource(in.AzureFile, out.AzureFile, s); err != nil { + return err + } + } else { + out.AzureFile = nil + } + // unable to generate simple pointer conversion for v1.ConfigMapVolumeSource -> api.ConfigMapVolumeSource + if in.ConfigMap != nil { + out.ConfigMap = new(api.ConfigMapVolumeSource) + if err := Convert_v1_ConfigMapVolumeSource_To_api_ConfigMapVolumeSource(in.ConfigMap, out.ConfigMap, s); err != nil { + return err + } + } else { + out.ConfigMap = nil + } + return nil +} + +func Convert_v1_VolumeSource_To_api_VolumeSource(in *v1.VolumeSource, out *api.VolumeSource, s conversion.Scope) error { + return autoConvert_v1_VolumeSource_To_api_VolumeSource(in, out, s) +} + +func autoConvert_v1_Job_To_extensions_Job(in *Job, out *extensions.Job, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*Job))(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_JobSpec_To_extensions_JobSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1_JobStatus_To_extensions_JobStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_v1_Job_To_extensions_Job(in *Job, out *extensions.Job, s conversion.Scope) error { + return autoConvert_v1_Job_To_extensions_Job(in, out, s) +} + +func autoConvert_v1_JobCondition_To_extensions_JobCondition(in *JobCondition, out *extensions.JobCondition, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*JobCondition))(in) + } + out.Type = extensions.JobConditionType(in.Type) + out.Status = api.ConditionStatus(in.Status) + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.LastProbeTime, &out.LastProbeTime, s); err != nil { + return err + } + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.LastTransitionTime, &out.LastTransitionTime, s); err != nil { + return err + } + out.Reason = in.Reason + out.Message = in.Message + return nil +} + +func Convert_v1_JobCondition_To_extensions_JobCondition(in *JobCondition, out *extensions.JobCondition, s conversion.Scope) error { + return autoConvert_v1_JobCondition_To_extensions_JobCondition(in, out, s) +} + +func autoConvert_v1_JobList_To_extensions_JobList(in *JobList, out *extensions.JobList, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*JobList))(in) + } + 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 { + out.Items = make([]extensions.Job, len(in.Items)) + for i := range in.Items { + if err := Convert_v1_Job_To_extensions_Job(&in.Items[i], &out.Items[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_v1_JobList_To_extensions_JobList(in *JobList, out *extensions.JobList, s conversion.Scope) error { + return autoConvert_v1_JobList_To_extensions_JobList(in, out, s) +} + +func autoConvert_v1_JobSpec_To_extensions_JobSpec(in *JobSpec, out *extensions.JobSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*JobSpec))(in) + } + if in.Parallelism != nil { + out.Parallelism = new(int) + *out.Parallelism = int(*in.Parallelism) + } else { + out.Parallelism = nil + } + if in.Completions != nil { + out.Completions = new(int) + *out.Completions = int(*in.Completions) + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + // unable to generate simple pointer conversion for v1.LabelSelector -> unversioned.LabelSelector + if in.Selector != nil { + out.Selector = new(unversioned.LabelSelector) + if err := Convert_v1_LabelSelector_To_unversioned_LabelSelector(in.Selector, out.Selector, s); err != nil { + return err + } + } else { + out.Selector = nil + } + if in.ManualSelector != nil { + out.ManualSelector = new(bool) + *out.ManualSelector = *in.ManualSelector + } else { + out.ManualSelector = nil + } + if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + +func Convert_v1_JobSpec_To_extensions_JobSpec(in *JobSpec, out *extensions.JobSpec, s conversion.Scope) error { + return autoConvert_v1_JobSpec_To_extensions_JobSpec(in, out, s) +} + +func autoConvert_v1_JobStatus_To_extensions_JobStatus(in *JobStatus, out *extensions.JobStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*JobStatus))(in) + } + if in.Conditions != nil { + out.Conditions = make([]extensions.JobCondition, len(in.Conditions)) + for i := range in.Conditions { + if err := Convert_v1_JobCondition_To_extensions_JobCondition(&in.Conditions[i], &out.Conditions[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // unable to generate simple pointer conversion for unversioned.Time -> unversioned.Time + if in.StartTime != nil { + out.StartTime = new(unversioned.Time) + if err := api.Convert_unversioned_Time_To_unversioned_Time(in.StartTime, out.StartTime, s); err != nil { + return err + } + } else { + out.StartTime = nil + } + // unable to generate simple pointer conversion for unversioned.Time -> unversioned.Time + if in.CompletionTime != nil { + out.CompletionTime = new(unversioned.Time) + if err := api.Convert_unversioned_Time_To_unversioned_Time(in.CompletionTime, out.CompletionTime, s); err != nil { + return err + } + } else { + out.CompletionTime = nil + } + out.Active = int(in.Active) + out.Succeeded = int(in.Succeeded) + out.Failed = int(in.Failed) + return nil +} + +func Convert_v1_JobStatus_To_extensions_JobStatus(in *JobStatus, out *extensions.JobStatus, s conversion.Scope) error { + return autoConvert_v1_JobStatus_To_extensions_JobStatus(in, out, s) +} + +func autoConvert_v1_LabelSelector_To_unversioned_LabelSelector(in *LabelSelector, out *unversioned.LabelSelector, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*LabelSelector))(in) + } + if in.MatchLabels != nil { + out.MatchLabels = make(map[string]string) + for key, val := range in.MatchLabels { + out.MatchLabels[key] = val + } + } else { + out.MatchLabels = nil + } + if in.MatchExpressions != nil { + out.MatchExpressions = make([]unversioned.LabelSelectorRequirement, len(in.MatchExpressions)) + for i := range in.MatchExpressions { + if err := Convert_v1_LabelSelectorRequirement_To_unversioned_LabelSelectorRequirement(&in.MatchExpressions[i], &out.MatchExpressions[i], s); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil +} + +func Convert_v1_LabelSelector_To_unversioned_LabelSelector(in *LabelSelector, out *unversioned.LabelSelector, s conversion.Scope) error { + return autoConvert_v1_LabelSelector_To_unversioned_LabelSelector(in, out, s) +} + +func autoConvert_v1_LabelSelectorRequirement_To_unversioned_LabelSelectorRequirement(in *LabelSelectorRequirement, out *unversioned.LabelSelectorRequirement, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*LabelSelectorRequirement))(in) + } + out.Key = in.Key + out.Operator = unversioned.LabelSelectorOperator(in.Operator) + if in.Values != nil { + out.Values = make([]string, len(in.Values)) + for i := range in.Values { + out.Values[i] = in.Values[i] + } + } else { + out.Values = nil + } + return nil +} + +func Convert_v1_LabelSelectorRequirement_To_unversioned_LabelSelectorRequirement(in *LabelSelectorRequirement, out *unversioned.LabelSelectorRequirement, s conversion.Scope) error { + return autoConvert_v1_LabelSelectorRequirement_To_unversioned_LabelSelectorRequirement(in, out, s) +} + +func autoConvert_extensions_Job_To_v1_Job(in *extensions.Job, out *Job, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.Job))(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_JobSpec_To_v1_JobSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_extensions_JobStatus_To_v1_JobStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_extensions_Job_To_v1_Job(in *extensions.Job, out *Job, s conversion.Scope) error { + return autoConvert_extensions_Job_To_v1_Job(in, out, s) +} + +func autoConvert_extensions_JobCondition_To_v1_JobCondition(in *extensions.JobCondition, out *JobCondition, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.JobCondition))(in) + } + out.Type = JobConditionType(in.Type) + out.Status = v1.ConditionStatus(in.Status) + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.LastProbeTime, &out.LastProbeTime, s); err != nil { + return err + } + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.LastTransitionTime, &out.LastTransitionTime, s); err != nil { + return err + } + out.Reason = in.Reason + out.Message = in.Message + return nil +} + +func Convert_extensions_JobCondition_To_v1_JobCondition(in *extensions.JobCondition, out *JobCondition, s conversion.Scope) error { + return autoConvert_extensions_JobCondition_To_v1_JobCondition(in, out, s) +} + +func autoConvert_extensions_JobList_To_v1_JobList(in *extensions.JobList, out *JobList, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.JobList))(in) + } + 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 { + out.Items = make([]Job, len(in.Items)) + for i := range in.Items { + if err := Convert_extensions_Job_To_v1_Job(&in.Items[i], &out.Items[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_extensions_JobList_To_v1_JobList(in *extensions.JobList, out *JobList, s conversion.Scope) error { + return autoConvert_extensions_JobList_To_v1_JobList(in, out, s) +} + +func autoConvert_extensions_JobSpec_To_v1_JobSpec(in *extensions.JobSpec, out *JobSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.JobSpec))(in) + } + if in.Parallelism != nil { + out.Parallelism = new(int32) + *out.Parallelism = int32(*in.Parallelism) + } else { + out.Parallelism = nil + } + if in.Completions != nil { + out.Completions = new(int32) + *out.Completions = int32(*in.Completions) + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + // unable to generate simple pointer conversion for unversioned.LabelSelector -> v1.LabelSelector + if in.Selector != nil { + out.Selector = new(LabelSelector) + if err := Convert_unversioned_LabelSelector_To_v1_LabelSelector(in.Selector, out.Selector, s); err != nil { + return err + } + } else { + out.Selector = nil + } + if in.ManualSelector != nil { + out.ManualSelector = new(bool) + *out.ManualSelector = *in.ManualSelector + } else { + out.ManualSelector = nil + } + if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + +func Convert_extensions_JobSpec_To_v1_JobSpec(in *extensions.JobSpec, out *JobSpec, s conversion.Scope) error { + return autoConvert_extensions_JobSpec_To_v1_JobSpec(in, out, s) +} + +func autoConvert_extensions_JobStatus_To_v1_JobStatus(in *extensions.JobStatus, out *JobStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.JobStatus))(in) + } + if in.Conditions != nil { + out.Conditions = make([]JobCondition, len(in.Conditions)) + for i := range in.Conditions { + if err := Convert_extensions_JobCondition_To_v1_JobCondition(&in.Conditions[i], &out.Conditions[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + // unable to generate simple pointer conversion for unversioned.Time -> unversioned.Time + if in.StartTime != nil { + out.StartTime = new(unversioned.Time) + if err := api.Convert_unversioned_Time_To_unversioned_Time(in.StartTime, out.StartTime, s); err != nil { + return err + } + } else { + out.StartTime = nil + } + // unable to generate simple pointer conversion for unversioned.Time -> unversioned.Time + if in.CompletionTime != nil { + out.CompletionTime = new(unversioned.Time) + if err := api.Convert_unversioned_Time_To_unversioned_Time(in.CompletionTime, out.CompletionTime, s); err != nil { + return err + } + } else { + out.CompletionTime = nil + } + out.Active = int32(in.Active) + out.Succeeded = int32(in.Succeeded) + out.Failed = int32(in.Failed) + return nil +} + +func Convert_extensions_JobStatus_To_v1_JobStatus(in *extensions.JobStatus, out *JobStatus, s conversion.Scope) error { + return autoConvert_extensions_JobStatus_To_v1_JobStatus(in, out, s) +} + +func init() { + err := api.Scheme.AddGeneratedConversionFuncs( + autoConvert_api_AWSElasticBlockStoreVolumeSource_To_v1_AWSElasticBlockStoreVolumeSource, + autoConvert_api_AzureFileVolumeSource_To_v1_AzureFileVolumeSource, + autoConvert_api_Capabilities_To_v1_Capabilities, + autoConvert_api_CephFSVolumeSource_To_v1_CephFSVolumeSource, + autoConvert_api_CinderVolumeSource_To_v1_CinderVolumeSource, + autoConvert_api_ConfigMapKeySelector_To_v1_ConfigMapKeySelector, + autoConvert_api_ConfigMapVolumeSource_To_v1_ConfigMapVolumeSource, + autoConvert_api_ContainerPort_To_v1_ContainerPort, + autoConvert_api_Container_To_v1_Container, + autoConvert_api_DownwardAPIVolumeFile_To_v1_DownwardAPIVolumeFile, + autoConvert_api_DownwardAPIVolumeSource_To_v1_DownwardAPIVolumeSource, + autoConvert_api_EmptyDirVolumeSource_To_v1_EmptyDirVolumeSource, + autoConvert_api_EnvVarSource_To_v1_EnvVarSource, + autoConvert_api_EnvVar_To_v1_EnvVar, + autoConvert_api_ExecAction_To_v1_ExecAction, + autoConvert_api_FCVolumeSource_To_v1_FCVolumeSource, + autoConvert_api_FlexVolumeSource_To_v1_FlexVolumeSource, + autoConvert_api_FlockerVolumeSource_To_v1_FlockerVolumeSource, + autoConvert_api_GCEPersistentDiskVolumeSource_To_v1_GCEPersistentDiskVolumeSource, + autoConvert_api_GitRepoVolumeSource_To_v1_GitRepoVolumeSource, + autoConvert_api_GlusterfsVolumeSource_To_v1_GlusterfsVolumeSource, + autoConvert_api_HTTPGetAction_To_v1_HTTPGetAction, + autoConvert_api_HTTPHeader_To_v1_HTTPHeader, + autoConvert_api_Handler_To_v1_Handler, + autoConvert_api_HostPathVolumeSource_To_v1_HostPathVolumeSource, + autoConvert_api_ISCSIVolumeSource_To_v1_ISCSIVolumeSource, + autoConvert_api_KeyToPath_To_v1_KeyToPath, + autoConvert_api_Lifecycle_To_v1_Lifecycle, + autoConvert_api_LocalObjectReference_To_v1_LocalObjectReference, + autoConvert_api_NFSVolumeSource_To_v1_NFSVolumeSource, + autoConvert_api_ObjectFieldSelector_To_v1_ObjectFieldSelector, + autoConvert_api_ObjectMeta_To_v1_ObjectMeta, + autoConvert_api_PersistentVolumeClaimVolumeSource_To_v1_PersistentVolumeClaimVolumeSource, + autoConvert_api_PodSpec_To_v1_PodSpec, + autoConvert_api_PodTemplateSpec_To_v1_PodTemplateSpec, + autoConvert_api_Probe_To_v1_Probe, + autoConvert_api_RBDVolumeSource_To_v1_RBDVolumeSource, + autoConvert_api_ResourceRequirements_To_v1_ResourceRequirements, + autoConvert_api_SELinuxOptions_To_v1_SELinuxOptions, + autoConvert_api_SecretKeySelector_To_v1_SecretKeySelector, + autoConvert_api_SecretVolumeSource_To_v1_SecretVolumeSource, + autoConvert_api_SecurityContext_To_v1_SecurityContext, + autoConvert_api_TCPSocketAction_To_v1_TCPSocketAction, + autoConvert_api_VolumeMount_To_v1_VolumeMount, + autoConvert_api_VolumeSource_To_v1_VolumeSource, + autoConvert_api_Volume_To_v1_Volume, + autoConvert_extensions_JobCondition_To_v1_JobCondition, + autoConvert_extensions_JobList_To_v1_JobList, + autoConvert_extensions_JobSpec_To_v1_JobSpec, + autoConvert_extensions_JobStatus_To_v1_JobStatus, + autoConvert_extensions_Job_To_v1_Job, + autoConvert_unversioned_LabelSelectorRequirement_To_v1_LabelSelectorRequirement, + autoConvert_unversioned_LabelSelector_To_v1_LabelSelector, + autoConvert_v1_AWSElasticBlockStoreVolumeSource_To_api_AWSElasticBlockStoreVolumeSource, + autoConvert_v1_AzureFileVolumeSource_To_api_AzureFileVolumeSource, + autoConvert_v1_Capabilities_To_api_Capabilities, + autoConvert_v1_CephFSVolumeSource_To_api_CephFSVolumeSource, + autoConvert_v1_CinderVolumeSource_To_api_CinderVolumeSource, + autoConvert_v1_ConfigMapKeySelector_To_api_ConfigMapKeySelector, + autoConvert_v1_ConfigMapVolumeSource_To_api_ConfigMapVolumeSource, + autoConvert_v1_ContainerPort_To_api_ContainerPort, + autoConvert_v1_Container_To_api_Container, + autoConvert_v1_DownwardAPIVolumeFile_To_api_DownwardAPIVolumeFile, + autoConvert_v1_DownwardAPIVolumeSource_To_api_DownwardAPIVolumeSource, + autoConvert_v1_EmptyDirVolumeSource_To_api_EmptyDirVolumeSource, + autoConvert_v1_EnvVarSource_To_api_EnvVarSource, + autoConvert_v1_EnvVar_To_api_EnvVar, + autoConvert_v1_ExecAction_To_api_ExecAction, + autoConvert_v1_FCVolumeSource_To_api_FCVolumeSource, + autoConvert_v1_FlexVolumeSource_To_api_FlexVolumeSource, + autoConvert_v1_FlockerVolumeSource_To_api_FlockerVolumeSource, + autoConvert_v1_GCEPersistentDiskVolumeSource_To_api_GCEPersistentDiskVolumeSource, + autoConvert_v1_GitRepoVolumeSource_To_api_GitRepoVolumeSource, + autoConvert_v1_GlusterfsVolumeSource_To_api_GlusterfsVolumeSource, + autoConvert_v1_HTTPGetAction_To_api_HTTPGetAction, + autoConvert_v1_HTTPHeader_To_api_HTTPHeader, + autoConvert_v1_Handler_To_api_Handler, + autoConvert_v1_HostPathVolumeSource_To_api_HostPathVolumeSource, + autoConvert_v1_ISCSIVolumeSource_To_api_ISCSIVolumeSource, + autoConvert_v1_JobCondition_To_extensions_JobCondition, + autoConvert_v1_JobList_To_extensions_JobList, + autoConvert_v1_JobSpec_To_extensions_JobSpec, + autoConvert_v1_JobStatus_To_extensions_JobStatus, + autoConvert_v1_Job_To_extensions_Job, + autoConvert_v1_KeyToPath_To_api_KeyToPath, + autoConvert_v1_LabelSelectorRequirement_To_unversioned_LabelSelectorRequirement, + autoConvert_v1_LabelSelector_To_unversioned_LabelSelector, + autoConvert_v1_Lifecycle_To_api_Lifecycle, + autoConvert_v1_LocalObjectReference_To_api_LocalObjectReference, + autoConvert_v1_NFSVolumeSource_To_api_NFSVolumeSource, + autoConvert_v1_ObjectFieldSelector_To_api_ObjectFieldSelector, + autoConvert_v1_ObjectMeta_To_api_ObjectMeta, + autoConvert_v1_PersistentVolumeClaimVolumeSource_To_api_PersistentVolumeClaimVolumeSource, + autoConvert_v1_PodSpec_To_api_PodSpec, + autoConvert_v1_PodTemplateSpec_To_api_PodTemplateSpec, + autoConvert_v1_Probe_To_api_Probe, + autoConvert_v1_RBDVolumeSource_To_api_RBDVolumeSource, + autoConvert_v1_ResourceRequirements_To_api_ResourceRequirements, + autoConvert_v1_SELinuxOptions_To_api_SELinuxOptions, + autoConvert_v1_SecretKeySelector_To_api_SecretKeySelector, + autoConvert_v1_SecretVolumeSource_To_api_SecretVolumeSource, + autoConvert_v1_SecurityContext_To_api_SecurityContext, + autoConvert_v1_TCPSocketAction_To_api_TCPSocketAction, + autoConvert_v1_VolumeMount_To_api_VolumeMount, + autoConvert_v1_VolumeSource_To_api_VolumeSource, + autoConvert_v1_Volume_To_api_Volume, + ) + if err != nil { + // If one of the conversion functions is malformed, detect it immediately. + panic(err) + } +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/deep_copy_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/deep_copy_generated.go new file mode 100644 index 000000000..3ddbd6d2b --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/deep_copy_generated.go @@ -0,0 +1,1233 @@ +/* +Copyright 2015 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. +*/ + +// DO NOT EDIT. THIS FILE IS AUTO-GENERATED BY $KUBEROOT/hack/update-generated-deep-copies.sh. + +package v1 + +import ( + time "time" + + 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" + inf "speter.net/go/exp/math/dec/inf" +) + +func deepCopy_resource_Quantity(in resource.Quantity, out *resource.Quantity, c *conversion.Cloner) error { + if in.Amount != nil { + if newVal, err := c.DeepCopy(in.Amount); err != nil { + return err + } else { + out.Amount = newVal.(*inf.Dec) + } + } else { + out.Amount = nil + } + out.Format = in.Format + return nil +} + +func deepCopy_unversioned_ListMeta(in unversioned.ListMeta, out *unversioned.ListMeta, c *conversion.Cloner) error { + out.SelfLink = in.SelfLink + out.ResourceVersion = in.ResourceVersion + return nil +} + +func deepCopy_unversioned_Time(in unversioned.Time, out *unversioned.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_TypeMeta(in unversioned.TypeMeta, out *unversioned.TypeMeta, c *conversion.Cloner) error { + out.Kind = in.Kind + out.APIVersion = in.APIVersion + return nil +} + +func deepCopy_v1_AWSElasticBlockStoreVolumeSource(in v1.AWSElasticBlockStoreVolumeSource, out *v1.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_AzureFileVolumeSource(in v1.AzureFileVolumeSource, out *v1.AzureFileVolumeSource, c *conversion.Cloner) error { + out.SecretName = in.SecretName + out.ShareName = in.ShareName + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_Capabilities(in v1.Capabilities, out *v1.Capabilities, c *conversion.Cloner) error { + if in.Add != nil { + out.Add = make([]v1.Capability, len(in.Add)) + for i := range in.Add { + out.Add[i] = in.Add[i] + } + } else { + out.Add = nil + } + if in.Drop != nil { + out.Drop = make([]v1.Capability, len(in.Drop)) + for i := range in.Drop { + out.Drop[i] = in.Drop[i] + } + } else { + out.Drop = nil + } + return nil +} + +func deepCopy_v1_CephFSVolumeSource(in v1.CephFSVolumeSource, out *v1.CephFSVolumeSource, c *conversion.Cloner) error { + if in.Monitors != nil { + out.Monitors = make([]string, len(in.Monitors)) + for i := range in.Monitors { + out.Monitors[i] = in.Monitors[i] + } + } else { + out.Monitors = nil + } + out.Path = in.Path + out.User = in.User + out.SecretFile = in.SecretFile + if in.SecretRef != nil { + out.SecretRef = new(v1.LocalObjectReference) + if err := deepCopy_v1_LocalObjectReference(*in.SecretRef, out.SecretRef, c); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_CinderVolumeSource(in v1.CinderVolumeSource, out *v1.CinderVolumeSource, c *conversion.Cloner) error { + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_ConfigMapKeySelector(in v1.ConfigMapKeySelector, out *v1.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_ConfigMapVolumeSource(in v1.ConfigMapVolumeSource, out *v1.ConfigMapVolumeSource, c *conversion.Cloner) error { + if err := deepCopy_v1_LocalObjectReference(in.LocalObjectReference, &out.LocalObjectReference, c); err != nil { + return err + } + if in.Items != nil { + out.Items = make([]v1.KeyToPath, len(in.Items)) + for i := range in.Items { + if err := deepCopy_v1_KeyToPath(in.Items[i], &out.Items[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func deepCopy_v1_Container(in v1.Container, out *v1.Container, c *conversion.Cloner) error { + out.Name = in.Name + out.Image = in.Image + if in.Command != nil { + out.Command = make([]string, len(in.Command)) + for i := range in.Command { + out.Command[i] = in.Command[i] + } + } else { + out.Command = nil + } + if in.Args != nil { + out.Args = make([]string, len(in.Args)) + for i := range in.Args { + out.Args[i] = in.Args[i] + } + } else { + out.Args = nil + } + out.WorkingDir = in.WorkingDir + if in.Ports != nil { + out.Ports = make([]v1.ContainerPort, len(in.Ports)) + for i := range in.Ports { + if err := deepCopy_v1_ContainerPort(in.Ports[i], &out.Ports[i], c); err != nil { + return err + } + } + } else { + out.Ports = nil + } + if in.Env != nil { + out.Env = make([]v1.EnvVar, len(in.Env)) + for i := range in.Env { + if err := deepCopy_v1_EnvVar(in.Env[i], &out.Env[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 { + out.VolumeMounts = make([]v1.VolumeMount, len(in.VolumeMounts)) + for i := range in.VolumeMounts { + if err := deepCopy_v1_VolumeMount(in.VolumeMounts[i], &out.VolumeMounts[i], c); err != nil { + return err + } + } + } else { + out.VolumeMounts = nil + } + if in.LivenessProbe != nil { + out.LivenessProbe = new(v1.Probe) + if err := deepCopy_v1_Probe(*in.LivenessProbe, out.LivenessProbe, c); err != nil { + return err + } + } else { + out.LivenessProbe = nil + } + if in.ReadinessProbe != nil { + out.ReadinessProbe = new(v1.Probe) + if err := deepCopy_v1_Probe(*in.ReadinessProbe, out.ReadinessProbe, c); err != nil { + return err + } + } else { + out.ReadinessProbe = nil + } + if in.Lifecycle != nil { + out.Lifecycle = new(v1.Lifecycle) + if err := deepCopy_v1_Lifecycle(*in.Lifecycle, out.Lifecycle, c); err != nil { + return err + } + } else { + out.Lifecycle = nil + } + out.TerminationMessagePath = in.TerminationMessagePath + out.ImagePullPolicy = in.ImagePullPolicy + if in.SecurityContext != nil { + out.SecurityContext = new(v1.SecurityContext) + if err := deepCopy_v1_SecurityContext(*in.SecurityContext, out.SecurityContext, 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_ContainerPort(in v1.ContainerPort, out *v1.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_DownwardAPIVolumeFile(in v1.DownwardAPIVolumeFile, out *v1.DownwardAPIVolumeFile, c *conversion.Cloner) error { + out.Path = in.Path + if err := deepCopy_v1_ObjectFieldSelector(in.FieldRef, &out.FieldRef, c); err != nil { + return err + } + return nil +} + +func deepCopy_v1_DownwardAPIVolumeSource(in v1.DownwardAPIVolumeSource, out *v1.DownwardAPIVolumeSource, c *conversion.Cloner) error { + if in.Items != nil { + out.Items = make([]v1.DownwardAPIVolumeFile, len(in.Items)) + for i := range in.Items { + if err := deepCopy_v1_DownwardAPIVolumeFile(in.Items[i], &out.Items[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func deepCopy_v1_EmptyDirVolumeSource(in v1.EmptyDirVolumeSource, out *v1.EmptyDirVolumeSource, c *conversion.Cloner) error { + out.Medium = in.Medium + return nil +} + +func deepCopy_v1_EnvVar(in v1.EnvVar, out *v1.EnvVar, c *conversion.Cloner) error { + out.Name = in.Name + out.Value = in.Value + if in.ValueFrom != nil { + out.ValueFrom = new(v1.EnvVarSource) + if err := deepCopy_v1_EnvVarSource(*in.ValueFrom, out.ValueFrom, c); err != nil { + return err + } + } else { + out.ValueFrom = nil + } + return nil +} + +func deepCopy_v1_EnvVarSource(in v1.EnvVarSource, out *v1.EnvVarSource, c *conversion.Cloner) error { + if in.FieldRef != nil { + out.FieldRef = new(v1.ObjectFieldSelector) + if err := deepCopy_v1_ObjectFieldSelector(*in.FieldRef, out.FieldRef, c); err != nil { + return err + } + } else { + out.FieldRef = nil + } + if in.ConfigMapKeyRef != nil { + out.ConfigMapKeyRef = new(v1.ConfigMapKeySelector) + if err := deepCopy_v1_ConfigMapKeySelector(*in.ConfigMapKeyRef, out.ConfigMapKeyRef, c); err != nil { + return err + } + } else { + out.ConfigMapKeyRef = nil + } + if in.SecretKeyRef != nil { + out.SecretKeyRef = new(v1.SecretKeySelector) + if err := deepCopy_v1_SecretKeySelector(*in.SecretKeyRef, out.SecretKeyRef, c); err != nil { + return err + } + } else { + out.SecretKeyRef = nil + } + return nil +} + +func deepCopy_v1_ExecAction(in v1.ExecAction, out *v1.ExecAction, c *conversion.Cloner) error { + if in.Command != nil { + out.Command = make([]string, len(in.Command)) + for i := range in.Command { + out.Command[i] = in.Command[i] + } + } else { + out.Command = nil + } + return nil +} + +func deepCopy_v1_FCVolumeSource(in v1.FCVolumeSource, out *v1.FCVolumeSource, c *conversion.Cloner) error { + if in.TargetWWNs != nil { + out.TargetWWNs = make([]string, len(in.TargetWWNs)) + for i := range in.TargetWWNs { + out.TargetWWNs[i] = in.TargetWWNs[i] + } + } else { + out.TargetWWNs = nil + } + if in.Lun != nil { + out.Lun = new(int32) + *out.Lun = *in.Lun + } else { + out.Lun = nil + } + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_FlexVolumeSource(in v1.FlexVolumeSource, out *v1.FlexVolumeSource, c *conversion.Cloner) error { + out.Driver = in.Driver + out.FSType = in.FSType + if in.SecretRef != nil { + out.SecretRef = new(v1.LocalObjectReference) + if err := deepCopy_v1_LocalObjectReference(*in.SecretRef, out.SecretRef, c); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + if in.Options != nil { + out.Options = make(map[string]string) + for key, val := range in.Options { + out.Options[key] = val + } + } else { + out.Options = nil + } + return nil +} + +func deepCopy_v1_FlockerVolumeSource(in v1.FlockerVolumeSource, out *v1.FlockerVolumeSource, c *conversion.Cloner) error { + out.DatasetName = in.DatasetName + return nil +} + +func deepCopy_v1_GCEPersistentDiskVolumeSource(in v1.GCEPersistentDiskVolumeSource, out *v1.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 v1.GitRepoVolumeSource, out *v1.GitRepoVolumeSource, c *conversion.Cloner) error { + out.Repository = in.Repository + out.Revision = in.Revision + out.Directory = in.Directory + return nil +} + +func deepCopy_v1_GlusterfsVolumeSource(in v1.GlusterfsVolumeSource, out *v1.GlusterfsVolumeSource, c *conversion.Cloner) error { + out.EndpointsName = in.EndpointsName + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_HTTPGetAction(in v1.HTTPGetAction, out *v1.HTTPGetAction, c *conversion.Cloner) error { + out.Path = in.Path + if err := deepCopy_intstr_IntOrString(in.Port, &out.Port, c); err != nil { + return err + } + out.Host = in.Host + out.Scheme = in.Scheme + if in.HTTPHeaders != nil { + out.HTTPHeaders = make([]v1.HTTPHeader, len(in.HTTPHeaders)) + for i := range in.HTTPHeaders { + if err := deepCopy_v1_HTTPHeader(in.HTTPHeaders[i], &out.HTTPHeaders[i], c); err != nil { + return err + } + } + } else { + out.HTTPHeaders = nil + } + return nil +} + +func deepCopy_v1_HTTPHeader(in v1.HTTPHeader, out *v1.HTTPHeader, c *conversion.Cloner) error { + out.Name = in.Name + out.Value = in.Value + return nil +} + +func deepCopy_v1_Handler(in v1.Handler, out *v1.Handler, c *conversion.Cloner) error { + if in.Exec != nil { + out.Exec = new(v1.ExecAction) + if err := deepCopy_v1_ExecAction(*in.Exec, out.Exec, c); err != nil { + return err + } + } else { + out.Exec = nil + } + if in.HTTPGet != nil { + out.HTTPGet = new(v1.HTTPGetAction) + if err := deepCopy_v1_HTTPGetAction(*in.HTTPGet, out.HTTPGet, c); err != nil { + return err + } + } else { + out.HTTPGet = nil + } + if in.TCPSocket != nil { + out.TCPSocket = new(v1.TCPSocketAction) + if err := deepCopy_v1_TCPSocketAction(*in.TCPSocket, out.TCPSocket, c); err != nil { + return err + } + } else { + out.TCPSocket = nil + } + return nil +} + +func deepCopy_v1_HostPathVolumeSource(in v1.HostPathVolumeSource, out *v1.HostPathVolumeSource, c *conversion.Cloner) error { + out.Path = in.Path + return nil +} + +func deepCopy_v1_ISCSIVolumeSource(in v1.ISCSIVolumeSource, out *v1.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 v1.KeyToPath, out *v1.KeyToPath, c *conversion.Cloner) error { + out.Key = in.Key + out.Path = in.Path + return nil +} + +func deepCopy_v1_Lifecycle(in v1.Lifecycle, out *v1.Lifecycle, c *conversion.Cloner) error { + if in.PostStart != nil { + out.PostStart = new(v1.Handler) + if err := deepCopy_v1_Handler(*in.PostStart, out.PostStart, c); err != nil { + return err + } + } else { + out.PostStart = nil + } + if in.PreStop != nil { + out.PreStop = new(v1.Handler) + if err := deepCopy_v1_Handler(*in.PreStop, out.PreStop, c); err != nil { + return err + } + } else { + out.PreStop = nil + } + return nil +} + +func deepCopy_v1_LocalObjectReference(in v1.LocalObjectReference, out *v1.LocalObjectReference, c *conversion.Cloner) error { + out.Name = in.Name + return nil +} + +func deepCopy_v1_NFSVolumeSource(in v1.NFSVolumeSource, out *v1.NFSVolumeSource, c *conversion.Cloner) error { + out.Server = in.Server + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_ObjectFieldSelector(in v1.ObjectFieldSelector, out *v1.ObjectFieldSelector, c *conversion.Cloner) error { + out.APIVersion = in.APIVersion + out.FieldPath = in.FieldPath + return nil +} + +func deepCopy_v1_ObjectMeta(in v1.ObjectMeta, out *v1.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 := deepCopy_unversioned_Time(in.CreationTimestamp, &out.CreationTimestamp, c); err != nil { + return err + } + if in.DeletionTimestamp != nil { + out.DeletionTimestamp = new(unversioned.Time) + if err := deepCopy_unversioned_Time(*in.DeletionTimestamp, out.DeletionTimestamp, c); err != nil { + return err + } + } else { + out.DeletionTimestamp = nil + } + if in.DeletionGracePeriodSeconds != nil { + out.DeletionGracePeriodSeconds = new(int64) + *out.DeletionGracePeriodSeconds = *in.DeletionGracePeriodSeconds + } else { + out.DeletionGracePeriodSeconds = nil + } + if in.Labels != nil { + out.Labels = make(map[string]string) + for key, val := range in.Labels { + out.Labels[key] = val + } + } else { + out.Labels = nil + } + if in.Annotations != nil { + out.Annotations = make(map[string]string) + for key, val := range in.Annotations { + out.Annotations[key] = val + } + } else { + out.Annotations = nil + } + return nil +} + +func deepCopy_v1_PersistentVolumeClaimVolumeSource(in v1.PersistentVolumeClaimVolumeSource, out *v1.PersistentVolumeClaimVolumeSource, c *conversion.Cloner) error { + out.ClaimName = in.ClaimName + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_PodSecurityContext(in v1.PodSecurityContext, out *v1.PodSecurityContext, c *conversion.Cloner) error { + if in.SELinuxOptions != nil { + out.SELinuxOptions = new(v1.SELinuxOptions) + if err := deepCopy_v1_SELinuxOptions(*in.SELinuxOptions, out.SELinuxOptions, c); err != nil { + return err + } + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + out.RunAsUser = new(int64) + *out.RunAsUser = *in.RunAsUser + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + out.RunAsNonRoot = new(bool) + *out.RunAsNonRoot = *in.RunAsNonRoot + } else { + out.RunAsNonRoot = nil + } + if in.SupplementalGroups != nil { + out.SupplementalGroups = make([]int64, len(in.SupplementalGroups)) + for i := range in.SupplementalGroups { + out.SupplementalGroups[i] = in.SupplementalGroups[i] + } + } else { + out.SupplementalGroups = nil + } + if in.FSGroup != nil { + out.FSGroup = new(int64) + *out.FSGroup = *in.FSGroup + } else { + out.FSGroup = nil + } + return nil +} + +func deepCopy_v1_PodSpec(in v1.PodSpec, out *v1.PodSpec, c *conversion.Cloner) error { + if in.Volumes != nil { + out.Volumes = make([]v1.Volume, len(in.Volumes)) + for i := range in.Volumes { + if err := deepCopy_v1_Volume(in.Volumes[i], &out.Volumes[i], c); err != nil { + return err + } + } + } else { + out.Volumes = nil + } + if in.Containers != nil { + out.Containers = make([]v1.Container, len(in.Containers)) + for i := range in.Containers { + if err := deepCopy_v1_Container(in.Containers[i], &out.Containers[i], c); err != nil { + return err + } + } + } else { + out.Containers = nil + } + out.RestartPolicy = in.RestartPolicy + if in.TerminationGracePeriodSeconds != nil { + out.TerminationGracePeriodSeconds = new(int64) + *out.TerminationGracePeriodSeconds = *in.TerminationGracePeriodSeconds + } else { + out.TerminationGracePeriodSeconds = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + out.DNSPolicy = in.DNSPolicy + if in.NodeSelector != nil { + out.NodeSelector = make(map[string]string) + for key, val := range in.NodeSelector { + out.NodeSelector[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 { + out.SecurityContext = new(v1.PodSecurityContext) + if err := deepCopy_v1_PodSecurityContext(*in.SecurityContext, out.SecurityContext, c); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + if in.ImagePullSecrets != nil { + out.ImagePullSecrets = make([]v1.LocalObjectReference, len(in.ImagePullSecrets)) + for i := range in.ImagePullSecrets { + if err := deepCopy_v1_LocalObjectReference(in.ImagePullSecrets[i], &out.ImagePullSecrets[i], c); err != nil { + return err + } + } + } else { + out.ImagePullSecrets = nil + } + return nil +} + +func deepCopy_v1_PodTemplateSpec(in v1.PodTemplateSpec, out *v1.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_Probe(in v1.Probe, out *v1.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 v1.RBDVolumeSource, out *v1.RBDVolumeSource, c *conversion.Cloner) error { + if in.CephMonitors != nil { + out.CephMonitors = make([]string, len(in.CephMonitors)) + for i := range in.CephMonitors { + out.CephMonitors[i] = in.CephMonitors[i] + } + } 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 { + out.SecretRef = new(v1.LocalObjectReference) + if err := deepCopy_v1_LocalObjectReference(*in.SecretRef, out.SecretRef, c); err != nil { + return err + } + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil +} + +func deepCopy_v1_ResourceRequirements(in v1.ResourceRequirements, out *v1.ResourceRequirements, c *conversion.Cloner) error { + if in.Limits != nil { + out.Limits = make(v1.ResourceList) + for key, val := range in.Limits { + newVal := new(resource.Quantity) + if err := deepCopy_resource_Quantity(val, newVal, c); err != nil { + return err + } + out.Limits[key] = *newVal + } + } else { + out.Limits = nil + } + if in.Requests != nil { + out.Requests = make(v1.ResourceList) + for key, val := range in.Requests { + newVal := new(resource.Quantity) + if err := deepCopy_resource_Quantity(val, newVal, c); err != nil { + return err + } + out.Requests[key] = *newVal + } + } else { + out.Requests = nil + } + return nil +} + +func deepCopy_v1_SELinuxOptions(in v1.SELinuxOptions, out *v1.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_SecretKeySelector(in v1.SecretKeySelector, out *v1.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_SecretVolumeSource(in v1.SecretVolumeSource, out *v1.SecretVolumeSource, c *conversion.Cloner) error { + out.SecretName = in.SecretName + return nil +} + +func deepCopy_v1_SecurityContext(in v1.SecurityContext, out *v1.SecurityContext, c *conversion.Cloner) error { + if in.Capabilities != nil { + out.Capabilities = new(v1.Capabilities) + if err := deepCopy_v1_Capabilities(*in.Capabilities, out.Capabilities, c); err != nil { + return err + } + } else { + out.Capabilities = nil + } + if in.Privileged != nil { + out.Privileged = new(bool) + *out.Privileged = *in.Privileged + } else { + out.Privileged = nil + } + if in.SELinuxOptions != nil { + out.SELinuxOptions = new(v1.SELinuxOptions) + if err := deepCopy_v1_SELinuxOptions(*in.SELinuxOptions, out.SELinuxOptions, c); err != nil { + return err + } + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + out.RunAsUser = new(int64) + *out.RunAsUser = *in.RunAsUser + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + out.RunAsNonRoot = new(bool) + *out.RunAsNonRoot = *in.RunAsNonRoot + } else { + out.RunAsNonRoot = nil + } + if in.ReadOnlyRootFilesystem != nil { + out.ReadOnlyRootFilesystem = new(bool) + *out.ReadOnlyRootFilesystem = *in.ReadOnlyRootFilesystem + } else { + out.ReadOnlyRootFilesystem = nil + } + return nil +} + +func deepCopy_v1_TCPSocketAction(in v1.TCPSocketAction, out *v1.TCPSocketAction, c *conversion.Cloner) error { + if err := deepCopy_intstr_IntOrString(in.Port, &out.Port, c); err != nil { + return err + } + return nil +} + +func deepCopy_v1_Volume(in v1.Volume, out *v1.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 v1.VolumeMount, out *v1.VolumeMount, c *conversion.Cloner) error { + out.Name = in.Name + out.ReadOnly = in.ReadOnly + out.MountPath = in.MountPath + return nil +} + +func deepCopy_v1_VolumeSource(in v1.VolumeSource, out *v1.VolumeSource, c *conversion.Cloner) error { + if in.HostPath != nil { + out.HostPath = new(v1.HostPathVolumeSource) + if err := deepCopy_v1_HostPathVolumeSource(*in.HostPath, out.HostPath, c); err != nil { + return err + } + } else { + out.HostPath = nil + } + if in.EmptyDir != nil { + out.EmptyDir = new(v1.EmptyDirVolumeSource) + if err := deepCopy_v1_EmptyDirVolumeSource(*in.EmptyDir, out.EmptyDir, c); err != nil { + return err + } + } else { + out.EmptyDir = nil + } + if in.GCEPersistentDisk != nil { + out.GCEPersistentDisk = new(v1.GCEPersistentDiskVolumeSource) + if err := deepCopy_v1_GCEPersistentDiskVolumeSource(*in.GCEPersistentDisk, out.GCEPersistentDisk, c); err != nil { + return err + } + } else { + out.GCEPersistentDisk = nil + } + if in.AWSElasticBlockStore != nil { + out.AWSElasticBlockStore = new(v1.AWSElasticBlockStoreVolumeSource) + if err := deepCopy_v1_AWSElasticBlockStoreVolumeSource(*in.AWSElasticBlockStore, out.AWSElasticBlockStore, c); err != nil { + return err + } + } else { + out.AWSElasticBlockStore = nil + } + if in.GitRepo != nil { + out.GitRepo = new(v1.GitRepoVolumeSource) + if err := deepCopy_v1_GitRepoVolumeSource(*in.GitRepo, out.GitRepo, c); err != nil { + return err + } + } else { + out.GitRepo = nil + } + if in.Secret != nil { + out.Secret = new(v1.SecretVolumeSource) + if err := deepCopy_v1_SecretVolumeSource(*in.Secret, out.Secret, c); err != nil { + return err + } + } else { + out.Secret = nil + } + if in.NFS != nil { + out.NFS = new(v1.NFSVolumeSource) + if err := deepCopy_v1_NFSVolumeSource(*in.NFS, out.NFS, c); err != nil { + return err + } + } else { + out.NFS = nil + } + if in.ISCSI != nil { + out.ISCSI = new(v1.ISCSIVolumeSource) + if err := deepCopy_v1_ISCSIVolumeSource(*in.ISCSI, out.ISCSI, c); err != nil { + return err + } + } else { + out.ISCSI = nil + } + if in.Glusterfs != nil { + out.Glusterfs = new(v1.GlusterfsVolumeSource) + if err := deepCopy_v1_GlusterfsVolumeSource(*in.Glusterfs, out.Glusterfs, c); err != nil { + return err + } + } else { + out.Glusterfs = nil + } + if in.PersistentVolumeClaim != nil { + out.PersistentVolumeClaim = new(v1.PersistentVolumeClaimVolumeSource) + if err := deepCopy_v1_PersistentVolumeClaimVolumeSource(*in.PersistentVolumeClaim, out.PersistentVolumeClaim, c); err != nil { + return err + } + } else { + out.PersistentVolumeClaim = nil + } + if in.RBD != nil { + out.RBD = new(v1.RBDVolumeSource) + if err := deepCopy_v1_RBDVolumeSource(*in.RBD, out.RBD, c); err != nil { + return err + } + } else { + out.RBD = nil + } + if in.FlexVolume != nil { + out.FlexVolume = new(v1.FlexVolumeSource) + if err := deepCopy_v1_FlexVolumeSource(*in.FlexVolume, out.FlexVolume, c); err != nil { + return err + } + } else { + out.FlexVolume = nil + } + if in.Cinder != nil { + out.Cinder = new(v1.CinderVolumeSource) + if err := deepCopy_v1_CinderVolumeSource(*in.Cinder, out.Cinder, c); err != nil { + return err + } + } else { + out.Cinder = nil + } + if in.CephFS != nil { + out.CephFS = new(v1.CephFSVolumeSource) + if err := deepCopy_v1_CephFSVolumeSource(*in.CephFS, out.CephFS, c); err != nil { + return err + } + } else { + out.CephFS = nil + } + if in.Flocker != nil { + out.Flocker = new(v1.FlockerVolumeSource) + if err := deepCopy_v1_FlockerVolumeSource(*in.Flocker, out.Flocker, c); err != nil { + return err + } + } else { + out.Flocker = nil + } + if in.DownwardAPI != nil { + out.DownwardAPI = new(v1.DownwardAPIVolumeSource) + if err := deepCopy_v1_DownwardAPIVolumeSource(*in.DownwardAPI, out.DownwardAPI, c); err != nil { + return err + } + } else { + out.DownwardAPI = nil + } + if in.FC != nil { + out.FC = new(v1.FCVolumeSource) + if err := deepCopy_v1_FCVolumeSource(*in.FC, out.FC, c); err != nil { + return err + } + } else { + out.FC = nil + } + if in.AzureFile != nil { + out.AzureFile = new(v1.AzureFileVolumeSource) + if err := deepCopy_v1_AzureFileVolumeSource(*in.AzureFile, out.AzureFile, c); err != nil { + return err + } + } else { + out.AzureFile = nil + } + if in.ConfigMap != nil { + out.ConfigMap = new(v1.ConfigMapVolumeSource) + if err := deepCopy_v1_ConfigMapVolumeSource(*in.ConfigMap, out.ConfigMap, c); err != nil { + return err + } + } else { + out.ConfigMap = nil + } + return nil +} + +func deepCopy_v1_Job(in Job, out *Job, c *conversion.Cloner) error { + if err := 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_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 := deepCopy_unversioned_Time(in.LastProbeTime, &out.LastProbeTime, c); err != nil { + return err + } + if err := 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 := 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 + } + if in.Items != nil { + out.Items = make([]Job, len(in.Items)) + for i := range in.Items { + if err := deepCopy_v1_Job(in.Items[i], &out.Items[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 { + out.Parallelism = new(int32) + *out.Parallelism = *in.Parallelism + } else { + out.Parallelism = nil + } + if in.Completions != nil { + out.Completions = new(int32) + *out.Completions = *in.Completions + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + if in.Selector != nil { + out.Selector = new(LabelSelector) + if err := deepCopy_v1_LabelSelector(*in.Selector, out.Selector, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if in.ManualSelector != nil { + out.ManualSelector = new(bool) + *out.ManualSelector = *in.ManualSelector + } else { + out.ManualSelector = nil + } + if err := 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 { + out.Conditions = make([]JobCondition, len(in.Conditions)) + for i := range in.Conditions { + if err := deepCopy_v1_JobCondition(in.Conditions[i], &out.Conditions[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.StartTime != nil { + out.StartTime = new(unversioned.Time) + if err := deepCopy_unversioned_Time(*in.StartTime, out.StartTime, c); err != nil { + return err + } + } else { + out.StartTime = nil + } + if in.CompletionTime != nil { + out.CompletionTime = new(unversioned.Time) + if err := deepCopy_unversioned_Time(*in.CompletionTime, out.CompletionTime, 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 { + out.MatchLabels = make(map[string]string) + for key, val := range in.MatchLabels { + out.MatchLabels[key] = val + } + } else { + out.MatchLabels = nil + } + if in.MatchExpressions != nil { + out.MatchExpressions = make([]LabelSelectorRequirement, len(in.MatchExpressions)) + for i := range in.MatchExpressions { + if err := deepCopy_v1_LabelSelectorRequirement(in.MatchExpressions[i], &out.MatchExpressions[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 { + out.Values = make([]string, len(in.Values)) + for i := range in.Values { + out.Values[i] = in.Values[i] + } + } else { + out.Values = nil + } + return nil +} + +func deepCopy_intstr_IntOrString(in intstr.IntOrString, out *intstr.IntOrString, c *conversion.Cloner) error { + out.Type = in.Type + out.IntVal = in.IntVal + out.StrVal = in.StrVal + return nil +} + +func init() { + err := api.Scheme.AddGeneratedDeepCopyFuncs( + deepCopy_resource_Quantity, + deepCopy_unversioned_ListMeta, + deepCopy_unversioned_Time, + deepCopy_unversioned_TypeMeta, + deepCopy_v1_AWSElasticBlockStoreVolumeSource, + deepCopy_v1_AzureFileVolumeSource, + deepCopy_v1_Capabilities, + deepCopy_v1_CephFSVolumeSource, + deepCopy_v1_CinderVolumeSource, + deepCopy_v1_ConfigMapKeySelector, + deepCopy_v1_ConfigMapVolumeSource, + deepCopy_v1_Container, + deepCopy_v1_ContainerPort, + deepCopy_v1_DownwardAPIVolumeFile, + deepCopy_v1_DownwardAPIVolumeSource, + deepCopy_v1_EmptyDirVolumeSource, + deepCopy_v1_EnvVar, + deepCopy_v1_EnvVarSource, + deepCopy_v1_ExecAction, + 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_LocalObjectReference, + deepCopy_v1_NFSVolumeSource, + deepCopy_v1_ObjectFieldSelector, + deepCopy_v1_ObjectMeta, + deepCopy_v1_PersistentVolumeClaimVolumeSource, + deepCopy_v1_PodSecurityContext, + deepCopy_v1_PodSpec, + deepCopy_v1_PodTemplateSpec, + deepCopy_v1_Probe, + deepCopy_v1_RBDVolumeSource, + deepCopy_v1_ResourceRequirements, + deepCopy_v1_SELinuxOptions, + deepCopy_v1_SecretKeySelector, + deepCopy_v1_SecretVolumeSource, + deepCopy_v1_SecurityContext, + deepCopy_v1_TCPSocketAction, + deepCopy_v1_Volume, + deepCopy_v1_VolumeMount, + deepCopy_v1_VolumeSource, + deepCopy_v1_Job, + deepCopy_v1_JobCondition, + deepCopy_v1_JobList, + deepCopy_v1_JobSpec, + deepCopy_v1_JobStatus, + deepCopy_v1_LabelSelector, + deepCopy_v1_LabelSelectorRequirement, + deepCopy_intstr_IntOrString, + ) + if err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/defaults.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/defaults.go new file mode 100644 index 000000000..759ab0fb6 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/defaults.go @@ -0,0 +1,40 @@ +/* +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. +*/ + +package v1 + +import ( + "k8s.io/kubernetes/pkg/runtime" +) + +func addDefaultingFuncs(scheme *runtime.Scheme) { + scheme.AddDefaultingFuncs( + func(obj *Job) { + // For a non-parallel job, you can leave both `.spec.completions` and + // `.spec.parallelism` unset. When both are unset, both are defaulted to 1. + if obj.Spec.Completions == nil && obj.Spec.Parallelism == nil { + obj.Spec.Completions = new(int32) + *obj.Spec.Completions = 1 + obj.Spec.Parallelism = new(int32) + *obj.Spec.Parallelism = 1 + } + if obj.Spec.Parallelism == nil { + obj.Spec.Parallelism = new(int32) + *obj.Spec.Parallelism = 1 + } + }, + ) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/register.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/register.go new file mode 100644 index 000000000..49f7376a3 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/register.go @@ -0,0 +1,47 @@ +/* +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. +*/ + +package v1 + +import ( + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/runtime" +) + +// GroupName is the group name use in this package +const GroupName = "batch" + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: "v1"} + +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, + &Job{}, + &JobList{}, + &v1.ListOptions{}, + ) +} + +func (obj *Job) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *JobList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types.generated.go new file mode 100644 index 000000000..2c07db216 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types.generated.go @@ -0,0 +1,3186 @@ +/* +Copyright 2015 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. +*/ + +// ************************************************************ +// DO NOT EDIT. +// THIS FILE IS AUTO-GENERATED BY codecgen. +// ************************************************************ + +package v1 + +import ( + "errors" + "fmt" + codec1978 "github.com/ugorji/go/codec" + pkg4_resource "k8s.io/kubernetes/pkg/api/resource" + pkg1_unversioned "k8s.io/kubernetes/pkg/api/unversioned" + pkg2_v1 "k8s.io/kubernetes/pkg/api/v1" + pkg3_types "k8s.io/kubernetes/pkg/types" + pkg6_intstr "k8s.io/kubernetes/pkg/util/intstr" + "reflect" + "runtime" + pkg5_inf "speter.net/go/exp/math/dec/inf" + 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 pkg4_resource.Quantity + var v1 pkg1_unversioned.TypeMeta + var v2 pkg2_v1.ObjectMeta + var v3 pkg3_types.UID + var v4 pkg6_intstr.IntOrString + var v5 pkg5_inf.Dec + var v6 time.Time + _, _, _, _, _, _, _ = v0, v1, v2, v3, v4, v5, v6 + } +} + +func (x *Job) 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 *Job) 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 *Job) 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 = JobSpec{} + } else { + yyv5 := &x.Spec + yyv5.CodecDecodeSelf(d) + } + case "status": + if r.TryDecodeAsNil() { + x.Status = JobStatus{} + } 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 *Job) 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 = JobSpec{} + } 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 = JobStatus{} + } 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 *JobList) 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.encSliceJob(([]Job)(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.encSliceJob(([]Job)(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 *JobList) 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 *JobList) 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.decSliceJob((*[]Job)(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 *JobList) 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.decSliceJob((*[]Job)(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 *JobSpec) 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 [6]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = x.Parallelism != nil + yyq2[1] = x.Completions != nil + yyq2[2] = x.ActiveDeadlineSeconds != nil + yyq2[3] = x.Selector != nil + yyq2[4] = x.ManualSelector != nil + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(6) + } 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] { + if x.Parallelism == nil { + r.EncodeNil() + } else { + yy4 := *x.Parallelism + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeInt(int64(yy4)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("parallelism")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Parallelism == nil { + r.EncodeNil() + } else { + yy6 := *x.Parallelism + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeInt(int64(yy6)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.Completions == nil { + r.EncodeNil() + } else { + yy9 := *x.Completions + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeInt(int64(yy9)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("completions")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Completions == nil { + r.EncodeNil() + } else { + yy11 := *x.Completions + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeInt(int64(yy11)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + if x.ActiveDeadlineSeconds == nil { + r.EncodeNil() + } else { + yy14 := *x.ActiveDeadlineSeconds + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeInt(int64(yy14)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("activeDeadlineSeconds")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.ActiveDeadlineSeconds == nil { + r.EncodeNil() + } else { + yy16 := *x.ActiveDeadlineSeconds + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeInt(int64(yy16)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + if x.Selector == nil { + r.EncodeNil() + } else { + x.Selector.CodecEncodeSelf(e) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("selector")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Selector == nil { + r.EncodeNil() + } else { + x.Selector.CodecEncodeSelf(e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + if x.ManualSelector == nil { + r.EncodeNil() + } else { + yy22 := *x.ManualSelector + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeBool(bool(yy22)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("manualSelector")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.ManualSelector == nil { + r.EncodeNil() + } else { + yy24 := *x.ManualSelector + yym25 := z.EncBinary() + _ = yym25 + if false { + } else { + r.EncodeBool(bool(yy24)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy27 := &x.Template + yy27.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("template")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy29 := &x.Template + yy29.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *JobSpec) 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 *JobSpec) 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 "parallelism": + if r.TryDecodeAsNil() { + if x.Parallelism != nil { + x.Parallelism = nil + } + } else { + if x.Parallelism == nil { + x.Parallelism = new(int32) + } + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *((*int32)(x.Parallelism)) = int32(r.DecodeInt(32)) + } + } + case "completions": + if r.TryDecodeAsNil() { + if x.Completions != nil { + x.Completions = nil + } + } else { + if x.Completions == nil { + x.Completions = new(int32) + } + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *((*int32)(x.Completions)) = int32(r.DecodeInt(32)) + } + } + case "activeDeadlineSeconds": + if r.TryDecodeAsNil() { + if x.ActiveDeadlineSeconds != nil { + x.ActiveDeadlineSeconds = nil + } + } else { + if x.ActiveDeadlineSeconds == nil { + x.ActiveDeadlineSeconds = new(int64) + } + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + *((*int64)(x.ActiveDeadlineSeconds)) = int64(r.DecodeInt(64)) + } + } + case "selector": + if r.TryDecodeAsNil() { + if x.Selector != nil { + x.Selector = nil + } + } else { + if x.Selector == nil { + x.Selector = new(LabelSelector) + } + x.Selector.CodecDecodeSelf(d) + } + case "manualSelector": + if r.TryDecodeAsNil() { + if x.ManualSelector != nil { + x.ManualSelector = nil + } + } else { + if x.ManualSelector == nil { + x.ManualSelector = new(bool) + } + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*bool)(x.ManualSelector)) = r.DecodeBool() + } + } + case "template": + if r.TryDecodeAsNil() { + x.Template = pkg2_v1.PodTemplateSpec{} + } else { + yyv13 := &x.Template + yyv13.CodecDecodeSelf(d) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj14 int + var yyb14 bool + var yyhl14 bool = l >= 0 + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.Parallelism != nil { + x.Parallelism = nil + } + } else { + if x.Parallelism == nil { + x.Parallelism = new(int32) + } + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + *((*int32)(x.Parallelism)) = int32(r.DecodeInt(32)) + } + } + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.Completions != nil { + x.Completions = nil + } + } else { + if x.Completions == nil { + x.Completions = new(int32) + } + yym18 := z.DecBinary() + _ = yym18 + if false { + } else { + *((*int32)(x.Completions)) = int32(r.DecodeInt(32)) + } + } + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.ActiveDeadlineSeconds != nil { + x.ActiveDeadlineSeconds = nil + } + } else { + if x.ActiveDeadlineSeconds == nil { + x.ActiveDeadlineSeconds = new(int64) + } + yym20 := z.DecBinary() + _ = yym20 + if false { + } else { + *((*int64)(x.ActiveDeadlineSeconds)) = int64(r.DecodeInt(64)) + } + } + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.Selector != nil { + x.Selector = nil + } + } else { + if x.Selector == nil { + x.Selector = new(LabelSelector) + } + x.Selector.CodecDecodeSelf(d) + } + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.ManualSelector != nil { + x.ManualSelector = nil + } + } else { + if x.ManualSelector == nil { + x.ManualSelector = new(bool) + } + yym23 := z.DecBinary() + _ = yym23 + if false { + } else { + *((*bool)(x.ManualSelector)) = r.DecodeBool() + } + } + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Template = pkg2_v1.PodTemplateSpec{} + } else { + yyv24 := &x.Template + yyv24.CodecDecodeSelf(d) + } + for { + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj14-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *JobStatus) 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 [6]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = len(x.Conditions) != 0 + yyq2[1] = x.StartTime != nil + yyq2[2] = x.CompletionTime != nil + yyq2[3] = x.Active != 0 + yyq2[4] = x.Succeeded != 0 + yyq2[5] = x.Failed != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(6) + } 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.encSliceJobCondition(([]JobCondition)(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.encSliceJobCondition(([]JobCondition)(x.Conditions), e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.StartTime == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else if z.HasExtensions() && z.EncExt(x.StartTime) { + } else if yym7 { + z.EncBinaryMarshal(x.StartTime) + } else if !yym7 && z.IsJSONHandle() { + z.EncJSONMarshal(x.StartTime) + } else { + z.EncFallback(x.StartTime) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("startTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.StartTime == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else if z.HasExtensions() && z.EncExt(x.StartTime) { + } else if yym8 { + z.EncBinaryMarshal(x.StartTime) + } else if !yym8 && z.IsJSONHandle() { + z.EncJSONMarshal(x.StartTime) + } else { + z.EncFallback(x.StartTime) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + if x.CompletionTime == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else if z.HasExtensions() && z.EncExt(x.CompletionTime) { + } else if yym10 { + z.EncBinaryMarshal(x.CompletionTime) + } else if !yym10 && z.IsJSONHandle() { + z.EncJSONMarshal(x.CompletionTime) + } else { + z.EncFallback(x.CompletionTime) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("completionTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.CompletionTime == nil { + r.EncodeNil() + } else { + yym11 := z.EncBinary() + _ = yym11 + if false { + } else if z.HasExtensions() && z.EncExt(x.CompletionTime) { + } else if yym11 { + z.EncBinaryMarshal(x.CompletionTime) + } else if !yym11 && z.IsJSONHandle() { + z.EncJSONMarshal(x.CompletionTime) + } else { + z.EncFallback(x.CompletionTime) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeInt(int64(x.Active)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("active")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeInt(int64(x.Active)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeInt(int64(x.Succeeded)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("succeeded")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeInt(int64(x.Succeeded)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[5] { + yym19 := z.EncBinary() + _ = yym19 + if false { + } else { + r.EncodeInt(int64(x.Failed)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[5] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("failed")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym20 := z.EncBinary() + _ = yym20 + if false { + } else { + r.EncodeInt(int64(x.Failed)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *JobStatus) 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 *JobStatus) 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.decSliceJobCondition((*[]JobCondition)(yyv4), d) + } + } + case "startTime": + if r.TryDecodeAsNil() { + if x.StartTime != nil { + x.StartTime = nil + } + } else { + if x.StartTime == nil { + x.StartTime = new(pkg1_unversioned.Time) + } + yym7 := z.DecBinary() + _ = yym7 + if false { + } else if z.HasExtensions() && z.DecExt(x.StartTime) { + } else if yym7 { + z.DecBinaryUnmarshal(x.StartTime) + } else if !yym7 && z.IsJSONHandle() { + z.DecJSONUnmarshal(x.StartTime) + } else { + z.DecFallback(x.StartTime, false) + } + } + case "completionTime": + if r.TryDecodeAsNil() { + if x.CompletionTime != nil { + x.CompletionTime = nil + } + } else { + if x.CompletionTime == nil { + x.CompletionTime = new(pkg1_unversioned.Time) + } + yym9 := z.DecBinary() + _ = yym9 + if false { + } else if z.HasExtensions() && z.DecExt(x.CompletionTime) { + } else if yym9 { + z.DecBinaryUnmarshal(x.CompletionTime) + } else if !yym9 && z.IsJSONHandle() { + z.DecJSONUnmarshal(x.CompletionTime) + } else { + z.DecFallback(x.CompletionTime, false) + } + } + case "active": + if r.TryDecodeAsNil() { + x.Active = 0 + } else { + x.Active = int32(r.DecodeInt(32)) + } + case "succeeded": + if r.TryDecodeAsNil() { + x.Succeeded = 0 + } else { + x.Succeeded = int32(r.DecodeInt(32)) + } + case "failed": + if r.TryDecodeAsNil() { + x.Failed = 0 + } else { + x.Failed = int32(r.DecodeInt(32)) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *JobStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj13 int + var yyb13 bool + var yyhl13 bool = l >= 0 + yyj13++ + if yyhl13 { + yyb13 = yyj13 > l + } else { + yyb13 = r.CheckBreak() + } + if yyb13 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Conditions = nil + } else { + yyv14 := &x.Conditions + yym15 := z.DecBinary() + _ = yym15 + if false { + } else { + h.decSliceJobCondition((*[]JobCondition)(yyv14), d) + } + } + yyj13++ + if yyhl13 { + yyb13 = yyj13 > l + } else { + yyb13 = r.CheckBreak() + } + if yyb13 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.StartTime != nil { + x.StartTime = nil + } + } else { + if x.StartTime == nil { + x.StartTime = new(pkg1_unversioned.Time) + } + yym17 := z.DecBinary() + _ = yym17 + if false { + } else if z.HasExtensions() && z.DecExt(x.StartTime) { + } else if yym17 { + z.DecBinaryUnmarshal(x.StartTime) + } else if !yym17 && z.IsJSONHandle() { + z.DecJSONUnmarshal(x.StartTime) + } else { + z.DecFallback(x.StartTime, false) + } + } + yyj13++ + if yyhl13 { + yyb13 = yyj13 > l + } else { + yyb13 = r.CheckBreak() + } + if yyb13 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.CompletionTime != nil { + x.CompletionTime = nil + } + } else { + if x.CompletionTime == nil { + x.CompletionTime = new(pkg1_unversioned.Time) + } + yym19 := z.DecBinary() + _ = yym19 + if false { + } else if z.HasExtensions() && z.DecExt(x.CompletionTime) { + } else if yym19 { + z.DecBinaryUnmarshal(x.CompletionTime) + } else if !yym19 && z.IsJSONHandle() { + z.DecJSONUnmarshal(x.CompletionTime) + } else { + z.DecFallback(x.CompletionTime, false) + } + } + yyj13++ + if yyhl13 { + yyb13 = yyj13 > l + } else { + yyb13 = r.CheckBreak() + } + if yyb13 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Active = 0 + } else { + x.Active = int32(r.DecodeInt(32)) + } + yyj13++ + if yyhl13 { + yyb13 = yyj13 > l + } else { + yyb13 = r.CheckBreak() + } + if yyb13 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Succeeded = 0 + } else { + x.Succeeded = int32(r.DecodeInt(32)) + } + yyj13++ + if yyhl13 { + yyb13 = yyj13 > l + } else { + yyb13 = r.CheckBreak() + } + if yyb13 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Failed = 0 + } else { + x.Failed = int32(r.DecodeInt(32)) + } + for { + yyj13++ + if yyhl13 { + yyb13 = yyj13 > l + } else { + yyb13 = r.CheckBreak() + } + if yyb13 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj13-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x JobConditionType) 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 *JobConditionType) 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 *JobCondition) 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 [6]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[2] = true + yyq2[3] = true + yyq2[4] = x.Reason != "" + yyq2[5] = x.Message != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(6) + } else { + yynn2 = 2 + 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) + yysf7 := &x.Status + yysf7.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("status")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yysf8 := &x.Status + yysf8.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yy10 := &x.LastProbeTime + yym11 := z.EncBinary() + _ = yym11 + if false { + } else if z.HasExtensions() && z.EncExt(yy10) { + } else if yym11 { + z.EncBinaryMarshal(yy10) + } else if !yym11 && z.IsJSONHandle() { + z.EncJSONMarshal(yy10) + } else { + z.EncFallback(yy10) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("lastProbeTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy12 := &x.LastProbeTime + yym13 := z.EncBinary() + _ = yym13 + if false { + } else if z.HasExtensions() && z.EncExt(yy12) { + } else if yym13 { + z.EncBinaryMarshal(yy12) + } else if !yym13 && z.IsJSONHandle() { + z.EncJSONMarshal(yy12) + } else { + z.EncFallback(yy12) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yy15 := &x.LastTransitionTime + 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) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("lastTransitionTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy17 := &x.LastTransitionTime + yym18 := z.EncBinary() + _ = yym18 + if false { + } else if z.HasExtensions() && z.EncExt(yy17) { + } else if yym18 { + z.EncBinaryMarshal(yy17) + } else if !yym18 && z.IsJSONHandle() { + z.EncJSONMarshal(yy17) + } else { + z.EncFallback(yy17) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym20 := z.EncBinary() + _ = yym20 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("reason")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym21 := z.EncBinary() + _ = yym21 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[5] { + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[5] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("message")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym24 := z.EncBinary() + _ = yym24 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *JobCondition) 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 *JobCondition) 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 = JobConditionType(r.DecodeString()) + } + case "status": + if r.TryDecodeAsNil() { + x.Status = "" + } else { + x.Status = pkg2_v1.ConditionStatus(r.DecodeString()) + } + case "lastProbeTime": + if r.TryDecodeAsNil() { + x.LastProbeTime = pkg1_unversioned.Time{} + } else { + yyv6 := &x.LastProbeTime + yym7 := z.DecBinary() + _ = yym7 + if false { + } else if z.HasExtensions() && z.DecExt(yyv6) { + } else if yym7 { + z.DecBinaryUnmarshal(yyv6) + } else if !yym7 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv6) + } else { + z.DecFallback(yyv6, false) + } + } + case "lastTransitionTime": + if r.TryDecodeAsNil() { + x.LastTransitionTime = pkg1_unversioned.Time{} + } else { + yyv8 := &x.LastTransitionTime + yym9 := z.DecBinary() + _ = yym9 + if false { + } else if z.HasExtensions() && z.DecExt(yyv8) { + } else if yym9 { + z.DecBinaryUnmarshal(yyv8) + } else if !yym9 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv8) + } else { + z.DecFallback(yyv8, 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 *JobCondition) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj12 int + var yyb12 bool + var yyhl12 bool = l >= 0 + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Type = "" + } else { + x.Type = JobConditionType(r.DecodeString()) + } + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Status = "" + } else { + x.Status = pkg2_v1.ConditionStatus(r.DecodeString()) + } + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.LastProbeTime = pkg1_unversioned.Time{} + } else { + yyv15 := &x.LastProbeTime + yym16 := z.DecBinary() + _ = yym16 + if false { + } else if z.HasExtensions() && z.DecExt(yyv15) { + } else if yym16 { + z.DecBinaryUnmarshal(yyv15) + } else if !yym16 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv15) + } else { + z.DecFallback(yyv15, false) + } + } + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.LastTransitionTime = pkg1_unversioned.Time{} + } else { + yyv17 := &x.LastTransitionTime + yym18 := z.DecBinary() + _ = yym18 + if false { + } else if z.HasExtensions() && z.DecExt(yyv17) { + } else if yym18 { + z.DecBinaryUnmarshal(yyv17) + } else if !yym18 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv17) + } else { + z.DecFallback(yyv17, false) + } + } + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + for { + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj12-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *LabelSelector) 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.MatchLabels) != 0 + yyq2[1] = len(x.MatchExpressions) != 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.MatchLabels == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + z.F.EncMapStringStringV(x.MatchLabels, false, e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("matchLabels")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.MatchLabels == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + z.F.EncMapStringStringV(x.MatchLabels, false, e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.MatchExpressions == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + h.encSliceLabelSelectorRequirement(([]LabelSelectorRequirement)(x.MatchExpressions), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("matchExpressions")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.MatchExpressions == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + h.encSliceLabelSelectorRequirement(([]LabelSelectorRequirement)(x.MatchExpressions), e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *LabelSelector) 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 *LabelSelector) 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 "matchLabels": + if r.TryDecodeAsNil() { + x.MatchLabels = nil + } else { + yyv4 := &x.MatchLabels + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + z.F.DecMapStringStringX(yyv4, false, d) + } + } + case "matchExpressions": + if r.TryDecodeAsNil() { + x.MatchExpressions = nil + } else { + yyv6 := &x.MatchExpressions + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + h.decSliceLabelSelectorRequirement((*[]LabelSelectorRequirement)(yyv6), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *LabelSelector) 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.MatchLabels = nil + } else { + yyv9 := &x.MatchLabels + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + z.F.DecMapStringStringX(yyv9, false, 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.MatchExpressions = nil + } else { + yyv11 := &x.MatchExpressions + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + h.decSliceLabelSelectorRequirement((*[]LabelSelectorRequirement)(yyv11), d) + } + } + 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 *LabelSelectorRequirement) 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 [3]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[2] = len(x.Values) != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(3) + } else { + yynn2 = 2 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Key)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("key")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Key)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + x.Operator.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("operator")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + x.Operator.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + if x.Values == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + z.F.EncSliceStringV(x.Values, false, e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("values")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Values == nil { + r.EncodeNil() + } else { + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + z.F.EncSliceStringV(x.Values, false, e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *LabelSelectorRequirement) 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 *LabelSelectorRequirement) 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 "key": + if r.TryDecodeAsNil() { + x.Key = "" + } else { + x.Key = string(r.DecodeString()) + } + case "operator": + if r.TryDecodeAsNil() { + x.Operator = "" + } else { + x.Operator = LabelSelectorOperator(r.DecodeString()) + } + case "values": + if r.TryDecodeAsNil() { + x.Values = nil + } else { + yyv6 := &x.Values + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + z.F.DecSliceStringX(yyv6, false, d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *LabelSelectorRequirement) 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.Key = "" + } else { + x.Key = string(r.DecodeString()) + } + 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.Operator = "" + } else { + x.Operator = LabelSelectorOperator(r.DecodeString()) + } + 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.Values = nil + } else { + yyv11 := &x.Values + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + z.F.DecSliceStringX(yyv11, false, d) + } + } + 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 LabelSelectorOperator) 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 *LabelSelectorOperator) 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 codecSelfer1234) encSliceJob(v []Job, 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) decSliceJob(v *[]Job, 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 = []Job{} + 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, 640) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]Job, yyrl1) + } + } else { + yyv1 = make([]Job, 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] = Job{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, Job{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = Job{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, Job{}) // var yyz1 Job + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = Job{} + } 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 = []Job{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer1234) encSliceJobCondition(v []JobCondition, 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) decSliceJobCondition(v *[]JobCondition, 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 = []JobCondition{} + 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, 112) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]JobCondition, yyrl1) + } + } else { + yyv1 = make([]JobCondition, 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] = JobCondition{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, JobCondition{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = JobCondition{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, JobCondition{}) // var yyz1 JobCondition + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = JobCondition{} + } 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 = []JobCondition{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer1234) encSliceLabelSelectorRequirement(v []LabelSelectorRequirement, 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) decSliceLabelSelectorRequirement(v *[]LabelSelectorRequirement, 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 = []LabelSelectorRequirement{} + 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, 56) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]LabelSelectorRequirement, yyrl1) + } + } else { + yyv1 = make([]LabelSelectorRequirement, 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] = LabelSelectorRequirement{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, LabelSelectorRequirement{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = LabelSelectorRequirement{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, LabelSelectorRequirement{}) // var yyz1 LabelSelectorRequirement + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = LabelSelectorRequirement{} + } 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 = []LabelSelectorRequirement{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types.go new file mode 100644 index 000000000..214ffe6d3 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types.go @@ -0,0 +1,184 @@ +/* +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. +*/ + +package v1 + +import ( + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" +) + +// Job represents the configuration of a single job. +type Job struct { + unversioned.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata + v1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is a structure defining the expected behavior of a job. + // More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status + Status JobStatus `json:"status,omitempty"` +} + +// JobList is a collection of jobs. +type JobList struct { + unversioned.TypeMeta `json:",inline"` + // Standard list metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata + unversioned.ListMeta `json:"metadata,omitempty"` + + // Items is the list of Job. + Items []Job `json:"items"` +} + +// JobSpec describes how the job execution will look like. +type JobSpec struct { + + // 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.2/docs/user-guide/jobs.md + Parallelism *int32 `json:"parallelism,omitempty"` + + // 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.2/docs/user-guide/jobs.md + Completions *int32 `json:"completions,omitempty"` + + // 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 + ActiveDeadlineSeconds *int64 `json:"activeDeadlineSeconds,omitempty"` + + // 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.2/docs/user-guide/labels.md#label-selectors + Selector *LabelSelector `json:"selector,omitempty"` + + // 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.2/docs/design/selector-generation.md + ManualSelector *bool `json:"manualSelector,omitempty"` + + // Template is the object that describes the pod that will be created when + // executing a job. + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/jobs.md + Template v1.PodTemplateSpec `json:"template"` +} + +// JobStatus represents the current state of a Job. +type JobStatus struct { + + // Conditions represent the latest available observations of an object's current state. + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/jobs.md + Conditions []JobCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` + + // 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. + StartTime *unversioned.Time `json:"startTime,omitempty"` + + // 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. + CompletionTime *unversioned.Time `json:"completionTime,omitempty"` + + // Active is the number of actively running pods. + Active int32 `json:"active,omitempty"` + + // Succeeded is the number of pods which reached Phase Succeeded. + Succeeded int32 `json:"succeeded,omitempty"` + + // Failed is the number of pods which reached Phase Failed. + Failed int32 `json:"failed,omitempty"` +} + +type JobConditionType string + +// These are valid conditions of a job. +const ( + // JobComplete means the job has completed its execution. + JobComplete JobConditionType = "Complete" + // JobFailed means the job has failed its execution. + JobFailed JobConditionType = "Failed" +) + +// JobCondition describes current state of a job. +type JobCondition struct { + // Type of job condition, Complete or Failed. + Type JobConditionType `json:"type"` + // Status of the condition, one of True, False, Unknown. + Status v1.ConditionStatus `json:"status"` + // Last time the condition was checked. + LastProbeTime unversioned.Time `json:"lastProbeTime,omitempty"` + // Last time the condition transit from one status to another. + LastTransitionTime unversioned.Time `json:"lastTransitionTime,omitempty"` + // (brief) reason for the condition's last transition. + Reason string `json:"reason,omitempty"` + // Human readable message indicating details about last transition. + Message string `json:"message,omitempty"` +} + +// A label selector is a label query over a set of resources. The result of matchLabels and +// matchExpressions are ANDed. An empty label selector matches all objects. A null +// label selector matches no objects. +type LabelSelector struct { + // matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + // map is equivalent to an element of matchExpressions, whose key field is "key", the + // operator is "In", and the values array contains only "value". The requirements are ANDed. + MatchLabels map[string]string `json:"matchLabels,omitempty"` + // matchExpressions is a list of label selector requirements. The requirements are ANDed. + MatchExpressions []LabelSelectorRequirement `json:"matchExpressions,omitempty"` +} + +// A label selector requirement is a selector that contains values, a key, and an operator that +// relates the key and values. +type LabelSelectorRequirement struct { + // key is the label key that the selector applies to. + Key string `json:"key" patchStrategy:"merge" patchMergeKey:"key"` + // operator represents a key's relationship to a set of values. + // Valid operators ard In, NotIn, Exists and DoesNotExist. + Operator LabelSelectorOperator `json:"operator"` + // values is an array of string values. If the operator is In or NotIn, + // the values array must be non-empty. If the operator is Exists or DoesNotExist, + // the values array must be empty. This array is replaced during a strategic + // merge patch. + Values []string `json:"values,omitempty"` +} + +// A label selector operator is the set of operators that can be used in a selector requirement. +type LabelSelectorOperator string + +const ( + LabelSelectorOpIn LabelSelectorOperator = "In" + LabelSelectorOpNotIn LabelSelectorOperator = "NotIn" + LabelSelectorOpExists LabelSelectorOperator = "Exists" + LabelSelectorOpDoesNotExist LabelSelectorOperator = "DoesNotExist" +) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types_swagger_doc_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types_swagger_doc_generated.go new file mode 100644 index 000000000..32e278eac --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/batch/v1/types_swagger_doc_generated.go @@ -0,0 +1,114 @@ +/* +Copyright 2015 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. +*/ + +package v1 + +// 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_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.2/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.2/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.2/docs/devel/api-conventions.md#spec-and-status", +} + +func (Job) SwaggerDoc() map[string]string { + return map_Job +} + +var map_JobCondition = map[string]string{ + "": "JobCondition describes current state of a job.", + "type": "Type of job condition, Complete or Failed.", + "status": "Status of the condition, one of True, False, Unknown.", + "lastProbeTime": "Last time the condition was checked.", + "lastTransitionTime": "Last time the condition transit from one status to another.", + "reason": "(brief) reason for the condition's last transition.", + "message": "Human readable message indicating details about last transition.", +} + +func (JobCondition) SwaggerDoc() map[string]string { + return map_JobCondition +} + +var map_JobList = map[string]string{ + "": "JobList is a collection of jobs.", + "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "items": "Items is the list of Job.", +} + +func (JobList) SwaggerDoc() map[string]string { + return map_JobList +} + +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.2/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.2/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.2/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.2/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.2/docs/user-guide/jobs.md", +} + +func (JobSpec) SwaggerDoc() map[string]string { + return map_JobSpec +} + +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.2/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.", + "succeeded": "Succeeded is the number of pods which reached Phase Succeeded.", + "failed": "Failed is the number of pods which reached Phase Failed.", +} + +func (JobStatus) SwaggerDoc() map[string]string { + return map_JobStatus +} + +var map_LabelSelector = map[string]string{ + "": "A label selector is a label query over a set of resources. The result of matchLabels and matchExpressions are ANDed. An empty label selector matches all objects. A null label selector matches no objects.", + "matchLabels": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", + "matchExpressions": "matchExpressions is a list of label selector requirements. The requirements are ANDed.", +} + +func (LabelSelector) SwaggerDoc() map[string]string { + return map_LabelSelector +} + +var map_LabelSelectorRequirement = map[string]string{ + "": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.", + "key": "key is the label key that the selector applies to.", + "operator": "operator represents a key's relationship to a set of values. Valid operators ard In, NotIn, Exists and DoesNotExist.", + "values": "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.", +} + +func (LabelSelectorRequirement) SwaggerDoc() map[string]string { + return map_LabelSelectorRequirement +} + +// AUTO-GENERATED FUNCTIONS END HERE diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/helpers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/helpers_test.go deleted file mode 100644 index 7aece8257..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/helpers_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -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. -*/ - -package componentconfig - -import ( - "strings" - "testing" - - "github.com/spf13/pflag" -) - -func TestIPVar(t *testing.T) { - defaultIP := "0.0.0.0" - cases := []struct { - argc string - expectErr bool - expectVal string - }{ - - { - argc: "blah --ip=1.2.3.4", - expectVal: "1.2.3.4", - }, - { - argc: "blah --ip=1.2.3.4a", - expectErr: true, - expectVal: defaultIP, - }, - } - for _, c := range cases { - fs := pflag.NewFlagSet("blah", pflag.PanicOnError) - ip := defaultIP - fs.Var(IPVar{&ip}, "ip", "the ip") - - var err error - func() { - defer func() { - if r := recover(); r != nil { - err = r.(error) - } - }() - fs.Parse(strings.Split(c.argc, " ")) - }() - - if c.expectErr && err == nil { - t.Errorf("did not observe an expected error") - continue - } - if !c.expectErr && err != nil { - t.Errorf("observed an unexpected error") - continue - } - if c.expectVal != ip { - t.Errorf("unexpected ip: expected %q, saw %q", c.expectVal, ip) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/install/install_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/install/install_test.go deleted file mode 100644 index 940e17567..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/install/install_test.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package install - -import ( - "encoding/json" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/componentconfig" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestCodec(t *testing.T) { - daemonSet := componentconfig.KubeProxyConfiguration{} - // We do want to use package registered rather than testapi here, because we - // want to test if the package install and package registered work as expected. - data, err := runtime.Encode(api.Codecs.LegacyCodec(registered.GroupOrDie(componentconfig.GroupName).GroupVersion), &daemonSet) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - other := componentconfig.KubeProxyConfiguration{} - if err := json.Unmarshal(data, &other); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if other.APIVersion != registered.GroupOrDie(componentconfig.GroupName).GroupVersion.String() || other.Kind != "KubeProxyConfiguration" { - t.Errorf("unexpected unmarshalled object %#v", other) - } -} - -func TestInterfacesFor(t *testing.T) { - if _, err := registered.GroupOrDie(componentconfig.GroupName).InterfacesFor(componentconfig.SchemeGroupVersion); err == nil { - t.Fatalf("unexpected non-error: %v", err) - } - for i, version := range registered.GroupOrDie(componentconfig.GroupName).GroupVersions { - if vi, err := registered.GroupOrDie(componentconfig.GroupName).InterfacesFor(version); err != nil || vi == nil { - t.Fatalf("%d: unexpected result: %v", i, err) - } - } -} - -func TestRESTMapper(t *testing.T) { - gv := unversioned.GroupVersion{Group: componentconfig.GroupName, Version: "v1alpha1"} - proxyGVK := gv.WithKind("KubeProxyConfiguration") - - if gvk, err := registered.GroupOrDie(componentconfig.GroupName).RESTMapper.KindFor(gv.WithResource("kubeproxyconfiguration")); err != nil || gvk != proxyGVK { - t.Errorf("unexpected version mapping: %v %v", gvk, err) - } - - if m, err := registered.GroupOrDie(componentconfig.GroupName).RESTMapper.RESTMapping(proxyGVK.GroupKind(), ""); err != nil || m.GroupVersionKind != proxyGVK || m.Resource != "kubeproxyconfigurations" { - t.Errorf("unexpected version mapping: %#v %v", m, err) - } - - for _, version := range registered.GroupOrDie(componentconfig.GroupName).GroupVersions { - mapping, err := registered.GroupOrDie(componentconfig.GroupName).RESTMapper.RESTMapping(proxyGVK.GroupKind(), version.Version) - if err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - - if mapping.Resource != "kubeproxyconfigurations" { - t.Errorf("incorrect resource name: %#v", mapping) - } - if mapping.GroupVersionKind.GroupVersion() != version { - t.Errorf("incorrect groupVersion: %v", mapping) - } - - interfaces, _ := registered.GroupOrDie(componentconfig.GroupName).InterfacesFor(version) - if mapping.ObjectConvertor != interfaces.ObjectConvertor { - t.Errorf("unexpected: %#v, expected: %#v", mapping, interfaces) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go index 445449a2c..f3f54626b 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go @@ -1094,6 +1094,32 @@ func (x *ProxyMode) CodecDecodeSelf(d *codec1978.Decoder) { } } +func (x HairpinMode) 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 *HairpinMode) 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 *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -1108,7 +1134,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [77]bool + var yyq2 [78]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[47] = x.CloudProvider != "" @@ -1119,13 +1145,13 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { yyq2[52] = x.CgroupRoot != "" yyq2[54] = x.RktPath != "" yyq2[56] = x.RktStage1Image != "" - yyq2[72] = true - yyq2[73] = x.NodeIP != "" + yyq2[73] = true + yyq2[74] = x.NodeIP != "" var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(77) + r.EncodeArrayStart(78) } else { - yynn2 = 67 + yynn2 = 68 for _, b := range yyq2 { if b { yynn2++ @@ -2354,17 +2380,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym194 if false { } else { - r.EncodeBool(bool(x.HairpinMode)) + r.EncodeString(codecSelferC_UTF81234, string(x.HairpinMode)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("configureHairpinMode")) + r.EncodeString(codecSelferC_UTF81234, string("hairpinMode")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym195 := z.EncBinary() _ = yym195 if false { } else { - r.EncodeBool(bool(x.HairpinMode)) + r.EncodeString(codecSelferC_UTF81234, string(x.HairpinMode)) } } if yyr2 || yy2arr2 { @@ -2373,17 +2399,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym197 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) yym198 := z.EncBinary() _ = yym198 if false { } else { - r.EncodeInt(int64(x.MaxPods)) + r.EncodeBool(bool(x.BabysitDaemons)) } } if yyr2 || yy2arr2 { @@ -2392,17 +2418,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym200 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.DockerExecHandlerName)) + r.EncodeInt(int64(x.MaxPods)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("dockerExecHandlerName")) + r.EncodeString(codecSelferC_UTF81234, string("maxPods")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym201 := z.EncBinary() _ = yym201 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.DockerExecHandlerName)) + r.EncodeInt(int64(x.MaxPods)) } } if yyr2 || yy2arr2 { @@ -2411,17 +2437,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym203 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) yym204 := z.EncBinary() _ = yym204 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.PodCIDR)) + r.EncodeString(codecSelferC_UTF81234, string(x.DockerExecHandlerName)) } } if yyr2 || yy2arr2 { @@ -2430,17 +2456,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym206 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) yym207 := z.EncBinary() _ = yym207 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ResolverConfig)) + r.EncodeString(codecSelferC_UTF81234, string(x.PodCIDR)) } } if yyr2 || yy2arr2 { @@ -2449,17 +2475,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym209 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) yym210 := z.EncBinary() _ = yym210 if false { } else { - r.EncodeBool(bool(x.CPUCFSQuota)) + r.EncodeString(codecSelferC_UTF81234, string(x.ResolverConfig)) } } if yyr2 || yy2arr2 { @@ -2468,17 +2494,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym212 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) yym213 := z.EncBinary() _ = yym213 if false { } else { - r.EncodeBool(bool(x.Containerized)) + r.EncodeBool(bool(x.CPUCFSQuota)) } } if yyr2 || yy2arr2 { @@ -2487,17 +2513,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym215 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) yym216 := z.EncBinary() _ = yym216 if false { } else { - r.EncodeUint(uint64(x.MaxOpenFiles)) + r.EncodeBool(bool(x.Containerized)) } } if yyr2 || yy2arr2 { @@ -2506,17 +2532,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym218 if false { } else { - r.EncodeBool(bool(x.ReconcileCIDR)) + r.EncodeUint(uint64(x.MaxOpenFiles)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("reconcileCIDR")) + r.EncodeString(codecSelferC_UTF81234, string("maxOpenFiles")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym219 := z.EncBinary() _ = yym219 if false { } else { - r.EncodeBool(bool(x.ReconcileCIDR)) + r.EncodeUint(uint64(x.MaxOpenFiles)) } } if yyr2 || yy2arr2 { @@ -2525,17 +2551,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym221 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) yym222 := z.EncBinary() _ = yym222 if false { } else { - r.EncodeBool(bool(x.RegisterSchedulable)) + r.EncodeBool(bool(x.ReconcileCIDR)) } } if yyr2 || yy2arr2 { @@ -2544,17 +2570,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym224 if false { } else { - r.EncodeFloat32(float32(x.KubeAPIQPS)) + r.EncodeBool(bool(x.RegisterSchedulable)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("kubeAPIQPS")) + r.EncodeString(codecSelferC_UTF81234, string("registerSchedulable")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym225 := z.EncBinary() _ = yym225 if false { } else { - r.EncodeFloat32(float32(x.KubeAPIQPS)) + r.EncodeBool(bool(x.RegisterSchedulable)) } } if yyr2 || yy2arr2 { @@ -2563,17 +2589,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym227 if false { } else { - r.EncodeInt(int64(x.KubeAPIBurst)) + r.EncodeFloat32(float32(x.KubeAPIQPS)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("kubeAPIBurst")) + r.EncodeString(codecSelferC_UTF81234, string("kubeAPIQPS")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym228 := z.EncBinary() _ = yym228 if false { } else { - r.EncodeInt(int64(x.KubeAPIBurst)) + r.EncodeFloat32(float32(x.KubeAPIQPS)) } } if yyr2 || yy2arr2 { @@ -2582,17 +2608,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym230 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) yym231 := z.EncBinary() _ = yym231 if false { } else { - r.EncodeBool(bool(x.SerializeImagePulls)) + r.EncodeInt(int64(x.KubeAPIBurst)) } } if yyr2 || yy2arr2 { @@ -2600,6 +2626,25 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { yym233 := z.EncBinary() _ = yym233 if false { + } else { + r.EncodeBool(bool(x.SerializeImagePulls)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("serializeImagePulls")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym234 := z.EncBinary() + _ = yym234 + if false { + } else { + r.EncodeBool(bool(x.SerializeImagePulls)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym236 := z.EncBinary() + _ = yym236 + if false { } else { r.EncodeBool(bool(x.ExperimentalFlannelOverlay)) } @@ -2607,8 +2652,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("experimentalFlannelOverlay")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym234 := z.EncBinary() - _ = yym234 + yym237 := z.EncBinary() + _ = yym237 if false { } else { r.EncodeBool(bool(x.ExperimentalFlannelOverlay)) @@ -2616,42 +2661,42 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[72] { - yy236 := &x.OutOfDiskTransitionFrequency - yym237 := z.EncBinary() - _ = yym237 + if yyq2[73] { + yy239 := &x.OutOfDiskTransitionFrequency + yym240 := z.EncBinary() + _ = yym240 if false { - } else if z.HasExtensions() && z.EncExt(yy236) { - } else if !yym237 && z.IsJSONHandle() { - z.EncJSONMarshal(yy236) + } else if z.HasExtensions() && z.EncExt(yy239) { + } else if !yym240 && z.IsJSONHandle() { + z.EncJSONMarshal(yy239) } else { - z.EncFallback(yy236) + z.EncFallback(yy239) } } else { r.EncodeNil() } } else { - if yyq2[72] { + if yyq2[73] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("outOfDiskTransitionFrequency")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy238 := &x.OutOfDiskTransitionFrequency - yym239 := z.EncBinary() - _ = yym239 + yy241 := &x.OutOfDiskTransitionFrequency + yym242 := z.EncBinary() + _ = yym242 if false { - } else if z.HasExtensions() && z.EncExt(yy238) { - } else if !yym239 && z.IsJSONHandle() { - z.EncJSONMarshal(yy238) + } else if z.HasExtensions() && z.EncExt(yy241) { + } else if !yym242 && z.IsJSONHandle() { + z.EncJSONMarshal(yy241) } else { - z.EncFallback(yy238) + z.EncFallback(yy241) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[73] { - yym241 := z.EncBinary() - _ = yym241 + if yyq2[74] { + yym244 := z.EncBinary() + _ = yym244 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NodeIP)) @@ -2660,12 +2705,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[73] { + if yyq2[74] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeIP")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym242 := z.EncBinary() - _ = yym242 + yym245 := z.EncBinary() + _ = yym245 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NodeIP)) @@ -2677,8 +2722,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { if x.NodeLabels == nil { r.EncodeNil() } else { - yym244 := z.EncBinary() - _ = yym244 + yym247 := z.EncBinary() + _ = yym247 if false { } else { z.F.EncMapStringStringV(x.NodeLabels, false, e) @@ -2691,8 +2736,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { if x.NodeLabels == nil { r.EncodeNil() } else { - yym245 := z.EncBinary() - _ = yym245 + yym248 := z.EncBinary() + _ = yym248 if false { } else { z.F.EncMapStringStringV(x.NodeLabels, false, e) @@ -2701,8 +2746,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym247 := z.EncBinary() - _ = yym247 + yym250 := z.EncBinary() + _ = yym250 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NonMasqueradeCIDR)) @@ -2711,8 +2756,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nonMasqueradeCIDR")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym248 := z.EncBinary() - _ = yym248 + yym251 := z.EncBinary() + _ = yym251 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NonMasqueradeCIDR)) @@ -2720,8 +2765,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym250 := z.EncBinary() - _ = yym250 + yym253 := z.EncBinary() + _ = yym253 if false { } else { r.EncodeBool(bool(x.EnableCustomMetrics)) @@ -2730,8 +2775,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("enableCustomMetrics")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym251 := z.EncBinary() - _ = yym251 + yym254 := z.EncBinary() + _ = yym254 if false { } else { r.EncodeBool(bool(x.EnableCustomMetrics)) @@ -3218,11 +3263,17 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode } else { x.ConfigureCBR0 = bool(r.DecodeBool()) } - case "configureHairpinMode": + case "hairpinMode": if r.TryDecodeAsNil() { - x.HairpinMode = false + x.HairpinMode = "" } else { - x.HairpinMode = bool(r.DecodeBool()) + x.HairpinMode = string(r.DecodeString()) + } + case "babysitDaemons": + if r.TryDecodeAsNil() { + x.BabysitDaemons = false + } else { + x.BabysitDaemons = bool(r.DecodeBool()) } case "maxPods": if r.TryDecodeAsNil() { @@ -3306,15 +3357,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.OutOfDiskTransitionFrequency = pkg1_unversioned.Duration{} } else { - yyv84 := &x.OutOfDiskTransitionFrequency - yym85 := z.DecBinary() - _ = yym85 + yyv85 := &x.OutOfDiskTransitionFrequency + yym86 := z.DecBinary() + _ = yym86 if false { - } else if z.HasExtensions() && z.DecExt(yyv84) { - } else if !yym85 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv84) + } else if z.HasExtensions() && z.DecExt(yyv85) { + } else if !yym86 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv85) } else { - z.DecFallback(yyv84, false) + z.DecFallback(yyv85, false) } } case "nodeIP": @@ -3327,12 +3378,12 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.NodeLabels = nil } else { - yyv87 := &x.NodeLabels - yym88 := z.DecBinary() - _ = yym88 + yyv88 := &x.NodeLabels + yym89 := z.DecBinary() + _ = yym89 if false { } else { - z.F.DecMapStringStringX(yyv87, false, d) + z.F.DecMapStringStringX(yyv88, false, d) } } case "nonMasqueradeCIDR": @@ -3358,16 +3409,16 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj91 int - var yyb91 bool - var yyhl91 bool = l >= 0 - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + var yyj92 int + var yyb92 bool + var yyhl92 bool = l >= 0 + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3377,13 +3428,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.Config = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3391,24 +3442,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.SyncFrequency = pkg1_unversioned.Duration{} } else { - yyv93 := &x.SyncFrequency - yym94 := z.DecBinary() - _ = yym94 + yyv94 := &x.SyncFrequency + yym95 := z.DecBinary() + _ = yym95 if false { - } else if z.HasExtensions() && z.DecExt(yyv93) { - } else if !yym94 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv93) + } else if z.HasExtensions() && z.DecExt(yyv94) { + } else if !yym95 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv94) } else { - z.DecFallback(yyv93, false) + z.DecFallback(yyv94, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3416,24 +3467,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.FileCheckFrequency = pkg1_unversioned.Duration{} } else { - yyv95 := &x.FileCheckFrequency - yym96 := z.DecBinary() - _ = yym96 + yyv96 := &x.FileCheckFrequency + yym97 := z.DecBinary() + _ = yym97 if false { - } else if z.HasExtensions() && z.DecExt(yyv95) { - } else if !yym96 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv95) + } else if z.HasExtensions() && z.DecExt(yyv96) { + } else if !yym97 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv96) } else { - z.DecFallback(yyv95, false) + z.DecFallback(yyv96, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3441,24 +3492,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.HTTPCheckFrequency = pkg1_unversioned.Duration{} } else { - yyv97 := &x.HTTPCheckFrequency - yym98 := z.DecBinary() - _ = yym98 + yyv98 := &x.HTTPCheckFrequency + yym99 := z.DecBinary() + _ = yym99 if false { - } else if z.HasExtensions() && z.DecExt(yyv97) { - } else if !yym98 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv97) + } else if z.HasExtensions() && z.DecExt(yyv98) { + } else if !yym99 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv98) } else { - z.DecFallback(yyv97, false) + z.DecFallback(yyv98, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3468,13 +3519,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ManifestURL = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3484,13 +3535,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ManifestURLHeader = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3500,13 +3551,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EnableServer = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3516,13 +3567,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.Address = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3532,13 +3583,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.Port = uint(r.DecodeUint(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3548,13 +3599,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ReadOnlyPort = uint(r.DecodeUint(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3564,13 +3615,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.TLSCertFile = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3580,13 +3631,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.TLSPrivateKeyFile = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3596,13 +3647,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CertDirectory = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3612,13 +3663,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HostnameOverride = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3628,13 +3679,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.PodInfraContainerImage = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3644,13 +3695,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.DockerEndpoint = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3660,13 +3711,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RootDirectory = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3676,13 +3727,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.AllowPrivileged = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3692,13 +3743,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HostNetworkSources = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3708,13 +3759,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HostPIDSources = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3724,13 +3775,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HostIPCSources = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3740,13 +3791,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RegistryPullQPS = float64(r.DecodeFloat(false)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3756,13 +3807,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RegistryBurst = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3772,13 +3823,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EventRecordQPS = float32(r.DecodeFloat(true)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3788,13 +3839,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EventBurst = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3804,13 +3855,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EnableDebuggingHandlers = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3818,24 +3869,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.MinimumGCAge = pkg1_unversioned.Duration{} } else { - yyv121 := &x.MinimumGCAge - yym122 := z.DecBinary() - _ = yym122 + yyv122 := &x.MinimumGCAge + yym123 := z.DecBinary() + _ = yym123 if false { - } else if z.HasExtensions() && z.DecExt(yyv121) { - } else if !yym122 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv121) + } else if z.HasExtensions() && z.DecExt(yyv122) { + } else if !yym123 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv122) } else { - z.DecFallback(yyv121, false) + z.DecFallback(yyv122, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3845,13 +3896,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MaxPerPodContainerCount = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3861,13 +3912,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MaxContainerCount = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3877,13 +3928,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CAdvisorPort = uint(r.DecodeUint(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3893,13 +3944,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HealthzPort = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3909,13 +3960,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HealthzBindAddress = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3925,13 +3976,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.OOMScoreAdj = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3941,13 +3992,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RegisterNode = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3957,13 +4008,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ClusterDomain = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3973,13 +4024,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MasterServiceNamespace = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3989,13 +4040,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ClusterDNS = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4003,24 +4054,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.StreamingConnectionIdleTimeout = pkg1_unversioned.Duration{} } else { - yyv133 := &x.StreamingConnectionIdleTimeout - yym134 := z.DecBinary() - _ = yym134 + yyv134 := &x.StreamingConnectionIdleTimeout + yym135 := z.DecBinary() + _ = yym135 if false { - } else if z.HasExtensions() && z.DecExt(yyv133) { - } else if !yym134 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv133) + } else if z.HasExtensions() && z.DecExt(yyv134) { + } else if !yym135 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv134) } else { - z.DecFallback(yyv133, false) + z.DecFallback(yyv134, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4028,24 +4079,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.NodeStatusUpdateFrequency = pkg1_unversioned.Duration{} } else { - yyv135 := &x.NodeStatusUpdateFrequency - yym136 := z.DecBinary() - _ = yym136 + yyv136 := &x.NodeStatusUpdateFrequency + yym137 := z.DecBinary() + _ = yym137 if false { - } else if z.HasExtensions() && z.DecExt(yyv135) { - } else if !yym136 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv135) + } else if z.HasExtensions() && z.DecExt(yyv136) { + } else if !yym137 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv136) } else { - z.DecFallback(yyv135, false) + z.DecFallback(yyv136, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4053,24 +4104,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.ImageMinimumGCAge = pkg1_unversioned.Duration{} } else { - yyv137 := &x.ImageMinimumGCAge - yym138 := z.DecBinary() - _ = yym138 + yyv138 := &x.ImageMinimumGCAge + yym139 := z.DecBinary() + _ = yym139 if false { - } else if z.HasExtensions() && z.DecExt(yyv137) { - } else if !yym138 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv137) + } else if z.HasExtensions() && z.DecExt(yyv138) { + } else if !yym139 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv138) } else { - z.DecFallback(yyv137, false) + z.DecFallback(yyv138, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4080,13 +4131,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ImageGCHighThresholdPercent = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4096,13 +4147,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ImageGCLowThresholdPercent = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4112,13 +4163,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.LowDiskSpaceThresholdMB = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4126,24 +4177,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.VolumeStatsAggPeriod = pkg1_unversioned.Duration{} } else { - yyv142 := &x.VolumeStatsAggPeriod - yym143 := z.DecBinary() - _ = yym143 + yyv143 := &x.VolumeStatsAggPeriod + yym144 := z.DecBinary() + _ = yym144 if false { - } else if z.HasExtensions() && z.DecExt(yyv142) { - } else if !yym143 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv142) + } else if z.HasExtensions() && z.DecExt(yyv143) { + } else if !yym144 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv143) } else { - z.DecFallback(yyv142, false) + z.DecFallback(yyv143, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4153,13 +4204,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NetworkPluginName = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4169,13 +4220,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NetworkPluginDir = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4185,13 +4236,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.VolumePluginDir = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4201,13 +4252,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CloudProvider = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4217,13 +4268,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CloudConfigFile = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4233,13 +4284,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.KubeletCgroups = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4249,13 +4300,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RuntimeCgroups = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4265,13 +4316,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.SystemCgroups = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4281,13 +4332,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CgroupRoot = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4297,13 +4348,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ContainerRuntime = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4313,13 +4364,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RktPath = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4329,13 +4380,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.LockFilePath = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4345,13 +4396,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RktStage1Image = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4361,29 +4412,45 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ConfigureCBR0 = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.HairpinMode = false + x.HairpinMode = "" } else { - x.HairpinMode = bool(r.DecodeBool()) + x.HairpinMode = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.BabysitDaemons = false + } else { + x.BabysitDaemons = bool(r.DecodeBool()) + } + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l + } else { + yyb92 = r.CheckBreak() + } + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4393,13 +4460,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MaxPods = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4409,13 +4476,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.DockerExecHandlerName = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4425,13 +4492,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.PodCIDR = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4441,13 +4508,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ResolverConfig = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4457,13 +4524,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CPUCFSQuota = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4473,13 +4540,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.Containerized = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4489,13 +4556,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MaxOpenFiles = uint64(r.DecodeUint(64)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4505,13 +4572,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ReconcileCIDR = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4521,13 +4588,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RegisterSchedulable = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4537,13 +4604,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.KubeAPIQPS = float32(r.DecodeFloat(true)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4553,13 +4620,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.KubeAPIBurst = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4569,13 +4636,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.SerializeImagePulls = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4585,13 +4652,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ExperimentalFlannelOverlay = bool(r.DecodeBool()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4599,24 +4666,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.OutOfDiskTransitionFrequency = pkg1_unversioned.Duration{} } else { - yyv172 := &x.OutOfDiskTransitionFrequency - yym173 := z.DecBinary() - _ = yym173 + yyv174 := &x.OutOfDiskTransitionFrequency + yym175 := z.DecBinary() + _ = yym175 if false { - } else if z.HasExtensions() && z.DecExt(yyv172) { - } else if !yym173 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv172) + } else if z.HasExtensions() && z.DecExt(yyv174) { + } else if !yym175 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv174) } else { - z.DecFallback(yyv172, false) + z.DecFallback(yyv174, false) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4626,13 +4693,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NodeIP = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4640,21 +4707,21 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.NodeLabels = nil } else { - yyv175 := &x.NodeLabels - yym176 := z.DecBinary() - _ = yym176 + yyv177 := &x.NodeLabels + yym178 := z.DecBinary() + _ = yym178 if false { } else { - z.F.DecMapStringStringX(yyv175, false, d) + z.F.DecMapStringStringX(yyv177, false, d) } } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4664,13 +4731,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NonMasqueradeCIDR = string(r.DecodeString()) } - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4681,17 +4748,17 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco x.EnableCustomMetrics = bool(r.DecodeBool()) } for { - yyj91++ - if yyhl91 { - yyb91 = yyj91 > l + yyj92++ + if yyhl92 { + yyb92 = yyj92 > l } else { - yyb91 = r.CheckBreak() + yyb92 = r.CheckBreak() } - if yyb91 { + if yyb92 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj91-1, "") + z.DecStructFieldNotFound(yyj92-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -5653,16 +5720,16 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [40]bool + var yyq2 [43]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[38] = x.Kind != "" - yyq2[39] = x.APIVersion != "" + yyq2[41] = x.Kind != "" + yyq2[42] = x.APIVersion != "" var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(40) + r.EncodeArrayStart(43) } else { - yynn2 = 38 + yynn2 = 41 for _, b := range yyq2 { if b { yynn2++ @@ -5901,170 +5968,227 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy40 := &x.ServiceSyncPeriod + yym40 := z.EncBinary() + _ = yym40 + if false { + } else { + r.EncodeInt(int64(x.LookupCacheSizeForRC)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForRC")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) yym41 := z.EncBinary() _ = yym41 if false { - } else if z.HasExtensions() && z.EncExt(yy40) { - } else if !yym41 && z.IsJSONHandle() { - z.EncJSONMarshal(yy40) } else { - z.EncFallback(yy40) + r.EncodeInt(int64(x.LookupCacheSizeForRC)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym43 := z.EncBinary() + _ = yym43 + if false { + } else { + r.EncodeInt(int64(x.LookupCacheSizeForRS)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForRS")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym44 := z.EncBinary() + _ = yym44 + if false { + } else { + r.EncodeInt(int64(x.LookupCacheSizeForRS)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym46 := z.EncBinary() + _ = yym46 + if false { + } else { + r.EncodeInt(int64(x.LookupCacheSizeForDaemonSet)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForDaemonSet")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym47 := z.EncBinary() + _ = yym47 + if false { + } else { + r.EncodeInt(int64(x.LookupCacheSizeForDaemonSet)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy49 := &x.ServiceSyncPeriod + yym50 := z.EncBinary() + _ = yym50 + if false { + } else if z.HasExtensions() && z.EncExt(yy49) { + } else if !yym50 && z.IsJSONHandle() { + z.EncJSONMarshal(yy49) + } else { + z.EncFallback(yy49) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("serviceSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy42 := &x.ServiceSyncPeriod - yym43 := z.EncBinary() - _ = yym43 + yy51 := &x.ServiceSyncPeriod + yym52 := z.EncBinary() + _ = yym52 if false { - } else if z.HasExtensions() && z.EncExt(yy42) { - } else if !yym43 && z.IsJSONHandle() { - z.EncJSONMarshal(yy42) + } else if z.HasExtensions() && z.EncExt(yy51) { + } else if !yym52 && z.IsJSONHandle() { + z.EncJSONMarshal(yy51) } else { - z.EncFallback(yy42) + z.EncFallback(yy51) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy45 := &x.NodeSyncPeriod - yym46 := z.EncBinary() - _ = yym46 + yy54 := &x.NodeSyncPeriod + yym55 := z.EncBinary() + _ = yym55 if false { - } else if z.HasExtensions() && z.EncExt(yy45) { - } else if !yym46 && z.IsJSONHandle() { - z.EncJSONMarshal(yy45) + } else if z.HasExtensions() && z.EncExt(yy54) { + } else if !yym55 && z.IsJSONHandle() { + z.EncJSONMarshal(yy54) } else { - z.EncFallback(yy45) + z.EncFallback(yy54) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy47 := &x.NodeSyncPeriod - yym48 := z.EncBinary() - _ = yym48 + yy56 := &x.NodeSyncPeriod + yym57 := z.EncBinary() + _ = yym57 if false { - } else if z.HasExtensions() && z.EncExt(yy47) { - } else if !yym48 && z.IsJSONHandle() { - z.EncJSONMarshal(yy47) + } else if z.HasExtensions() && z.EncExt(yy56) { + } else if !yym57 && z.IsJSONHandle() { + z.EncJSONMarshal(yy56) } else { - z.EncFallback(yy47) + z.EncFallback(yy56) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy50 := &x.ResourceQuotaSyncPeriod - yym51 := z.EncBinary() - _ = yym51 + yy59 := &x.ResourceQuotaSyncPeriod + yym60 := z.EncBinary() + _ = yym60 if false { - } else if z.HasExtensions() && z.EncExt(yy50) { - } else if !yym51 && z.IsJSONHandle() { - z.EncJSONMarshal(yy50) + } else if z.HasExtensions() && z.EncExt(yy59) { + } else if !yym60 && z.IsJSONHandle() { + z.EncJSONMarshal(yy59) } else { - z.EncFallback(yy50) + z.EncFallback(yy59) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("resourceQuotaSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy52 := &x.ResourceQuotaSyncPeriod - yym53 := z.EncBinary() - _ = yym53 + yy61 := &x.ResourceQuotaSyncPeriod + yym62 := z.EncBinary() + _ = yym62 if false { - } else if z.HasExtensions() && z.EncExt(yy52) { - } else if !yym53 && z.IsJSONHandle() { - z.EncJSONMarshal(yy52) + } else if z.HasExtensions() && z.EncExt(yy61) { + } else if !yym62 && z.IsJSONHandle() { + z.EncJSONMarshal(yy61) } else { - z.EncFallback(yy52) + z.EncFallback(yy61) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy55 := &x.NamespaceSyncPeriod - yym56 := z.EncBinary() - _ = yym56 + yy64 := &x.NamespaceSyncPeriod + yym65 := z.EncBinary() + _ = yym65 if false { - } else if z.HasExtensions() && z.EncExt(yy55) { - } else if !yym56 && z.IsJSONHandle() { - z.EncJSONMarshal(yy55) + } else if z.HasExtensions() && z.EncExt(yy64) { + } else if !yym65 && z.IsJSONHandle() { + z.EncJSONMarshal(yy64) } else { - z.EncFallback(yy55) + z.EncFallback(yy64) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("namespaceSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy57 := &x.NamespaceSyncPeriod - yym58 := z.EncBinary() - _ = yym58 + yy66 := &x.NamespaceSyncPeriod + yym67 := z.EncBinary() + _ = yym67 if false { - } else if z.HasExtensions() && z.EncExt(yy57) { - } else if !yym58 && z.IsJSONHandle() { - z.EncJSONMarshal(yy57) + } else if z.HasExtensions() && z.EncExt(yy66) { + } else if !yym67 && z.IsJSONHandle() { + z.EncJSONMarshal(yy66) } else { - z.EncFallback(yy57) + z.EncFallback(yy66) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy60 := &x.PVClaimBinderSyncPeriod - yym61 := z.EncBinary() - _ = yym61 + yy69 := &x.PVClaimBinderSyncPeriod + yym70 := z.EncBinary() + _ = yym70 if false { - } else if z.HasExtensions() && z.EncExt(yy60) { - } else if !yym61 && z.IsJSONHandle() { - z.EncJSONMarshal(yy60) + } else if z.HasExtensions() && z.EncExt(yy69) { + } else if !yym70 && z.IsJSONHandle() { + z.EncJSONMarshal(yy69) } else { - z.EncFallback(yy60) + z.EncFallback(yy69) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("pvClaimBinderSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy62 := &x.PVClaimBinderSyncPeriod - yym63 := z.EncBinary() - _ = yym63 + yy71 := &x.PVClaimBinderSyncPeriod + yym72 := z.EncBinary() + _ = yym72 if false { - } else if z.HasExtensions() && z.EncExt(yy62) { - } else if !yym63 && z.IsJSONHandle() { - z.EncJSONMarshal(yy62) + } else if z.HasExtensions() && z.EncExt(yy71) { + } else if !yym72 && z.IsJSONHandle() { + z.EncJSONMarshal(yy71) } else { - z.EncFallback(yy62) + z.EncFallback(yy71) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy65 := &x.MinResyncPeriod - yym66 := z.EncBinary() - _ = yym66 + yy74 := &x.MinResyncPeriod + yym75 := z.EncBinary() + _ = yym75 if false { - } else if z.HasExtensions() && z.EncExt(yy65) { - } else if !yym66 && z.IsJSONHandle() { - z.EncJSONMarshal(yy65) + } else if z.HasExtensions() && z.EncExt(yy74) { + } else if !yym75 && z.IsJSONHandle() { + z.EncJSONMarshal(yy74) } else { - z.EncFallback(yy65) + z.EncFallback(yy74) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("minResyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy67 := &x.MinResyncPeriod - yym68 := z.EncBinary() - _ = yym68 + yy76 := &x.MinResyncPeriod + yym77 := z.EncBinary() + _ = yym77 if false { - } else if z.HasExtensions() && z.EncExt(yy67) { - } else if !yym68 && z.IsJSONHandle() { - z.EncJSONMarshal(yy67) + } else if z.HasExtensions() && z.EncExt(yy76) { + } else if !yym77 && z.IsJSONHandle() { + z.EncJSONMarshal(yy76) } else { - z.EncFallback(yy67) + z.EncFallback(yy76) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym70 := z.EncBinary() - _ = yym70 + yym79 := z.EncBinary() + _ = yym79 if false { } else { r.EncodeInt(int64(x.TerminatedPodGCThreshold)) @@ -6073,8 +6197,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("terminatedPodGCThreshold")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym71 := z.EncBinary() - _ = yym71 + yym80 := z.EncBinary() + _ = yym80 if false { } else { r.EncodeInt(int64(x.TerminatedPodGCThreshold)) @@ -6082,126 +6206,75 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy73 := &x.HorizontalPodAutoscalerSyncPeriod - yym74 := z.EncBinary() - _ = yym74 + yy82 := &x.HorizontalPodAutoscalerSyncPeriod + yym83 := z.EncBinary() + _ = yym83 if false { - } else if z.HasExtensions() && z.EncExt(yy73) { - } else if !yym74 && z.IsJSONHandle() { - z.EncJSONMarshal(yy73) + } else if z.HasExtensions() && z.EncExt(yy82) { + } else if !yym83 && z.IsJSONHandle() { + z.EncJSONMarshal(yy82) } else { - z.EncFallback(yy73) + z.EncFallback(yy82) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("horizontalPodAutoscalerSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy75 := &x.HorizontalPodAutoscalerSyncPeriod - yym76 := z.EncBinary() - _ = yym76 + yy84 := &x.HorizontalPodAutoscalerSyncPeriod + yym85 := z.EncBinary() + _ = yym85 if false { - } else if z.HasExtensions() && z.EncExt(yy75) { - } else if !yym76 && z.IsJSONHandle() { - z.EncJSONMarshal(yy75) + } else if z.HasExtensions() && z.EncExt(yy84) { + } else if !yym85 && z.IsJSONHandle() { + z.EncJSONMarshal(yy84) } else { - z.EncFallback(yy75) + z.EncFallback(yy84) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy78 := &x.DeploymentControllerSyncPeriod - yym79 := z.EncBinary() - _ = yym79 + yy87 := &x.DeploymentControllerSyncPeriod + yym88 := z.EncBinary() + _ = yym88 if false { - } else if z.HasExtensions() && z.EncExt(yy78) { - } else if !yym79 && z.IsJSONHandle() { - z.EncJSONMarshal(yy78) + } else if z.HasExtensions() && z.EncExt(yy87) { + } else if !yym88 && z.IsJSONHandle() { + z.EncJSONMarshal(yy87) } else { - z.EncFallback(yy78) + z.EncFallback(yy87) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("deploymentControllerSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy80 := &x.DeploymentControllerSyncPeriod - yym81 := z.EncBinary() - _ = yym81 + yy89 := &x.DeploymentControllerSyncPeriod + yym90 := z.EncBinary() + _ = yym90 if false { - } else if z.HasExtensions() && z.EncExt(yy80) { - } else if !yym81 && z.IsJSONHandle() { - z.EncJSONMarshal(yy80) + } else if z.HasExtensions() && z.EncExt(yy89) { + } else if !yym90 && z.IsJSONHandle() { + z.EncJSONMarshal(yy89) } else { - z.EncFallback(yy80) + z.EncFallback(yy89) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy83 := &x.PodEvictionTimeout - yym84 := z.EncBinary() - _ = yym84 + yy92 := &x.PodEvictionTimeout + yym93 := z.EncBinary() + _ = yym93 if false { - } else if z.HasExtensions() && z.EncExt(yy83) { - } else if !yym84 && z.IsJSONHandle() { - z.EncJSONMarshal(yy83) + } else if z.HasExtensions() && z.EncExt(yy92) { + } else if !yym93 && z.IsJSONHandle() { + z.EncJSONMarshal(yy92) } else { - z.EncFallback(yy83) + z.EncFallback(yy92) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("podEvictionTimeout")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy85 := &x.PodEvictionTimeout - yym86 := z.EncBinary() - _ = yym86 - if false { - } else if z.HasExtensions() && z.EncExt(yy85) { - } else if !yym86 && z.IsJSONHandle() { - z.EncJSONMarshal(yy85) - } else { - z.EncFallback(yy85) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym88 := z.EncBinary() - _ = yym88 - if false { - } else { - r.EncodeFloat32(float32(x.DeletingPodsQps)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("deletingPodsQps")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym89 := z.EncBinary() - _ = yym89 - if false { - } else { - r.EncodeFloat32(float32(x.DeletingPodsQps)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym91 := z.EncBinary() - _ = yym91 - if false { - } else { - r.EncodeInt(int64(x.DeletingPodsBurst)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("deletingPodsBurst")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym92 := z.EncBinary() - _ = yym92 - if false { - } else { - r.EncodeInt(int64(x.DeletingPodsBurst)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy94 := &x.NodeMonitorGracePeriod + yy94 := &x.PodEvictionTimeout yym95 := z.EncBinary() _ = yym95 if false { @@ -6211,25 +6284,76 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy94) } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("nodeMonitorGracePeriod")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy96 := &x.NodeMonitorGracePeriod + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym97 := z.EncBinary() _ = yym97 if false { - } else if z.HasExtensions() && z.EncExt(yy96) { - } else if !yym97 && z.IsJSONHandle() { - z.EncJSONMarshal(yy96) } else { - z.EncFallback(yy96) + r.EncodeFloat32(float32(x.DeletingPodsQps)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("deletingPodsQps")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym98 := z.EncBinary() + _ = yym98 + if false { + } else { + r.EncodeFloat32(float32(x.DeletingPodsQps)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym99 := z.EncBinary() - _ = yym99 + yym100 := z.EncBinary() + _ = yym100 + if false { + } else { + r.EncodeInt(int64(x.DeletingPodsBurst)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("deletingPodsBurst")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym101 := z.EncBinary() + _ = yym101 + if false { + } else { + r.EncodeInt(int64(x.DeletingPodsBurst)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy103 := &x.NodeMonitorGracePeriod + yym104 := z.EncBinary() + _ = yym104 + if false { + } else if z.HasExtensions() && z.EncExt(yy103) { + } else if !yym104 && z.IsJSONHandle() { + z.EncJSONMarshal(yy103) + } else { + z.EncFallback(yy103) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("nodeMonitorGracePeriod")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy105 := &x.NodeMonitorGracePeriod + yym106 := z.EncBinary() + _ = yym106 + if false { + } else if z.HasExtensions() && z.EncExt(yy105) { + } else if !yym106 && z.IsJSONHandle() { + z.EncJSONMarshal(yy105) + } else { + z.EncFallback(yy105) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym108 := z.EncBinary() + _ = yym108 if false { } else { r.EncodeInt(int64(x.RegisterRetryCount)) @@ -6238,8 +6362,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("registerRetryCount")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym100 := z.EncBinary() - _ = yym100 + yym109 := z.EncBinary() + _ = yym109 if false { } else { r.EncodeInt(int64(x.RegisterRetryCount)) @@ -6247,113 +6371,56 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy102 := &x.NodeStartupGracePeriod - yym103 := z.EncBinary() - _ = yym103 + yy111 := &x.NodeStartupGracePeriod + yym112 := z.EncBinary() + _ = yym112 if false { - } else if z.HasExtensions() && z.EncExt(yy102) { - } else if !yym103 && z.IsJSONHandle() { - z.EncJSONMarshal(yy102) + } else if z.HasExtensions() && z.EncExt(yy111) { + } else if !yym112 && z.IsJSONHandle() { + z.EncJSONMarshal(yy111) } else { - z.EncFallback(yy102) + z.EncFallback(yy111) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeStartupGracePeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy104 := &x.NodeStartupGracePeriod - yym105 := z.EncBinary() - _ = yym105 + yy113 := &x.NodeStartupGracePeriod + yym114 := z.EncBinary() + _ = yym114 if false { - } else if z.HasExtensions() && z.EncExt(yy104) { - } else if !yym105 && z.IsJSONHandle() { - z.EncJSONMarshal(yy104) + } else if z.HasExtensions() && z.EncExt(yy113) { + } else if !yym114 && z.IsJSONHandle() { + z.EncJSONMarshal(yy113) } else { - z.EncFallback(yy104) + z.EncFallback(yy113) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy107 := &x.NodeMonitorPeriod - yym108 := z.EncBinary() - _ = yym108 + yy116 := &x.NodeMonitorPeriod + yym117 := z.EncBinary() + _ = yym117 if false { - } else if z.HasExtensions() && z.EncExt(yy107) { - } else if !yym108 && z.IsJSONHandle() { - z.EncJSONMarshal(yy107) + } else if z.HasExtensions() && z.EncExt(yy116) { + } else if !yym117 && z.IsJSONHandle() { + z.EncJSONMarshal(yy116) } else { - z.EncFallback(yy107) + z.EncFallback(yy116) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeMonitorPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy109 := &x.NodeMonitorPeriod - yym110 := z.EncBinary() - _ = yym110 - if false { - } else if z.HasExtensions() && z.EncExt(yy109) { - } else if !yym110 && z.IsJSONHandle() { - z.EncJSONMarshal(yy109) - } else { - z.EncFallback(yy109) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym112 := z.EncBinary() - _ = yym112 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ServiceAccountKeyFile)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("serviceAccountKeyFile")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym113 := z.EncBinary() - _ = yym113 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ServiceAccountKeyFile)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym115 := z.EncBinary() - _ = yym115 - if false { - } else { - r.EncodeBool(bool(x.EnableProfiling)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("enableProfiling")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym116 := z.EncBinary() - _ = yym116 - if false { - } else { - r.EncodeBool(bool(x.EnableProfiling)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym118 := z.EncBinary() - _ = yym118 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ClusterName)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("clusterName")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy118 := &x.NodeMonitorPeriod yym119 := z.EncBinary() _ = yym119 if false { + } else if z.HasExtensions() && z.EncExt(yy118) { + } else if !yym119 && z.IsJSONHandle() { + z.EncJSONMarshal(yy118) } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ClusterName)) + z.EncFallback(yy118) } } if yyr2 || yy2arr2 { @@ -6362,17 +6429,17 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode _ = yym121 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ClusterCIDR)) + r.EncodeString(codecSelferC_UTF81234, string(x.ServiceAccountKeyFile)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("clusterCIDR")) + r.EncodeString(codecSelferC_UTF81234, string("serviceAccountKeyFile")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym122 := z.EncBinary() _ = yym122 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ClusterCIDR)) + r.EncodeString(codecSelferC_UTF81234, string(x.ServiceAccountKeyFile)) } } if yyr2 || yy2arr2 { @@ -6381,17 +6448,17 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode _ = yym124 if false { } else { - r.EncodeBool(bool(x.AllocateNodeCIDRs)) + r.EncodeBool(bool(x.EnableProfiling)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("allocateNodeCIDRs")) + r.EncodeString(codecSelferC_UTF81234, string("enableProfiling")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym125 := z.EncBinary() _ = yym125 if false { } else { - r.EncodeBool(bool(x.AllocateNodeCIDRs)) + r.EncodeBool(bool(x.EnableProfiling)) } } if yyr2 || yy2arr2 { @@ -6400,17 +6467,17 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode _ = yym127 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.RootCAFile)) + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterName)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("rootCAFile")) + r.EncodeString(codecSelferC_UTF81234, string("clusterName")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym128 := z.EncBinary() _ = yym128 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.RootCAFile)) + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterName)) } } if yyr2 || yy2arr2 { @@ -6419,17 +6486,17 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode _ = yym130 if false { } else { - r.EncodeFloat32(float32(x.KubeAPIQPS)) + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterCIDR)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("kubeAPIQPS")) + r.EncodeString(codecSelferC_UTF81234, string("clusterCIDR")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym131 := z.EncBinary() _ = yym131 if false { } else { - r.EncodeFloat32(float32(x.KubeAPIQPS)) + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterCIDR)) } } if yyr2 || yy2arr2 { @@ -6437,6 +6504,63 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode yym133 := z.EncBinary() _ = yym133 if false { + } else { + r.EncodeBool(bool(x.AllocateNodeCIDRs)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("allocateNodeCIDRs")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym134 := z.EncBinary() + _ = yym134 + if false { + } else { + r.EncodeBool(bool(x.AllocateNodeCIDRs)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym136 := z.EncBinary() + _ = yym136 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.RootCAFile)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("rootCAFile")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym137 := z.EncBinary() + _ = yym137 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.RootCAFile)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym139 := z.EncBinary() + _ = yym139 + if false { + } else { + r.EncodeFloat32(float32(x.KubeAPIQPS)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kubeAPIQPS")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym140 := z.EncBinary() + _ = yym140 + if false { + } else { + r.EncodeFloat32(float32(x.KubeAPIQPS)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym142 := z.EncBinary() + _ = yym142 + if false { } else { r.EncodeInt(int64(x.KubeAPIBurst)) } @@ -6444,8 +6568,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kubeAPIBurst")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym134 := z.EncBinary() - _ = yym134 + yym143 := z.EncBinary() + _ = yym143 if false { } else { r.EncodeInt(int64(x.KubeAPIBurst)) @@ -6453,31 +6577,31 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy136 := &x.LeaderElection - yy136.CodecEncodeSelf(e) + yy145 := &x.LeaderElection + yy145.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("leaderElection")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy138 := &x.LeaderElection - yy138.CodecEncodeSelf(e) + yy147 := &x.LeaderElection + yy147.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy141 := &x.VolumeConfiguration - yy141.CodecEncodeSelf(e) + yy150 := &x.VolumeConfiguration + yy150.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("volumeConfiguration")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy143 := &x.VolumeConfiguration - yy143.CodecEncodeSelf(e) + yy152 := &x.VolumeConfiguration + yy152.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[38] { - yym146 := z.EncBinary() - _ = yym146 + if yyq2[41] { + yym155 := z.EncBinary() + _ = yym155 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) @@ -6486,12 +6610,12 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[38] { + if yyq2[41] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kind")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym147 := z.EncBinary() - _ = yym147 + yym156 := z.EncBinary() + _ = yym156 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) @@ -6500,9 +6624,9 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[39] { - yym149 := z.EncBinary() - _ = yym149 + if yyq2[42] { + yym158 := z.EncBinary() + _ = yym158 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) @@ -6511,12 +6635,12 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[39] { + if yyq2[42] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym150 := z.EncBinary() - _ = yym150 + yym159 := z.EncBinary() + _ = yym159 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) @@ -6656,94 +6780,112 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co } else { x.ConcurrentNamespaceSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } + case "lookupCacheSizeForRC": + if r.TryDecodeAsNil() { + x.LookupCacheSizeForRC = 0 + } else { + x.LookupCacheSizeForRC = int(r.DecodeInt(codecSelferBitsize1234)) + } + case "lookupCacheSizeForRS": + if r.TryDecodeAsNil() { + x.LookupCacheSizeForRS = 0 + } else { + x.LookupCacheSizeForRS = int(r.DecodeInt(codecSelferBitsize1234)) + } + case "lookupCacheSizeForDaemonSet": + if r.TryDecodeAsNil() { + x.LookupCacheSizeForDaemonSet = 0 + } else { + x.LookupCacheSizeForDaemonSet = int(r.DecodeInt(codecSelferBitsize1234)) + } case "serviceSyncPeriod": if r.TryDecodeAsNil() { x.ServiceSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv16 := &x.ServiceSyncPeriod - yym17 := z.DecBinary() - _ = yym17 + yyv19 := &x.ServiceSyncPeriod + yym20 := z.DecBinary() + _ = yym20 if false { - } else if z.HasExtensions() && z.DecExt(yyv16) { - } else if !yym17 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv16) + } else if z.HasExtensions() && z.DecExt(yyv19) { + } else if !yym20 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv19) } else { - z.DecFallback(yyv16, false) + z.DecFallback(yyv19, false) } } case "nodeSyncPeriod": if r.TryDecodeAsNil() { x.NodeSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv18 := &x.NodeSyncPeriod - yym19 := z.DecBinary() - _ = yym19 + yyv21 := &x.NodeSyncPeriod + yym22 := z.DecBinary() + _ = yym22 if false { - } else if z.HasExtensions() && z.DecExt(yyv18) { - } else if !yym19 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv18) + } else if z.HasExtensions() && z.DecExt(yyv21) { + } else if !yym22 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv21) } else { - z.DecFallback(yyv18, false) + z.DecFallback(yyv21, false) } } case "resourceQuotaSyncPeriod": if r.TryDecodeAsNil() { x.ResourceQuotaSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv20 := &x.ResourceQuotaSyncPeriod - yym21 := z.DecBinary() - _ = yym21 + yyv23 := &x.ResourceQuotaSyncPeriod + yym24 := z.DecBinary() + _ = yym24 if false { - } else if z.HasExtensions() && z.DecExt(yyv20) { - } else if !yym21 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv20) + } else if z.HasExtensions() && z.DecExt(yyv23) { + } else if !yym24 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv23) } else { - z.DecFallback(yyv20, false) + z.DecFallback(yyv23, false) } } case "namespaceSyncPeriod": if r.TryDecodeAsNil() { x.NamespaceSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv22 := &x.NamespaceSyncPeriod - yym23 := z.DecBinary() - _ = yym23 + yyv25 := &x.NamespaceSyncPeriod + yym26 := z.DecBinary() + _ = yym26 if false { - } else if z.HasExtensions() && z.DecExt(yyv22) { - } else if !yym23 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv22) + } else if z.HasExtensions() && z.DecExt(yyv25) { + } else if !yym26 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv25) } else { - z.DecFallback(yyv22, false) + z.DecFallback(yyv25, false) } } case "pvClaimBinderSyncPeriod": if r.TryDecodeAsNil() { x.PVClaimBinderSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv24 := &x.PVClaimBinderSyncPeriod - yym25 := z.DecBinary() - _ = yym25 + yyv27 := &x.PVClaimBinderSyncPeriod + yym28 := z.DecBinary() + _ = yym28 if false { - } else if z.HasExtensions() && z.DecExt(yyv24) { - } else if !yym25 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv24) + } else if z.HasExtensions() && z.DecExt(yyv27) { + } else if !yym28 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv27) } else { - z.DecFallback(yyv24, false) + z.DecFallback(yyv27, false) } } case "minResyncPeriod": if r.TryDecodeAsNil() { x.MinResyncPeriod = pkg1_unversioned.Duration{} } else { - yyv26 := &x.MinResyncPeriod - yym27 := z.DecBinary() - _ = yym27 + yyv29 := &x.MinResyncPeriod + yym30 := z.DecBinary() + _ = yym30 if false { - } else if z.HasExtensions() && z.DecExt(yyv26) { - } else if !yym27 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv26) + } else if z.HasExtensions() && z.DecExt(yyv29) { + } else if !yym30 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv29) } else { - z.DecFallback(yyv26, false) + z.DecFallback(yyv29, false) } } case "terminatedPodGCThreshold": @@ -6756,45 +6898,45 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.HorizontalPodAutoscalerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv29 := &x.HorizontalPodAutoscalerSyncPeriod - yym30 := z.DecBinary() - _ = yym30 + yyv32 := &x.HorizontalPodAutoscalerSyncPeriod + yym33 := z.DecBinary() + _ = yym33 if false { - } else if z.HasExtensions() && z.DecExt(yyv29) { - } else if !yym30 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv29) + } else if z.HasExtensions() && z.DecExt(yyv32) { + } else if !yym33 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv32) } else { - z.DecFallback(yyv29, false) + z.DecFallback(yyv32, false) } } case "deploymentControllerSyncPeriod": if r.TryDecodeAsNil() { x.DeploymentControllerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv31 := &x.DeploymentControllerSyncPeriod - yym32 := z.DecBinary() - _ = yym32 + yyv34 := &x.DeploymentControllerSyncPeriod + yym35 := z.DecBinary() + _ = yym35 if false { - } else if z.HasExtensions() && z.DecExt(yyv31) { - } else if !yym32 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv31) + } else if z.HasExtensions() && z.DecExt(yyv34) { + } else if !yym35 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv34) } else { - z.DecFallback(yyv31, false) + z.DecFallback(yyv34, false) } } case "podEvictionTimeout": if r.TryDecodeAsNil() { x.PodEvictionTimeout = pkg1_unversioned.Duration{} } else { - yyv33 := &x.PodEvictionTimeout - yym34 := z.DecBinary() - _ = yym34 + yyv36 := &x.PodEvictionTimeout + yym37 := z.DecBinary() + _ = yym37 if false { - } else if z.HasExtensions() && z.DecExt(yyv33) { - } else if !yym34 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv33) + } else if z.HasExtensions() && z.DecExt(yyv36) { + } else if !yym37 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv36) } else { - z.DecFallback(yyv33, false) + z.DecFallback(yyv36, false) } } case "deletingPodsQps": @@ -6813,15 +6955,15 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.NodeMonitorGracePeriod = pkg1_unversioned.Duration{} } else { - yyv37 := &x.NodeMonitorGracePeriod - yym38 := z.DecBinary() - _ = yym38 + yyv40 := &x.NodeMonitorGracePeriod + yym41 := z.DecBinary() + _ = yym41 if false { - } else if z.HasExtensions() && z.DecExt(yyv37) { - } else if !yym38 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv37) + } else if z.HasExtensions() && z.DecExt(yyv40) { + } else if !yym41 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv40) } else { - z.DecFallback(yyv37, false) + z.DecFallback(yyv40, false) } } case "registerRetryCount": @@ -6834,30 +6976,30 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.NodeStartupGracePeriod = pkg1_unversioned.Duration{} } else { - yyv40 := &x.NodeStartupGracePeriod - yym41 := z.DecBinary() - _ = yym41 + yyv43 := &x.NodeStartupGracePeriod + yym44 := z.DecBinary() + _ = yym44 if false { - } else if z.HasExtensions() && z.DecExt(yyv40) { - } else if !yym41 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv40) + } else if z.HasExtensions() && z.DecExt(yyv43) { + } else if !yym44 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv43) } else { - z.DecFallback(yyv40, false) + z.DecFallback(yyv43, false) } } case "nodeMonitorPeriod": if r.TryDecodeAsNil() { x.NodeMonitorPeriod = pkg1_unversioned.Duration{} } else { - yyv42 := &x.NodeMonitorPeriod - yym43 := z.DecBinary() - _ = yym43 + yyv45 := &x.NodeMonitorPeriod + yym46 := z.DecBinary() + _ = yym46 if false { - } else if z.HasExtensions() && z.DecExt(yyv42) { - } else if !yym43 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv42) + } else if z.HasExtensions() && z.DecExt(yyv45) { + } else if !yym46 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv45) } else { - z.DecFallback(yyv42, false) + z.DecFallback(yyv45, false) } } case "serviceAccountKeyFile": @@ -6912,15 +7054,15 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.LeaderElection = LeaderElectionConfiguration{} } else { - yyv52 := &x.LeaderElection - yyv52.CodecDecodeSelf(d) + yyv55 := &x.LeaderElection + yyv55.CodecDecodeSelf(d) } case "volumeConfiguration": if r.TryDecodeAsNil() { x.VolumeConfiguration = VolumeConfiguration{} } else { - yyv53 := &x.VolumeConfiguration - yyv53.CodecDecodeSelf(d) + yyv56 := &x.VolumeConfiguration + yyv56.CodecDecodeSelf(d) } case "kind": if r.TryDecodeAsNil() { @@ -6945,16 +7087,16 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj56 int - var yyb56 bool - var yyhl56 bool = l >= 0 - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + var yyj59 int + var yyb59 bool + var yyhl59 bool = l >= 0 + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -6964,13 +7106,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.Port = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -6980,13 +7122,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.Address = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -6996,13 +7138,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.CloudProvider = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7012,13 +7154,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.CloudConfigFile = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7028,13 +7170,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentEndpointSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7044,13 +7186,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentRSSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7060,13 +7202,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentRCSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7076,13 +7218,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentResourceQuotaSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7092,13 +7234,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentDeploymentSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7108,13 +7250,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentDaemonSetSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7124,13 +7266,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentJobSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7140,13 +7282,61 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentNamespaceSyncs = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.LookupCacheSizeForRC = 0 + } else { + x.LookupCacheSizeForRC = int(r.DecodeInt(codecSelferBitsize1234)) + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.LookupCacheSizeForRS = 0 + } else { + x.LookupCacheSizeForRS = int(r.DecodeInt(codecSelferBitsize1234)) + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.LookupCacheSizeForDaemonSet = 0 + } else { + x.LookupCacheSizeForDaemonSet = int(r.DecodeInt(codecSelferBitsize1234)) + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7154,82 +7344,7 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.ServiceSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv69 := &x.ServiceSyncPeriod - yym70 := z.DecBinary() - _ = yym70 - if false { - } else if z.HasExtensions() && z.DecExt(yyv69) { - } else if !yym70 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv69) - } else { - z.DecFallback(yyv69, false) - } - } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l - } else { - yyb56 = r.CheckBreak() - } - if yyb56 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.NodeSyncPeriod = pkg1_unversioned.Duration{} - } else { - yyv71 := &x.NodeSyncPeriod - yym72 := z.DecBinary() - _ = yym72 - if false { - } else if z.HasExtensions() && z.DecExt(yyv71) { - } else if !yym72 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv71) - } else { - z.DecFallback(yyv71, false) - } - } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l - } else { - yyb56 = r.CheckBreak() - } - if yyb56 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.ResourceQuotaSyncPeriod = pkg1_unversioned.Duration{} - } else { - yyv73 := &x.ResourceQuotaSyncPeriod - yym74 := z.DecBinary() - _ = yym74 - if false { - } else if z.HasExtensions() && z.DecExt(yyv73) { - } else if !yym74 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv73) - } else { - z.DecFallback(yyv73, false) - } - } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l - } else { - yyb56 = r.CheckBreak() - } - if yyb56 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.NamespaceSyncPeriod = pkg1_unversioned.Duration{} - } else { - yyv75 := &x.NamespaceSyncPeriod + yyv75 := &x.ServiceSyncPeriod yym76 := z.DecBinary() _ = yym76 if false { @@ -7240,21 +7355,21 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * z.DecFallback(yyv75, false) } } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.PVClaimBinderSyncPeriod = pkg1_unversioned.Duration{} + x.NodeSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv77 := &x.PVClaimBinderSyncPeriod + yyv77 := &x.NodeSyncPeriod yym78 := z.DecBinary() _ = yym78 if false { @@ -7265,21 +7380,21 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * z.DecFallback(yyv77, false) } } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.MinResyncPeriod = pkg1_unversioned.Duration{} + x.ResourceQuotaSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv79 := &x.MinResyncPeriod + yyv79 := &x.ResourceQuotaSyncPeriod yym80 := z.DecBinary() _ = yym80 if false { @@ -7290,13 +7405,88 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * z.DecFallback(yyv79, false) } } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.NamespaceSyncPeriod = pkg1_unversioned.Duration{} + } else { + yyv81 := &x.NamespaceSyncPeriod + yym82 := z.DecBinary() + _ = yym82 + if false { + } else if z.HasExtensions() && z.DecExt(yyv81) { + } else if !yym82 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv81) + } else { + z.DecFallback(yyv81, false) + } + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.PVClaimBinderSyncPeriod = pkg1_unversioned.Duration{} + } else { + yyv83 := &x.PVClaimBinderSyncPeriod + yym84 := z.DecBinary() + _ = yym84 + if false { + } else if z.HasExtensions() && z.DecExt(yyv83) { + } else if !yym84 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv83) + } else { + z.DecFallback(yyv83, false) + } + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.MinResyncPeriod = pkg1_unversioned.Duration{} + } else { + yyv85 := &x.MinResyncPeriod + yym86 := z.DecBinary() + _ = yym86 + if false { + } else if z.HasExtensions() && z.DecExt(yyv85) { + } else if !yym86 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv85) + } else { + z.DecFallback(yyv85, false) + } + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7306,13 +7496,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.TerminatedPodGCThreshold = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7320,24 +7510,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.HorizontalPodAutoscalerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv82 := &x.HorizontalPodAutoscalerSyncPeriod - yym83 := z.DecBinary() - _ = yym83 + yyv88 := &x.HorizontalPodAutoscalerSyncPeriod + yym89 := z.DecBinary() + _ = yym89 if false { - } else if z.HasExtensions() && z.DecExt(yyv82) { - } else if !yym83 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv82) + } else if z.HasExtensions() && z.DecExt(yyv88) { + } else if !yym89 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv88) } else { - z.DecFallback(yyv82, false) + z.DecFallback(yyv88, false) } } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7345,89 +7535,7 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.DeploymentControllerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv84 := &x.DeploymentControllerSyncPeriod - yym85 := z.DecBinary() - _ = yym85 - if false { - } else if z.HasExtensions() && z.DecExt(yyv84) { - } else if !yym85 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv84) - } else { - z.DecFallback(yyv84, false) - } - } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l - } else { - yyb56 = r.CheckBreak() - } - if yyb56 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.PodEvictionTimeout = pkg1_unversioned.Duration{} - } else { - yyv86 := &x.PodEvictionTimeout - yym87 := z.DecBinary() - _ = yym87 - if false { - } else if z.HasExtensions() && z.DecExt(yyv86) { - } else if !yym87 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv86) - } else { - z.DecFallback(yyv86, false) - } - } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l - } else { - yyb56 = r.CheckBreak() - } - if yyb56 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.DeletingPodsQps = 0 - } else { - x.DeletingPodsQps = float32(r.DecodeFloat(true)) - } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l - } else { - yyb56 = r.CheckBreak() - } - if yyb56 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.DeletingPodsBurst = 0 - } else { - x.DeletingPodsBurst = int(r.DecodeInt(codecSelferBitsize1234)) - } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l - } else { - yyb56 = r.CheckBreak() - } - if yyb56 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.NodeMonitorGracePeriod = pkg1_unversioned.Duration{} - } else { - yyv90 := &x.NodeMonitorGracePeriod + yyv90 := &x.DeploymentControllerSyncPeriod yym91 := z.DecBinary() _ = yym91 if false { @@ -7438,13 +7546,95 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * z.DecFallback(yyv90, false) } } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.PodEvictionTimeout = pkg1_unversioned.Duration{} + } else { + yyv92 := &x.PodEvictionTimeout + yym93 := z.DecBinary() + _ = yym93 + if false { + } else if z.HasExtensions() && z.DecExt(yyv92) { + } else if !yym93 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv92) + } else { + z.DecFallback(yyv92, false) + } + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.DeletingPodsQps = 0 + } else { + x.DeletingPodsQps = float32(r.DecodeFloat(true)) + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.DeletingPodsBurst = 0 + } else { + x.DeletingPodsBurst = int(r.DecodeInt(codecSelferBitsize1234)) + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.NodeMonitorGracePeriod = pkg1_unversioned.Duration{} + } else { + yyv96 := &x.NodeMonitorGracePeriod + yym97 := z.DecBinary() + _ = yym97 + if false { + } else if z.HasExtensions() && z.DecExt(yyv96) { + } else if !yym97 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv96) + } else { + z.DecFallback(yyv96, false) + } + } + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l + } else { + yyb59 = r.CheckBreak() + } + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7454,13 +7644,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.RegisterRetryCount = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7468,24 +7658,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.NodeStartupGracePeriod = pkg1_unversioned.Duration{} } else { - yyv93 := &x.NodeStartupGracePeriod - yym94 := z.DecBinary() - _ = yym94 + yyv99 := &x.NodeStartupGracePeriod + yym100 := z.DecBinary() + _ = yym100 if false { - } else if z.HasExtensions() && z.DecExt(yyv93) { - } else if !yym94 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv93) + } else if z.HasExtensions() && z.DecExt(yyv99) { + } else if !yym100 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv99) } else { - z.DecFallback(yyv93, false) + z.DecFallback(yyv99, false) } } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7493,24 +7683,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.NodeMonitorPeriod = pkg1_unversioned.Duration{} } else { - yyv95 := &x.NodeMonitorPeriod - yym96 := z.DecBinary() - _ = yym96 + yyv101 := &x.NodeMonitorPeriod + yym102 := z.DecBinary() + _ = yym102 if false { - } else if z.HasExtensions() && z.DecExt(yyv95) { - } else if !yym96 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv95) + } else if z.HasExtensions() && z.DecExt(yyv101) { + } else if !yym102 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv101) } else { - z.DecFallback(yyv95, false) + z.DecFallback(yyv101, false) } } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7520,13 +7710,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ServiceAccountKeyFile = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7536,13 +7726,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.EnableProfiling = bool(r.DecodeBool()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7552,13 +7742,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ClusterName = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7568,13 +7758,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ClusterCIDR = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7584,13 +7774,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.AllocateNodeCIDRs = bool(r.DecodeBool()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7600,13 +7790,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.RootCAFile = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7616,13 +7806,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.KubeAPIQPS = float32(r.DecodeFloat(true)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7632,13 +7822,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.KubeAPIBurst = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7646,16 +7836,16 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.LeaderElection = LeaderElectionConfiguration{} } else { - yyv105 := &x.LeaderElection - yyv105.CodecDecodeSelf(d) + yyv111 := &x.LeaderElection + yyv111.CodecDecodeSelf(d) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7663,16 +7853,16 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.VolumeConfiguration = VolumeConfiguration{} } else { - yyv106 := &x.VolumeConfiguration - yyv106.CodecDecodeSelf(d) + yyv112 := &x.VolumeConfiguration + yyv112.CodecDecodeSelf(d) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7682,13 +7872,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.Kind = string(r.DecodeString()) } - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7699,17 +7889,17 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * x.APIVersion = string(r.DecodeString()) } for { - yyj56++ - if yyhl56 { - yyb56 = yyj56 > l + yyj59++ + if yyhl59 { + yyb59 = yyj59 > l } else { - yyb56 = r.CheckBreak() + yyb59 = r.CheckBreak() } - if yyb56 { + if yyb59 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj56-1, "") + z.DecStructFieldNotFound(yyj59-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.go index 5f15c7a40..fa52286da 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/componentconfig/types.go @@ -78,6 +78,24 @@ const ( ProxyModeIPTables ProxyMode = "iptables" ) +// 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" +) + // TODO: curate the ordering and structure of this config object type KubeletConfiguration struct { // config is the path to the config file or directory of files @@ -252,11 +270,18 @@ type KubeletConfiguration struct { // configureCBR0 enables the kublet to configure cbr0 based on // Node.Spec.PodCIDR. ConfigureCBR0 bool `json:"configureCbr0"` - // Should the kubelet set the hairpin flag on veth interfaces for containers - // it creates? Setting this flag allows endpoints in a Service to - // loadbalance back to themselves if they should try to access their own - // Service. - HairpinMode bool `json:"configureHairpinMode"` + // 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 int `json:"maxPods"` // dockerExecHandlerName is the handler to use when executing a command @@ -376,11 +401,11 @@ type KubeControllerManagerConfiguration struct { // but more CPU (and network) load. ConcurrentEndpointSyncs int `json:"concurrentEndpointSyncs"` // concurrentRSSyncs is the number of replica sets that are allowed to sync - // concurrently. Larger number = more reponsive replica management, but more + // concurrently. Larger number = more responsive replica management, but more // CPU (and network) load. ConcurrentRSSyncs int `json:"concurrentRSSyncs"` // concurrentRCSyncs is the number of replication controllers that are - // allowed to sync concurrently. Larger number = more reponsive replica + // allowed to sync concurrently. Larger number = more responsive replica // management, but more CPU (and network) load. ConcurrentRCSyncs int `json:"concurrentRCSyncs"` // concurrentResourceQuotaSyncs is the number of resource quotas that are @@ -388,20 +413,29 @@ type KubeControllerManagerConfiguration struct { // management, but more CPU (and network) load. ConcurrentResourceQuotaSyncs int `json:"concurrentResourceQuotaSyncs"` // concurrentDeploymentSyncs is the number of deployment objects that are - // allowed to sync concurrently. Larger number = more reponsive deployments, + // allowed to sync concurrently. Larger number = more responsive deployments, // but more CPU (and network) load. ConcurrentDeploymentSyncs int `json:"concurrentDeploymentSyncs"` // concurrentDaemonSetSyncs is the number of daemonset objects that are - // allowed to sync concurrently. Larger number = more reponsive DaemonSet, + // allowed to sync concurrently. Larger number = more responsive daemonset, // but more CPU (and network) load. ConcurrentDaemonSetSyncs int `json:"concurrentDaemonSetSyncs"` // concurrentJobSyncs is the number of job objects that are - // allowed to sync concurrently. Larger number = more reponsive jobs, + // allowed to sync concurrently. Larger number = more responsive jobs, // but more CPU (and network) load. ConcurrentJobSyncs int `json:"concurrentJobSyncs"` // concurrentNamespaceSyncs is the number of namespace objects that are // allowed to sync concurrently. ConcurrentNamespaceSyncs int `json:"concurrentNamespaceSyncs"` + // lookupCacheSizeForRC is the size of lookup cache for replication controllers. + // Larger number = more responsive replica management, but more MEM load. + LookupCacheSizeForRC int `json:"lookupCacheSizeForRC"` + // lookupCacheSizeForRS is the size of lookup cache for replicatsets. + // Larger number = more responsive replica management, but more MEM load. + LookupCacheSizeForRS int `json:"lookupCacheSizeForRS"` + // lookupCacheSizeForDaemonSet is the size of lookup cache for daemonsets. + // Larger number = more responsive daemonset, but more MEM load. + LookupCacheSizeForDaemonSet int `json:"lookupCacheSizeForDaemonSet"` // serviceSyncPeriod is the period for syncing services with their external // load balancers. ServiceSyncPeriod unversioned.Duration `json:"serviceSyncPeriod"` diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/helpers.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/helpers.go deleted file mode 100644 index c6d79d663..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/helpers.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package extensions - -// TODO(madhusudancs): Fix this when Scale group issues are resolved (see issue #18528). -// import ( -// "fmt" - -// "k8s.io/kubernetes/pkg/api" -// "k8s.io/kubernetes/pkg/api/unversioned" -// ) - -// // ScaleFromDeployment returns a scale subresource for a deployment. -// func ScaleFromDeployment(deployment *Deployment) (*Scale, error) { -// selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) -// if err != nil { -// return nil, fmt.Errorf("invalid label selector: %v", err) -// } -// return &Scale{ -// ObjectMeta: api.ObjectMeta{ -// Name: deployment.Name, -// Namespace: deployment.Namespace, -// CreationTimestamp: deployment.CreationTimestamp, -// }, -// Spec: ScaleSpec{ -// Replicas: deployment.Spec.Replicas, -// }, -// Status: ScaleStatus{ -// Replicas: deployment.Status.Replicas, -// Selector: selector.String(), -// }, -// }, nil -// } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/install/install_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/install/install_test.go deleted file mode 100644 index 311fad56d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/install/install_test.go +++ /dev/null @@ -1,119 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package install - -import ( - "encoding/json" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestResourceVersioner(t *testing.T) { - daemonSet := extensions.DaemonSet{ObjectMeta: api.ObjectMeta{ResourceVersion: "10"}} - version, err := accessor.ResourceVersion(&daemonSet) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if version != "10" { - t.Errorf("unexpected version %v", version) - } - - daemonSetList := extensions.DaemonSetList{ListMeta: unversioned.ListMeta{ResourceVersion: "10"}} - version, err = accessor.ResourceVersion(&daemonSetList) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if version != "10" { - t.Errorf("unexpected version %v", version) - } -} - -func TestCodec(t *testing.T) { - daemonSet := extensions.DaemonSet{} - // We do want to use package registered rather than testapi here, because we - // want to test if the package install and package registered work as expected. - data, err := runtime.Encode(api.Codecs.LegacyCodec(registered.GroupOrDie(extensions.GroupName).GroupVersion), &daemonSet) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - other := extensions.DaemonSet{} - if err := json.Unmarshal(data, &other); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if other.APIVersion != registered.GroupOrDie(extensions.GroupName).GroupVersion.String() || other.Kind != "DaemonSet" { - t.Errorf("unexpected unmarshalled object %#v", other) - } -} - -func TestInterfacesFor(t *testing.T) { - if _, err := registered.GroupOrDie(extensions.GroupName).InterfacesFor(extensions.SchemeGroupVersion); err == nil { - t.Fatalf("unexpected non-error: %v", err) - } - for i, version := range registered.GroupOrDie(extensions.GroupName).GroupVersions { - if vi, err := registered.GroupOrDie(extensions.GroupName).InterfacesFor(version); err != nil || vi == nil { - t.Fatalf("%d: unexpected result: %v", i, err) - } - } -} - -func TestRESTMapper(t *testing.T) { - gv := v1beta1.SchemeGroupVersion - hpaGVK := gv.WithKind("HorizontalPodAutoscaler") - daemonSetGVK := gv.WithKind("DaemonSet") - - if gvk, err := registered.GroupOrDie(extensions.GroupName).RESTMapper.KindFor(gv.WithResource("horizontalpodautoscalers")); err != nil || gvk != hpaGVK { - t.Errorf("unexpected version mapping: %v %v", gvk, err) - } - - if m, err := registered.GroupOrDie(extensions.GroupName).RESTMapper.RESTMapping(daemonSetGVK.GroupKind(), ""); err != nil || m.GroupVersionKind != daemonSetGVK || m.Resource != "daemonsets" { - t.Errorf("unexpected version mapping: %#v %v", m, err) - } - - for _, version := range registered.GroupOrDie(extensions.GroupName).GroupVersions { - mapping, err := registered.GroupOrDie(extensions.GroupName).RESTMapper.RESTMapping(hpaGVK.GroupKind(), version.Version) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if mapping.Resource != "horizontalpodautoscalers" { - t.Errorf("incorrect resource name: %#v", mapping) - } - if mapping.GroupVersionKind.GroupVersion() != version { - t.Errorf("incorrect groupVersion: %v", mapping) - } - - interfaces, _ := registered.GroupOrDie(extensions.GroupName).InterfacesFor(version) - if mapping.ObjectConvertor != interfaces.ObjectConvertor { - t.Errorf("unexpected: %#v, expected: %#v", mapping, interfaces) - } - - rc := &extensions.HorizontalPodAutoscaler{ObjectMeta: api.ObjectMeta{Name: "foo"}} - name, err := mapping.MetadataAccessor.Name(rc) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if name != "foo" { - t.Errorf("unable to retrieve object meta with: %v", mapping.MetadataAccessor) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/register.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/register.go index db7b93770..057940d16 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/register.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/register.go @@ -47,8 +47,6 @@ func AddToScheme(scheme *runtime.Scheme) { func addKnownTypes(scheme *runtime.Scheme) { // TODO this gets cleaned up when the types are fixed scheme.AddKnownTypes(SchemeGroupVersion, - &ClusterAutoscaler{}, - &ClusterAutoscalerList{}, &Deployment{}, &DeploymentList{}, &DeploymentRollback{}, @@ -75,8 +73,6 @@ func addKnownTypes(scheme *runtime.Scheme) { ) } -func (obj *ClusterAutoscaler) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ClusterAutoscalerList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *Deployment) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *DeploymentList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *DeploymentRollback) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go index fabe00c2f..2df949897 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go @@ -68,7 +68,7 @@ func init() { if false { // reference the types, but skip this branch at build/run time var v0 pkg2_api.ObjectMeta var v1 pkg4_resource.Quantity - var v2 pkg1_unversioned.TypeMeta + var v2 pkg1_unversioned.LabelSelector var v3 pkg3_types.UID var v4 pkg6_intstr.IntOrString var v5 pkg5_inf.Dec @@ -263,7 +263,7 @@ func (x *ScaleStatus) CodecEncodeSelf(e *codec1978.Encoder) { var yyq2 [2]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[1] = len(x.Selector) != 0 + yyq2[1] = x.Selector != nil var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(2) @@ -305,8 +305,9 @@ func (x *ScaleStatus) CodecEncodeSelf(e *codec1978.Encoder) { yym7 := z.EncBinary() _ = yym7 if false { + } else if z.HasExtensions() && z.EncExt(x.Selector) { } else { - z.F.EncMapStringStringV(x.Selector, false, e) + z.EncFallback(x.Selector) } } } else { @@ -323,8 +324,9 @@ func (x *ScaleStatus) CodecEncodeSelf(e *codec1978.Encoder) { yym8 := z.EncBinary() _ = yym8 if false { + } else if z.HasExtensions() && z.EncExt(x.Selector) { } else { - z.F.EncMapStringStringV(x.Selector, false, e) + z.EncFallback(x.Selector) } } } @@ -398,14 +400,19 @@ func (x *ScaleStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { } case "selector": if r.TryDecodeAsNil() { - x.Selector = nil + if x.Selector != nil { + x.Selector = nil + } } else { - yyv5 := &x.Selector + if x.Selector == nil { + x.Selector = new(pkg1_unversioned.LabelSelector) + } yym6 := z.DecBinary() _ = yym6 if false { + } else if z.HasExtensions() && z.DecExt(x.Selector) { } else { - z.F.DecMapStringStringX(yyv5, false, d) + z.DecFallback(x.Selector, false) } } default: @@ -450,14 +457,19 @@ func (x *ScaleStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.Selector = nil + if x.Selector != nil { + x.Selector = nil + } } else { - yyv9 := &x.Selector + if x.Selector == nil { + x.Selector = new(pkg1_unversioned.LabelSelector) + } yym10 := z.DecBinary() _ = yym10 if false { + } else if z.HasExtensions() && z.DecExt(x.Selector) { } else { - z.F.DecMapStringStringX(yyv9, false, d) + z.DecFallback(x.Selector, false) } } for { @@ -7022,16 +7034,17 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [4]bool + var yyq2 [5]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[0] = x.Replicas != 0 - yyq2[1] = x.UpdatedReplicas != 0 - yyq2[2] = x.AvailableReplicas != 0 - yyq2[3] = x.UnavailableReplicas != 0 + yyq2[0] = x.ObservedGeneration != 0 + yyq2[1] = x.Replicas != 0 + yyq2[2] = x.UpdatedReplicas != 0 + yyq2[3] = x.AvailableReplicas != 0 + yyq2[4] = x.UnavailableReplicas != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(4) + r.EncodeArrayStart(5) } else { yynn2 = 0 for _, b := range yyq2 { @@ -7049,7 +7062,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym4 if false { } else { - r.EncodeInt(int64(x.Replicas)) + r.EncodeInt(int64(x.ObservedGeneration)) } } else { r.EncodeInt(0) @@ -7057,13 +7070,13 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[0] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("replicas")) + r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym5 := z.EncBinary() _ = yym5 if false { } else { - r.EncodeInt(int64(x.Replicas)) + r.EncodeInt(int64(x.ObservedGeneration)) } } } @@ -7074,7 +7087,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym7 if false { } else { - r.EncodeInt(int64(x.UpdatedReplicas)) + r.EncodeInt(int64(x.Replicas)) } } else { r.EncodeInt(0) @@ -7082,13 +7095,13 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("updatedReplicas")) + r.EncodeString(codecSelferC_UTF81234, string("replicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { } else { - r.EncodeInt(int64(x.UpdatedReplicas)) + r.EncodeInt(int64(x.Replicas)) } } } @@ -7099,7 +7112,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym10 if false { } else { - r.EncodeInt(int64(x.AvailableReplicas)) + r.EncodeInt(int64(x.UpdatedReplicas)) } } else { r.EncodeInt(0) @@ -7107,13 +7120,13 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("availableReplicas")) + r.EncodeString(codecSelferC_UTF81234, string("updatedReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym11 := z.EncBinary() _ = yym11 if false { } else { - r.EncodeInt(int64(x.AvailableReplicas)) + r.EncodeInt(int64(x.UpdatedReplicas)) } } } @@ -7124,7 +7137,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym13 if false { } else { - r.EncodeInt(int64(x.UnavailableReplicas)) + r.EncodeInt(int64(x.AvailableReplicas)) } } else { r.EncodeInt(0) @@ -7132,11 +7145,36 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[3] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("unavailableReplicas")) + r.EncodeString(codecSelferC_UTF81234, string("availableReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym14 := z.EncBinary() _ = yym14 if false { + } else { + r.EncodeInt(int64(x.AvailableReplicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeInt(int64(x.UnavailableReplicas)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("unavailableReplicas")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym17 := z.EncBinary() + _ = yym17 + if false { } else { r.EncodeInt(int64(x.UnavailableReplicas)) } @@ -7203,6 +7241,12 @@ func (x *DeploymentStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { + case "observedGeneration": + if r.TryDecodeAsNil() { + x.ObservedGeneration = 0 + } else { + x.ObservedGeneration = int64(r.DecodeInt(64)) + } case "replicas": if r.TryDecodeAsNil() { x.Replicas = 0 @@ -7238,16 +7282,32 @@ func (x *DeploymentStatus) 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 + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ObservedGeneration = 0 + } else { + x.ObservedGeneration = int64(r.DecodeInt(64)) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7257,13 +7317,13 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7273,13 +7333,13 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.UpdatedReplicas = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7289,13 +7349,13 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.AvailableReplicas = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7306,17 +7366,17 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) x.UnavailableReplicas = int(r.DecodeInt(codecSelferBitsize1234)) } for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj8-1, "") + z.DecStructFieldNotFound(yyj9-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -9877,16 +9937,17 @@ func (x *JobSpec) 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] = x.Parallelism != nil yyq2[1] = x.Completions != nil yyq2[2] = x.ActiveDeadlineSeconds != nil yyq2[3] = x.Selector != nil + yyq2[4] = x.ManualSelector != nil var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(5) + r.EncodeArrayStart(6) } else { yynn2 = 1 for _, b := range yyq2 { @@ -10039,14 +10100,49 @@ func (x *JobSpec) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy22 := &x.Template - yy22.CodecEncodeSelf(e) + if yyq2[4] { + if x.ManualSelector == nil { + r.EncodeNil() + } else { + yy22 := *x.ManualSelector + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeBool(bool(yy22)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("manualSelector")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.ManualSelector == nil { + r.EncodeNil() + } else { + yy24 := *x.ManualSelector + yym25 := z.EncBinary() + _ = yym25 + if false { + } else { + r.EncodeBool(bool(yy24)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy27 := &x.Template + yy27.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("template")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy24 := &x.Template - yy24.CodecEncodeSelf(e) + yy29 := &x.Template + yy29.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) @@ -10174,12 +10270,28 @@ func (x *JobSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { z.DecFallback(x.Selector, false) } } + case "manualSelector": + if r.TryDecodeAsNil() { + if x.ManualSelector != nil { + x.ManualSelector = nil + } + } else { + if x.ManualSelector == nil { + x.ManualSelector = new(bool) + } + yym13 := z.DecBinary() + _ = yym13 + if false { + } else { + *((*bool)(x.ManualSelector)) = r.DecodeBool() + } + } case "template": if r.TryDecodeAsNil() { x.Template = pkg2_api.PodTemplateSpec{} } else { - yyv12 := &x.Template - yyv12.CodecDecodeSelf(d) + yyv14 := &x.Template + yyv14.CodecDecodeSelf(d) } default: z.DecStructFieldNotFound(-1, yys3) @@ -10192,16 +10304,16 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj13 int - var yyb13 bool - var yyhl13 bool = l >= 0 - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l + var yyj15 int + var yyb15 bool + var yyhl15 bool = l >= 0 + yyj15++ + if yyhl15 { + yyb15 = yyj15 > l } else { - yyb13 = r.CheckBreak() + yyb15 = r.CheckBreak() } - if yyb13 { + if yyb15 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10214,20 +10326,20 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.Parallelism == nil { x.Parallelism = new(int) } - yym15 := z.DecBinary() - _ = yym15 + yym17 := z.DecBinary() + _ = yym17 if false { } else { *((*int)(x.Parallelism)) = int(r.DecodeInt(codecSelferBitsize1234)) } } - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l + yyj15++ + if yyhl15 { + yyb15 = yyj15 > l } else { - yyb13 = r.CheckBreak() + yyb15 = r.CheckBreak() } - if yyb13 { + if yyb15 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10240,20 +10352,20 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.Completions == nil { x.Completions = new(int) } - yym17 := z.DecBinary() - _ = yym17 + yym19 := z.DecBinary() + _ = yym19 if false { } else { *((*int)(x.Completions)) = int(r.DecodeInt(codecSelferBitsize1234)) } } - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l + yyj15++ + if yyhl15 { + yyb15 = yyj15 > l } else { - yyb13 = r.CheckBreak() + yyb15 = r.CheckBreak() } - if yyb13 { + if yyb15 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10266,20 +10378,20 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.ActiveDeadlineSeconds == nil { x.ActiveDeadlineSeconds = new(int64) } - yym19 := z.DecBinary() - _ = yym19 + yym21 := z.DecBinary() + _ = yym21 if false { } else { *((*int64)(x.ActiveDeadlineSeconds)) = int64(r.DecodeInt(64)) } } - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l + yyj15++ + if yyhl15 { + yyb15 = yyj15 > l } else { - yyb13 = r.CheckBreak() + yyb15 = r.CheckBreak() } - if yyb13 { + if yyb15 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10292,21 +10404,47 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.Selector == nil { x.Selector = new(pkg1_unversioned.LabelSelector) } - yym21 := z.DecBinary() - _ = yym21 + yym23 := z.DecBinary() + _ = yym23 if false { } else if z.HasExtensions() && z.DecExt(x.Selector) { } else { z.DecFallback(x.Selector, false) } } - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l + yyj15++ + if yyhl15 { + yyb15 = yyj15 > l } else { - yyb13 = r.CheckBreak() + yyb15 = r.CheckBreak() } - if yyb13 { + if yyb15 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.ManualSelector != nil { + x.ManualSelector = nil + } + } else { + if x.ManualSelector == nil { + x.ManualSelector = new(bool) + } + yym25 := z.DecBinary() + _ = yym25 + if false { + } else { + *((*bool)(x.ManualSelector)) = r.DecodeBool() + } + } + yyj15++ + if yyhl15 { + yyb15 = yyj15 > l + } else { + yyb15 = r.CheckBreak() + } + if yyb15 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10314,21 +10452,21 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if r.TryDecodeAsNil() { x.Template = pkg2_api.PodTemplateSpec{} } else { - yyv22 := &x.Template - yyv22.CodecDecodeSelf(d) + yyv26 := &x.Template + yyv26.CodecDecodeSelf(d) } for { - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l + yyj15++ + if yyhl15 { + yyb15 = yyj15 > l } else { - yyb13 = r.CheckBreak() + yyb15 = r.CheckBreak() } - if yyb13 { + if yyb15 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj13-1, "") + z.DecStructFieldNotFound(yyj15-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -13766,1134 +13904,6 @@ func (x *IngressBackend) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } -func (x NodeResource) 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 *NodeResource) 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 *NodeUtilization) 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 - var yynn2 int - if yyr2 || yy2arr2 { - r.EncodeArrayStart(2) - } else { - yynn2 = 2 - for _, b := range yyq2 { - if b { - yynn2++ - } - } - r.EncodeMapStart(yynn2) - yynn2 = 0 - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - x.Resource.CodecEncodeSelf(e) - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("resource")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - x.Resource.CodecEncodeSelf(e) - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym7 := z.EncBinary() - _ = yym7 - if false { - } else { - r.EncodeFloat64(float64(x.Value)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("value")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym8 := z.EncBinary() - _ = yym8 - if false { - } else { - r.EncodeFloat64(float64(x.Value)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayEnd1234) - } else { - z.EncSendContainerState(codecSelfer_containerMapEnd1234) - } - } - } -} - -func (x *NodeUtilization) 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 *NodeUtilization) 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 "resource": - if r.TryDecodeAsNil() { - x.Resource = "" - } else { - x.Resource = NodeResource(r.DecodeString()) - } - case "value": - if r.TryDecodeAsNil() { - x.Value = 0 - } else { - x.Value = float64(r.DecodeFloat(false)) - } - default: - z.DecStructFieldNotFound(-1, yys3) - } // end switch yys3 - } // end for yyj3 - z.DecSendContainerState(codecSelfer_containerMapEnd1234) -} - -func (x *NodeUtilization) 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.Resource = "" - } else { - x.Resource = NodeResource(r.DecodeString()) - } - 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.Value = 0 - } else { - x.Value = float64(r.DecodeFloat(false)) - } - 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 *ClusterAutoscalerSpec) 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 [3]bool - _, _, _ = yysep2, yyq2, yy2arr2 - const yyr2 bool = false - var yynn2 int - if yyr2 || yy2arr2 { - r.EncodeArrayStart(3) - } else { - yynn2 = 3 - for _, b := range yyq2 { - if b { - yynn2++ - } - } - r.EncodeMapStart(yynn2) - yynn2 = 0 - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym4 := z.EncBinary() - _ = yym4 - if false { - } else { - r.EncodeInt(int64(x.MinNodes)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("minNodes")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym5 := z.EncBinary() - _ = yym5 - if false { - } else { - r.EncodeInt(int64(x.MinNodes)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym7 := z.EncBinary() - _ = yym7 - if false { - } else { - r.EncodeInt(int64(x.MaxNodes)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("maxNodes")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym8 := z.EncBinary() - _ = yym8 - if false { - } else { - r.EncodeInt(int64(x.MaxNodes)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if x.TargetUtilization == nil { - r.EncodeNil() - } else { - yym10 := z.EncBinary() - _ = yym10 - if false { - } else { - h.encSliceNodeUtilization(([]NodeUtilization)(x.TargetUtilization), e) - } - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("target")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - if x.TargetUtilization == nil { - r.EncodeNil() - } else { - yym11 := z.EncBinary() - _ = yym11 - if false { - } else { - h.encSliceNodeUtilization(([]NodeUtilization)(x.TargetUtilization), e) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayEnd1234) - } else { - z.EncSendContainerState(codecSelfer_containerMapEnd1234) - } - } - } -} - -func (x *ClusterAutoscalerSpec) 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 *ClusterAutoscalerSpec) 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 "minNodes": - if r.TryDecodeAsNil() { - x.MinNodes = 0 - } else { - x.MinNodes = int(r.DecodeInt(codecSelferBitsize1234)) - } - case "maxNodes": - if r.TryDecodeAsNil() { - x.MaxNodes = 0 - } else { - x.MaxNodes = int(r.DecodeInt(codecSelferBitsize1234)) - } - case "target": - if r.TryDecodeAsNil() { - x.TargetUtilization = nil - } else { - yyv6 := &x.TargetUtilization - yym7 := z.DecBinary() - _ = yym7 - if false { - } else { - h.decSliceNodeUtilization((*[]NodeUtilization)(yyv6), d) - } - } - default: - z.DecStructFieldNotFound(-1, yys3) - } // end switch yys3 - } // end for yyj3 - z.DecSendContainerState(codecSelfer_containerMapEnd1234) -} - -func (x *ClusterAutoscalerSpec) 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.MinNodes = 0 - } else { - x.MinNodes = int(r.DecodeInt(codecSelferBitsize1234)) - } - 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.MaxNodes = 0 - } else { - x.MaxNodes = int(r.DecodeInt(codecSelferBitsize1234)) - } - 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.TargetUtilization = nil - } else { - yyv11 := &x.TargetUtilization - yym12 := z.DecBinary() - _ = yym12 - if false { - } else { - h.decSliceNodeUtilization((*[]NodeUtilization)(yyv11), d) - } - } - 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 *ClusterAutoscaler) 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] = true - 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.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] { - yym14 := z.EncBinary() - _ = yym14 - 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) - yym15 := z.EncBinary() - _ = yym15 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[3] { - yym17 := z.EncBinary() - _ = yym17 - 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) - yym18 := z.EncBinary() - _ = yym18 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayEnd1234) - } else { - z.EncSendContainerState(codecSelfer_containerMapEnd1234) - } - } - } -} - -func (x *ClusterAutoscaler) 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 *ClusterAutoscaler) 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 = ClusterAutoscalerSpec{} - } else { - yyv5 := &x.Spec - yyv5.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 *ClusterAutoscaler) 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.ObjectMeta = pkg2_api.ObjectMeta{} - } else { - yyv9 := &x.ObjectMeta - yyv9.CodecDecodeSelf(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.Spec = ClusterAutoscalerSpec{} - } else { - yyv10 := &x.Spec - yyv10.CodecDecodeSelf(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.Kind = "" - } else { - x.Kind = string(r.DecodeString()) - } - 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.APIVersion = "" - } else { - x.APIVersion = string(r.DecodeString()) - } - 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 *ClusterAutoscalerList) 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.encSliceClusterAutoscaler(([]ClusterAutoscaler)(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.encSliceClusterAutoscaler(([]ClusterAutoscaler)(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 *ClusterAutoscalerList) 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 *ClusterAutoscalerList) 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.decSliceClusterAutoscaler((*[]ClusterAutoscaler)(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 *ClusterAutoscalerList) 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.decSliceClusterAutoscaler((*[]ClusterAutoscaler)(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 *ReplicaSet) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -15599,7 +14609,7 @@ func (x *ReplicaSetSpec) CodecEncodeSelf(e *codec1978.Encoder) { _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[1] = x.Selector != nil - yyq2[2] = x.Template != nil + yyq2[2] = true var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(3) @@ -15670,11 +14680,8 @@ func (x *ReplicaSetSpec) CodecEncodeSelf(e *codec1978.Encoder) { if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { - if x.Template == nil { - r.EncodeNil() - } else { - x.Template.CodecEncodeSelf(e) - } + yy10 := &x.Template + yy10.CodecEncodeSelf(e) } else { r.EncodeNil() } @@ -15683,11 +14690,8 @@ func (x *ReplicaSetSpec) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("template")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - if x.Template == nil { - r.EncodeNil() - } else { - x.Template.CodecEncodeSelf(e) - } + yy12 := &x.Template + yy12.CodecEncodeSelf(e) } } if yyr2 || yy2arr2 { @@ -15776,14 +14780,10 @@ func (x *ReplicaSetSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { } case "template": if r.TryDecodeAsNil() { - if x.Template != nil { - x.Template = nil - } + x.Template = pkg2_api.PodTemplateSpec{} } else { - if x.Template == nil { - x.Template = new(pkg2_api.PodTemplateSpec) - } - x.Template.CodecDecodeSelf(d) + yyv7 := &x.Template + yyv7.CodecDecodeSelf(d) } default: z.DecStructFieldNotFound(-1, yys3) @@ -15854,14 +14854,10 @@ func (x *ReplicaSetSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - if x.Template != nil { - x.Template = nil - } + x.Template = pkg2_api.PodTemplateSpec{} } else { - if x.Template == nil { - x.Template = new(pkg2_api.PodTemplateSpec) - } - x.Template.CodecDecodeSelf(d) + yyv12 := &x.Template + yyv12.CodecDecodeSelf(d) } for { yyj8++ @@ -15893,13 +14889,14 @@ func (x *ReplicaSetStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [2]bool + var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[1] = x.ObservedGeneration != 0 + yyq2[1] = x.FullyLabeledReplicas != 0 + yyq2[2] = x.ObservedGeneration != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(2) + r.EncodeArrayStart(3) } else { yynn2 = 1 for _, b := range yyq2 { @@ -15936,7 +14933,7 @@ func (x *ReplicaSetStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym7 if false { } else { - r.EncodeInt(int64(x.ObservedGeneration)) + r.EncodeInt(int64(x.FullyLabeledReplicas)) } } else { r.EncodeInt(0) @@ -15944,11 +14941,36 @@ func (x *ReplicaSetStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + r.EncodeString(codecSelferC_UTF81234, string("fullyLabeledReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { + } else { + r.EncodeInt(int64(x.FullyLabeledReplicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeInt(int64(x.ObservedGeneration)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { } else { r.EncodeInt(int64(x.ObservedGeneration)) } @@ -16021,6 +15043,12 @@ func (x *ReplicaSetStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { } else { x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) } + case "fullyLabeledReplicas": + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int(r.DecodeInt(codecSelferBitsize1234)) + } case "observedGeneration": if r.TryDecodeAsNil() { x.ObservedGeneration = 0 @@ -16038,16 +15066,16 @@ func (x *ReplicaSetStatus) 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 + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -16057,13 +15085,29 @@ func (x *ReplicaSetStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.Replicas = int(r.DecodeInt(codecSelferBitsize1234)) } - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int(r.DecodeInt(codecSelferBitsize1234)) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -16074,17 +15118,17 @@ func (x *ReplicaSetStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) x.ObservedGeneration = int64(r.DecodeInt(64)) } for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj6-1, "") + z.DecStructFieldNotFound(yyj7-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -16631,7 +15675,7 @@ func (x *PodSecurityPolicySpec) CodecEncodeSelf(e *codec1978.Encoder) { if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[7] { - yy25 := &x.SELinuxContext + yy25 := &x.SELinux yy25.CodecEncodeSelf(e) } else { r.EncodeNil() @@ -16639,9 +15683,9 @@ func (x *PodSecurityPolicySpec) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[7] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("seLinuxContext")) + r.EncodeString(codecSelferC_UTF81234, string("seLinux")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy27 := &x.SELinuxContext + yy27 := &x.SELinux yy27.CodecEncodeSelf(e) } } @@ -16783,11 +15827,11 @@ func (x *PodSecurityPolicySpec) codecDecodeSelfFromMap(l int, d *codec1978.Decod } else { x.HostIPC = bool(r.DecodeBool()) } - case "seLinuxContext": + case "seLinux": if r.TryDecodeAsNil() { - x.SELinuxContext = SELinuxContextStrategyOptions{} + x.SELinux = SELinuxStrategyOptions{} } else { - yyv14 := &x.SELinuxContext + yyv14 := &x.SELinux yyv14.CodecDecodeSelf(d) } case "runAsUser": @@ -16953,9 +15997,9 @@ func (x *PodSecurityPolicySpec) codecDecodeSelfFromArray(l int, d *codec1978.Dec } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.SELinuxContext = SELinuxContextStrategyOptions{} + x.SELinux = SELinuxStrategyOptions{} } else { - yyv27 := &x.SELinuxContext + yyv27 := &x.SELinux yyv27.CodecDecodeSelf(d) } yyj16++ @@ -17220,7 +16264,7 @@ func (x *FSType) CodecDecodeSelf(d *codec1978.Decoder) { } } -func (x *SELinuxContextStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { +func (x *SELinuxStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r @@ -17253,12 +16297,12 @@ func (x *SELinuxContextStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("type")) + r.EncodeString(codecSelferC_UTF81234, string("rule")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) @@ -17292,7 +16336,7 @@ func (x *SELinuxContextStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { } } -func (x *SELinuxContextStrategyOptions) CodecDecodeSelf(d *codec1978.Decoder) { +func (x *SELinuxStrategyOptions) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -17322,7 +16366,7 @@ func (x *SELinuxContextStrategyOptions) CodecDecodeSelf(d *codec1978.Decoder) { } } -func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { +func (x *SELinuxStrategyOptions) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -17344,11 +16388,11 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromMap(l int, d *codec19 yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { - case "type": + case "rule": if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = SELinuxContextStrategy(r.DecodeString()) + x.Rule = SELinuxStrategy(r.DecodeString()) } case "seLinuxOptions": if r.TryDecodeAsNil() { @@ -17368,7 +16412,7 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromMap(l int, d *codec19 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } -func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { +func (x *SELinuxStrategyOptions) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -17387,9 +16431,9 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromArray(l int, d *codec } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = SELinuxContextStrategy(r.DecodeString()) + x.Rule = SELinuxStrategy(r.DecodeString()) } yyj6++ if yyhl6 { @@ -17428,7 +16472,7 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromArray(l int, d *codec z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } -func (x SELinuxContextStrategy) CodecEncodeSelf(e *codec1978.Encoder) { +func (x SELinuxStrategy) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r @@ -17441,7 +16485,7 @@ func (x SELinuxContextStrategy) CodecEncodeSelf(e *codec1978.Encoder) { } } -func (x *SELinuxContextStrategy) CodecDecodeSelf(d *codec1978.Decoder) { +func (x *SELinuxStrategy) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -17487,12 +16531,12 @@ func (x *RunAsUserStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("type")) + r.EncodeString(codecSelferC_UTF81234, string("rule")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) @@ -17588,11 +16632,11 @@ func (x *RunAsUserStrategyOptions) codecDecodeSelfFromMap(l int, d *codec1978.De yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { - case "type": + case "rule": if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = RunAsUserStrategy(r.DecodeString()) + x.Rule = RunAsUserStrategy(r.DecodeString()) } case "ranges": if r.TryDecodeAsNil() { @@ -17632,9 +16676,9 @@ func (x *RunAsUserStrategyOptions) codecDecodeSelfFromArray(l int, d *codec1978. } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = RunAsUserStrategy(r.DecodeString()) + x.Rule = RunAsUserStrategy(r.DecodeString()) } yyj7++ if yyhl7 { @@ -18881,7 +17925,7 @@ func (x codecSelfer1234) decSliceDeployment(v *[]Deployment, d *codec1978.Decode yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 624) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 632) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] @@ -19238,7 +18282,7 @@ func (x codecSelfer1234) decSliceJob(v *[]Job, d *codec1978.Decoder) { yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 616) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 624) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] @@ -19913,244 +18957,6 @@ func (x codecSelfer1234) decSliceHTTPIngressPath(v *[]HTTPIngressPath, d *codec1 } } -func (x codecSelfer1234) encSliceNodeUtilization(v []NodeUtilization, 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) decSliceNodeUtilization(v *[]NodeUtilization, 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 = []NodeUtilization{} - 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, 24) - if yyrt1 { - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]NodeUtilization, yyrl1) - } - } else { - yyv1 = make([]NodeUtilization, 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] = NodeUtilization{} - } else { - yyv2 := &yyv1[yyj1] - yyv2.CodecDecodeSelf(d) - } - - } - if yyrt1 { - for ; yyj1 < yyl1; yyj1++ { - yyv1 = append(yyv1, NodeUtilization{}) - yyh1.ElemContainerState(yyj1) - if r.TryDecodeAsNil() { - yyv1[yyj1] = NodeUtilization{} - } else { - yyv3 := &yyv1[yyj1] - yyv3.CodecDecodeSelf(d) - } - - } - } - - } else { - yyj1 := 0 - for ; !r.CheckBreak(); yyj1++ { - - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, NodeUtilization{}) // var yyz1 NodeUtilization - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - if yyj1 < len(yyv1) { - if r.TryDecodeAsNil() { - yyv1[yyj1] = NodeUtilization{} - } 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 = []NodeUtilization{} - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer1234) encSliceClusterAutoscaler(v []ClusterAutoscaler, 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) decSliceClusterAutoscaler(v *[]ClusterAutoscaler, 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 = []ClusterAutoscaler{} - 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, 232) - if yyrt1 { - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]ClusterAutoscaler, yyrl1) - } - } else { - yyv1 = make([]ClusterAutoscaler, 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] = ClusterAutoscaler{} - } else { - yyv2 := &yyv1[yyj1] - yyv2.CodecDecodeSelf(d) - } - - } - if yyrt1 { - for ; yyj1 < yyl1; yyj1++ { - yyv1 = append(yyv1, ClusterAutoscaler{}) - yyh1.ElemContainerState(yyj1) - if r.TryDecodeAsNil() { - yyv1[yyj1] = ClusterAutoscaler{} - } else { - yyv3 := &yyv1[yyj1] - yyv3.CodecDecodeSelf(d) - } - - } - } - - } else { - yyj1 := 0 - for ; !r.CheckBreak(); yyj1++ { - - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, ClusterAutoscaler{}) // var yyz1 ClusterAutoscaler - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - if yyj1 < len(yyv1) { - if r.TryDecodeAsNil() { - yyv1[yyj1] = ClusterAutoscaler{} - } 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 = []ClusterAutoscaler{} - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - func (x codecSelfer1234) encSliceReplicaSet(v []ReplicaSet, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -20190,7 +18996,7 @@ func (x codecSelfer1234) decSliceReplicaSet(v *[]ReplicaSet, d *codec1978.Decode yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 232) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 560) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.go index 4bfbef8d0..f8a736bdf 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/types.go @@ -46,8 +46,9 @@ type ScaleStatus struct { // actual number of observed instances of the scaled object. Replicas int `json:"replicas"` - // 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"` + // label query over pods that should match the replicas count. + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors + Selector *unversioned.LabelSelector `json:"selector,omitempty"` } // +genclient=true,noMethods=true @@ -55,13 +56,13 @@ type ScaleStatus struct { // represents a scaling request for a resource. type Scale struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata. api.ObjectMeta `json:"metadata,omitempty"` - // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Spec ScaleSpec `json:"spec,omitempty"` - // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Read-only. Status ScaleStatus `json:"status,omitempty"` } @@ -72,9 +73,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/HEAD/docs/devel/api-conventions.md#types-kinds" + // Kind of the referent; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds" Kind string `json:"kind,omitempty"` - // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names Name string `json:"name,omitempty"` // API version of the referent APIVersion string `json:"apiVersion,omitempty"` @@ -152,7 +153,7 @@ type HorizontalPodAutoscaler struct { unversioned.TypeMeta `json:",inline"` api.ObjectMeta `json:"metadata,omitempty"` - // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Spec HorizontalPodAutoscalerSpec `json:"spec,omitempty"` // current information about the autoscaler. @@ -332,6 +333,9 @@ type RollingUpdateDeployment struct { } type DeploymentStatus struct { + // The generation observed by the deployment controller. + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + // Total number of non-terminated pods targeted by this deployment (their labels match the selector). Replicas int `json:"replicas,omitempty"` @@ -404,14 +408,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/HEAD/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#pod-template Template api.PodTemplateSpec `json:"template"` // TODO(madhusudancs): Uncomment while implementing DaemonSet updates. @@ -458,18 +462,18 @@ type DaemonSetStatus struct { type DaemonSet struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status DaemonSetStatus `json:"status,omitempty"` } @@ -477,7 +481,7 @@ type DaemonSet struct { type DaemonSetList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of daemon sets. @@ -487,7 +491,7 @@ type DaemonSetList struct { type ThirdPartyResourceDataList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of third party objects Items []ThirdPartyResourceData `json:"items"` @@ -499,15 +503,15 @@ type ThirdPartyResourceDataList struct { type Job struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status JobStatus `json:"status,omitempty"` } @@ -515,7 +519,7 @@ type Job struct { type JobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of Job. @@ -532,7 +536,10 @@ type JobSpec struct { Parallelism *int `json:"parallelism,omitempty"` // Completions specifies the desired number of successfully finished pods the - // job should be run with. When unset, any pod exiting signals the job to complete. + // 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. Completions *int `json:"completions,omitempty"` // Optional duration in seconds relative to the startTime that the job may be active @@ -540,8 +547,20 @@ type JobSpec struct { ActiveDeadlineSeconds *int64 `json:"activeDeadlineSeconds,omitempty"` // Selector is a label query over pods that should match the pod count. + // Normally, the system sets this field for you. Selector *unversioned.LabelSelector `json:"selector,omitempty"` + // 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. + ManualSelector *bool `json:"manualSelector,omitempty"` + // Template is the object that describes the pod that will be created when // executing a job. Template api.PodTemplateSpec `json:"template"` @@ -608,15 +627,15 @@ type JobCondition struct { type Ingress struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status IngressStatus `json:"status,omitempty"` } @@ -624,7 +643,7 @@ type Ingress struct { type IngressList struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of Ingress. @@ -750,67 +769,6 @@ type IngressBackend struct { ServicePort intstr.IntOrString `json:"servicePort"` } -type NodeResource string - -const ( - // Percentage of node's CPUs that is currently used. - CpuConsumption NodeResource = "CpuConsumption" - - // Percentage of node's CPUs that is currently requested for pods. - CpuRequest NodeResource = "CpuRequest" - - // Percentage od node's memory that is currently used. - MemConsumption NodeResource = "MemConsumption" - - // Percentage of node's CPUs that is currently requested for pods. - MemRequest NodeResource = "MemRequest" -) - -// NodeUtilization describes what percentage of a particular resource is used on a node. -type NodeUtilization struct { - Resource NodeResource `json:"resource"` - - // The accepted values are from 0 to 1. - Value float64 `json:"value"` -} - -// Configuration of the Cluster Autoscaler -type ClusterAutoscalerSpec struct { - // Minimum number of nodes that the cluster should have. - MinNodes int `json:"minNodes"` - - // Maximum number of nodes that the cluster should have. - MaxNodes int `json:"maxNodes"` - - // Target average utilization of the cluster nodes. New nodes will be added if one of the - // targets is exceeded. Cluster size will be decreased if the current utilization is too low - // for all targets. - TargetUtilization []NodeUtilization `json:"target"` -} - -type ClusterAutoscaler struct { - unversioned.TypeMeta `json:",inline"` - - // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata - // For now (experimental api) it is required that the name is set to "ClusterAutoscaler" and namespace is "default". - api.ObjectMeta `json:"metadata,omitempty"` - - // Spec defines the desired behavior of this daemon set. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status - Spec ClusterAutoscalerSpec `json:"spec,omitempty"` -} - -// There will be just one (or none) ClusterAutoscaler. -type ClusterAutoscalerList struct { - unversioned.TypeMeta `json:",inline"` - // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata - unversioned.ListMeta `json:"metadata,omitempty"` - - Items []ClusterAutoscaler `json:"items"` -} - // +genclient=true // ReplicaSet represents the configuration of a replica set. @@ -844,12 +802,12 @@ 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/HEAD/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/release-1.2/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 // insufficient replicas are detected. - Template *api.PodTemplateSpec `json:"template,omitempty"` + Template api.PodTemplateSpec `json:"template,omitempty"` } // ReplicaSetStatus represents the current status of a ReplicaSet. @@ -857,6 +815,9 @@ type ReplicaSetStatus struct { // Replicas is the number of actual replicas. Replicas int `json:"replicas"` + // The number of pods that have labels matching the labels of the pod template of the replicaset. + FullyLabeledReplicas int `json:"fullyLabeledReplicas,omitempty"` + // ObservedGeneration is the most recent generation observed by the controller. ObservedGeneration int64 `json:"observedGeneration,omitempty"` } @@ -888,8 +849,8 @@ type PodSecurityPolicySpec struct { HostPID bool `json:"hostPID,omitempty"` // HostIPC determines if the policy allows the use of HostIPC in the pod spec. HostIPC bool `json:"hostIPC,omitempty"` - // SELinuxContext is the strategy that will dictate the allowable labels that may be set. - SELinuxContext SELinuxContextStrategyOptions `json:"seLinuxContext,omitempty"` + // SELinux is the strategy that will dictate the allowable labels that may be set. + SELinux SELinuxStrategyOptions `json:"seLinux,omitempty"` // RunAsUser is the strategy that will dictate the allowable RunAsUser values that may be set. RunAsUser RunAsUserStrategyOptions `json:"runAsUser,omitempty"` } @@ -924,30 +885,30 @@ var ( FC FSType = "fc" ) -// SELinuxContextStrategyOptions defines the strategy type and any options used to create the strategy. -type SELinuxContextStrategyOptions struct { - // Type is the strategy that will dictate the allowable labels that may be set. - Type SELinuxContextStrategy `json:"type"` +// SELinuxStrategyOptions defines the strategy type and any options used to create the strategy. +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/HEAD/docs/design/security_context.md#security-context + // More info: http://releases.k8s.io/release-1.2/docs/design/security_context.md#security-context SELinuxOptions *api.SELinuxOptions `json:"seLinuxOptions,omitempty"` } -// SELinuxContextStrategyType denotes strategy types for generating SELinux options for a -// SecurityContext. -type SELinuxContextStrategy string +// SELinuxStrategy denotes strategy types for generating SELinux options for a +// Security. +type SELinuxStrategy string const ( // container must have SELinux labels of X applied. - SELinuxStrategyMustRunAs SELinuxContextStrategy = "MustRunAs" + SELinuxStrategyMustRunAs SELinuxStrategy = "MustRunAs" // container may make requests for any SELinux context labels. - SELinuxStrategyRunAsAny SELinuxContextStrategy = "RunAsAny" + SELinuxStrategyRunAsAny SELinuxStrategy = "RunAsAny" ) // RunAsUserStrategyOptions defines the strategy type and any options used to create the strategy. type RunAsUserStrategyOptions struct { - // Type is the strategy that will dictate the allowable RunAsUser values that may be set. - Type RunAsUserStrategy `json:"type"` + // Rule is the strategy that will dictate the allowable RunAsUser values that may be set. + Rule RunAsUserStrategy `json:"rule"` // Ranges are the allowed ranges of uids that may be used. Ranges []IDRange `json:"ranges,omitempty"` } @@ -960,7 +921,7 @@ type IDRange struct { Max int64 `json:"max"` } -// RunAsUserStrategyType denotes strategy types for generating RunAsUser values for a +// RunAsUserStrategy denotes strategy types for generating RunAsUser values for a // SecurityContext. type RunAsUserStrategy string diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go index 595091e02..5f4841cb4 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go @@ -34,6 +34,8 @@ func addConversionFuncs(scheme *runtime.Scheme) { err := scheme.AddConversionFuncs( Convert_api_PodSpec_To_v1_PodSpec, Convert_v1_PodSpec_To_api_PodSpec, + Convert_extensions_ScaleStatus_To_v1beta1_ScaleStatus, + Convert_v1beta1_ScaleStatus_To_extensions_ScaleStatus, Convert_extensions_DeploymentSpec_To_v1beta1_DeploymentSpec, Convert_v1beta1_DeploymentSpec_To_extensions_DeploymentSpec, Convert_extensions_DeploymentStrategy_To_v1beta1_DeploymentStrategy, @@ -42,6 +44,8 @@ func addConversionFuncs(scheme *runtime.Scheme) { Convert_v1beta1_RollingUpdateDeployment_To_extensions_RollingUpdateDeployment, Convert_extensions_ReplicaSetSpec_To_v1beta1_ReplicaSetSpec, Convert_v1beta1_ReplicaSetSpec_To_extensions_ReplicaSetSpec, + Convert_extensions_JobSpec_To_v1beta1_JobSpec, + Convert_v1beta1_JobSpec_To_extensions_JobSpec, ) if err != nil { // If one of the conversion functions is malformed, detect it immediately. @@ -91,6 +95,58 @@ func Convert_v1_PodSpec_To_api_PodSpec(in *v1.PodSpec, out *api.PodSpec, s conve return v1.Convert_v1_PodSpec_To_api_PodSpec(in, out, s) } +func Convert_extensions_ScaleStatus_To_v1beta1_ScaleStatus(in *extensions.ScaleStatus, out *ScaleStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.ScaleStatus))(in) + } + out.Replicas = int32(in.Replicas) + + out.Selector = nil + out.TargetSelector = "" + if in.Selector != nil { + if in.Selector.MatchExpressions == nil || len(in.Selector.MatchExpressions) == 0 { + out.Selector = in.Selector.MatchLabels + } + + selector, err := unversioned.LabelSelectorAsSelector(in.Selector) + if err != nil { + return fmt.Errorf("invalid label selector: %v", err) + } + out.TargetSelector = selector.String() + } + return nil +} + +func Convert_v1beta1_ScaleStatus_To_extensions_ScaleStatus(in *ScaleStatus, out *extensions.ScaleStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*ScaleStatus))(in) + } + out.Replicas = int(in.Replicas) + + // Normally when 2 fields map to the same internal value we favor the old field, since + // old clients can't be expected to know about new fields but clients that know about the + // new field can be expected to know about the old field (though that's not quite true, due + // to kubectl apply). However, these fields are readonly, so any non-nil value should work. + if in.TargetSelector != "" { + labelSelector, err := unversioned.ParseToLabelSelector(in.TargetSelector) + if err != nil { + out.Selector = nil + return fmt.Errorf("failed to parse target selector: %v", err) + } + out.Selector = labelSelector + } else if in.Selector != nil { + out.Selector = new(unversioned.LabelSelector) + selector := make(map[string]string) + for key, val := range in.Selector { + selector[key] = val + } + out.Selector.MatchLabels = selector + } else { + out.Selector = nil + } + return nil +} + func Convert_extensions_DeploymentSpec_To_v1beta1_DeploymentSpec(in *extensions.DeploymentSpec, out *DeploymentSpec, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.DeploymentSpec))(in) @@ -241,13 +297,9 @@ func Convert_extensions_ReplicaSetSpec_To_v1beta1_ReplicaSetSpec(in *extensions. } else { out.Selector = nil } - if in.Template != nil { - out.Template = new(v1.PodTemplateSpec) - if err := v1.Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(in.Template, out.Template, s); err != nil { - return err - } - } else { - out.Template = nil + + if err := v1.Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err } return nil } @@ -267,13 +319,112 @@ func Convert_v1beta1_ReplicaSetSpec_To_extensions_ReplicaSetSpec(in *ReplicaSetS } else { out.Selector = nil } - if in.Template != nil { - out.Template = new(api.PodTemplateSpec) - if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in.Template, out.Template, s); err != nil { - return err - } - } else { - out.Template = nil + if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + +func Convert_extensions_JobSpec_To_v1beta1_JobSpec(in *extensions.JobSpec, out *JobSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.JobSpec))(in) + } + if in.Parallelism != nil { + out.Parallelism = new(int32) + *out.Parallelism = int32(*in.Parallelism) + } else { + out.Parallelism = nil + } + if in.Completions != nil { + out.Completions = new(int32) + *out.Completions = int32(*in.Completions) + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + // unable to generate simple pointer conversion for unversioned.LabelSelector -> v1beta1.LabelSelector + if in.Selector != nil { + out.Selector = new(LabelSelector) + if err := Convert_unversioned_LabelSelector_To_v1beta1_LabelSelector(in.Selector, out.Selector, s); err != nil { + return err + } + } else { + out.Selector = nil + } + + // BEGIN non-standard conversion + // autoSelector has opposite meaning as manualSelector. + // in both cases, unset means false, and unset is always preferred to false. + // unset vs set-false distinction is not preserved. + manualSelector := in.ManualSelector != nil && *in.ManualSelector + autoSelector := !manualSelector + if autoSelector { + out.AutoSelector = new(bool) + *out.AutoSelector = true + } else { + out.AutoSelector = nil + } + // END non-standard conversion + + if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + +func Convert_v1beta1_JobSpec_To_extensions_JobSpec(in *JobSpec, out *extensions.JobSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*JobSpec))(in) + } + if in.Parallelism != nil { + out.Parallelism = new(int) + *out.Parallelism = int(*in.Parallelism) + } else { + out.Parallelism = nil + } + if in.Completions != nil { + out.Completions = new(int) + *out.Completions = int(*in.Completions) + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + out.ActiveDeadlineSeconds = new(int64) + *out.ActiveDeadlineSeconds = *in.ActiveDeadlineSeconds + } else { + out.ActiveDeadlineSeconds = nil + } + // unable to generate simple pointer conversion for v1beta1.LabelSelector -> unversioned.LabelSelector + if in.Selector != nil { + out.Selector = new(unversioned.LabelSelector) + if err := Convert_v1beta1_LabelSelector_To_unversioned_LabelSelector(in.Selector, out.Selector, s); err != nil { + return err + } + } else { + out.Selector = nil + } + + // BEGIN non-standard conversion + // autoSelector has opposite meaning as manualSelector. + // in both cases, unset means false, and unset is always preferred to false. + // unset vs set-false distinction is not preserved. + autoSelector := bool(in.AutoSelector != nil && *in.AutoSelector) + manualSelector := !autoSelector + if manualSelector { + out.ManualSelector = new(bool) + *out.ManualSelector = true + } else { + out.ManualSelector = nil + } + // END non-standard conversion + + if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err } return nil } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion_generated.go index f1c50ad2a..26ba97ece 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion_generated.go @@ -2700,76 +2700,6 @@ func Convert_extensions_CPUTargetUtilization_To_v1beta1_CPUTargetUtilization(in return autoConvert_extensions_CPUTargetUtilization_To_v1beta1_CPUTargetUtilization(in, out, s) } -func autoConvert_extensions_ClusterAutoscaler_To_v1beta1_ClusterAutoscaler(in *extensions.ClusterAutoscaler, out *ClusterAutoscaler, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*extensions.ClusterAutoscaler))(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_ClusterAutoscalerSpec_To_v1beta1_ClusterAutoscalerSpec(&in.Spec, &out.Spec, s); err != nil { - return err - } - return nil -} - -func Convert_extensions_ClusterAutoscaler_To_v1beta1_ClusterAutoscaler(in *extensions.ClusterAutoscaler, out *ClusterAutoscaler, s conversion.Scope) error { - return autoConvert_extensions_ClusterAutoscaler_To_v1beta1_ClusterAutoscaler(in, out, s) -} - -func autoConvert_extensions_ClusterAutoscalerList_To_v1beta1_ClusterAutoscalerList(in *extensions.ClusterAutoscalerList, out *ClusterAutoscalerList, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*extensions.ClusterAutoscalerList))(in) - } - 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 { - out.Items = make([]ClusterAutoscaler, len(in.Items)) - for i := range in.Items { - if err := Convert_extensions_ClusterAutoscaler_To_v1beta1_ClusterAutoscaler(&in.Items[i], &out.Items[i], s); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func Convert_extensions_ClusterAutoscalerList_To_v1beta1_ClusterAutoscalerList(in *extensions.ClusterAutoscalerList, out *ClusterAutoscalerList, s conversion.Scope) error { - return autoConvert_extensions_ClusterAutoscalerList_To_v1beta1_ClusterAutoscalerList(in, out, s) -} - -func autoConvert_extensions_ClusterAutoscalerSpec_To_v1beta1_ClusterAutoscalerSpec(in *extensions.ClusterAutoscalerSpec, out *ClusterAutoscalerSpec, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*extensions.ClusterAutoscalerSpec))(in) - } - out.MinNodes = int32(in.MinNodes) - out.MaxNodes = int32(in.MaxNodes) - if in.TargetUtilization != nil { - out.TargetUtilization = make([]NodeUtilization, len(in.TargetUtilization)) - for i := range in.TargetUtilization { - if err := Convert_extensions_NodeUtilization_To_v1beta1_NodeUtilization(&in.TargetUtilization[i], &out.TargetUtilization[i], s); err != nil { - return err - } - } - } else { - out.TargetUtilization = nil - } - return nil -} - -func Convert_extensions_ClusterAutoscalerSpec_To_v1beta1_ClusterAutoscalerSpec(in *extensions.ClusterAutoscalerSpec, out *ClusterAutoscalerSpec, s conversion.Scope) error { - return autoConvert_extensions_ClusterAutoscalerSpec_To_v1beta1_ClusterAutoscalerSpec(in, out, s) -} - func autoConvert_extensions_DaemonSet_To_v1beta1_DaemonSet(in *extensions.DaemonSet, out *DaemonSet, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.DaemonSet))(in) @@ -2979,6 +2909,7 @@ func autoConvert_extensions_DeploymentStatus_To_v1beta1_DeploymentStatus(in *ext if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.DeploymentStatus))(in) } + out.ObservedGeneration = in.ObservedGeneration out.Replicas = int32(in.Replicas) out.UpdatedReplicas = int32(in.UpdatedReplicas) out.AvailableReplicas = int32(in.AvailableReplicas) @@ -3459,16 +3390,13 @@ func autoConvert_extensions_JobSpec_To_v1beta1_JobSpec(in *extensions.JobSpec, o } else { out.Selector = nil } + // in.ManualSelector has no peer in out if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { return err } return nil } -func Convert_extensions_JobSpec_To_v1beta1_JobSpec(in *extensions.JobSpec, out *JobSpec, s conversion.Scope) error { - return autoConvert_extensions_JobSpec_To_v1beta1_JobSpec(in, out, s) -} - func autoConvert_extensions_JobStatus_To_v1beta1_JobStatus(in *extensions.JobStatus, out *JobStatus, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.JobStatus))(in) @@ -3511,19 +3439,6 @@ func Convert_extensions_JobStatus_To_v1beta1_JobStatus(in *extensions.JobStatus, return autoConvert_extensions_JobStatus_To_v1beta1_JobStatus(in, out, s) } -func autoConvert_extensions_NodeUtilization_To_v1beta1_NodeUtilization(in *extensions.NodeUtilization, out *NodeUtilization, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*extensions.NodeUtilization))(in) - } - out.Resource = NodeResource(in.Resource) - out.Value = in.Value - return nil -} - -func Convert_extensions_NodeUtilization_To_v1beta1_NodeUtilization(in *extensions.NodeUtilization, out *NodeUtilization, s conversion.Scope) error { - return autoConvert_extensions_NodeUtilization_To_v1beta1_NodeUtilization(in, out, s) -} - func autoConvert_extensions_PodSecurityPolicy_To_v1beta1_PodSecurityPolicy(in *extensions.PodSecurityPolicy, out *PodSecurityPolicy, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.PodSecurityPolicy))(in) @@ -3605,7 +3520,7 @@ func autoConvert_extensions_PodSecurityPolicySpec_To_v1beta1_PodSecurityPolicySp } out.HostPID = in.HostPID out.HostIPC = in.HostIPC - if err := Convert_extensions_SELinuxContextStrategyOptions_To_v1beta1_SELinuxContextStrategyOptions(&in.SELinuxContext, &out.SELinuxContext, s); err != nil { + if err := Convert_extensions_SELinuxStrategyOptions_To_v1beta1_SELinuxStrategyOptions(&in.SELinux, &out.SELinux, s); err != nil { return err } if err := Convert_extensions_RunAsUserStrategyOptions_To_v1beta1_RunAsUserStrategyOptions(&in.RunAsUser, &out.RunAsUser, s); err != nil { @@ -3684,14 +3599,8 @@ func autoConvert_extensions_ReplicaSetSpec_To_v1beta1_ReplicaSetSpec(in *extensi } else { out.Selector = nil } - // unable to generate simple pointer conversion for api.PodTemplateSpec -> v1.PodTemplateSpec - if in.Template != nil { - out.Template = new(v1.PodTemplateSpec) - if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(in.Template, out.Template, s); err != nil { - return err - } - } else { - out.Template = nil + if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err } return nil } @@ -3701,6 +3610,7 @@ func autoConvert_extensions_ReplicaSetStatus_To_v1beta1_ReplicaSetStatus(in *ext defaulting.(func(*extensions.ReplicaSetStatus))(in) } out.Replicas = int32(in.Replicas) + out.FullyLabeledReplicas = int32(in.FullyLabeledReplicas) out.ObservedGeneration = in.ObservedGeneration return nil } @@ -3752,7 +3662,7 @@ func autoConvert_extensions_RunAsUserStrategyOptions_To_v1beta1_RunAsUserStrateg if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.RunAsUserStrategyOptions))(in) } - out.Type = RunAsUserStrategy(in.Type) + out.Rule = RunAsUserStrategy(in.Rule) if in.Ranges != nil { out.Ranges = make([]IDRange, len(in.Ranges)) for i := range in.Ranges { @@ -3770,11 +3680,11 @@ func Convert_extensions_RunAsUserStrategyOptions_To_v1beta1_RunAsUserStrategyOpt return autoConvert_extensions_RunAsUserStrategyOptions_To_v1beta1_RunAsUserStrategyOptions(in, out, s) } -func autoConvert_extensions_SELinuxContextStrategyOptions_To_v1beta1_SELinuxContextStrategyOptions(in *extensions.SELinuxContextStrategyOptions, out *SELinuxContextStrategyOptions, s conversion.Scope) error { +func autoConvert_extensions_SELinuxStrategyOptions_To_v1beta1_SELinuxStrategyOptions(in *extensions.SELinuxStrategyOptions, out *SELinuxStrategyOptions, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*extensions.SELinuxContextStrategyOptions))(in) + defaulting.(func(*extensions.SELinuxStrategyOptions))(in) } - out.Type = SELinuxContextStrategy(in.Type) + out.Rule = SELinuxStrategy(in.Rule) // unable to generate simple pointer conversion for api.SELinuxOptions -> v1.SELinuxOptions if in.SELinuxOptions != nil { out.SELinuxOptions = new(v1.SELinuxOptions) @@ -3787,8 +3697,8 @@ func autoConvert_extensions_SELinuxContextStrategyOptions_To_v1beta1_SELinuxCont return nil } -func Convert_extensions_SELinuxContextStrategyOptions_To_v1beta1_SELinuxContextStrategyOptions(in *extensions.SELinuxContextStrategyOptions, out *SELinuxContextStrategyOptions, s conversion.Scope) error { - return autoConvert_extensions_SELinuxContextStrategyOptions_To_v1beta1_SELinuxContextStrategyOptions(in, out, s) +func Convert_extensions_SELinuxStrategyOptions_To_v1beta1_SELinuxStrategyOptions(in *extensions.SELinuxStrategyOptions, out *SELinuxStrategyOptions, s conversion.Scope) error { + return autoConvert_extensions_SELinuxStrategyOptions_To_v1beta1_SELinuxStrategyOptions(in, out, s) } func autoConvert_extensions_Scale_To_v1beta1_Scale(in *extensions.Scale, out *Scale, s conversion.Scope) error { @@ -3831,21 +3741,10 @@ func autoConvert_extensions_ScaleStatus_To_v1beta1_ScaleStatus(in *extensions.Sc defaulting.(func(*extensions.ScaleStatus))(in) } out.Replicas = int32(in.Replicas) - if in.Selector != nil { - out.Selector = make(map[string]string) - for key, val := range in.Selector { - out.Selector[key] = val - } - } else { - out.Selector = nil - } + // in.Selector has no peer in out return nil } -func Convert_extensions_ScaleStatus_To_v1beta1_ScaleStatus(in *extensions.ScaleStatus, out *ScaleStatus, s conversion.Scope) error { - return autoConvert_extensions_ScaleStatus_To_v1beta1_ScaleStatus(in, out, s) -} - func autoConvert_extensions_SubresourceReference_To_v1beta1_SubresourceReference(in *extensions.SubresourceReference, out *SubresourceReference, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*extensions.SubresourceReference))(in) @@ -3988,76 +3887,6 @@ func Convert_v1beta1_CPUTargetUtilization_To_extensions_CPUTargetUtilization(in return autoConvert_v1beta1_CPUTargetUtilization_To_extensions_CPUTargetUtilization(in, out, s) } -func autoConvert_v1beta1_ClusterAutoscaler_To_extensions_ClusterAutoscaler(in *ClusterAutoscaler, out *extensions.ClusterAutoscaler, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*ClusterAutoscaler))(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_v1beta1_ClusterAutoscalerSpec_To_extensions_ClusterAutoscalerSpec(&in.Spec, &out.Spec, s); err != nil { - return err - } - return nil -} - -func Convert_v1beta1_ClusterAutoscaler_To_extensions_ClusterAutoscaler(in *ClusterAutoscaler, out *extensions.ClusterAutoscaler, s conversion.Scope) error { - return autoConvert_v1beta1_ClusterAutoscaler_To_extensions_ClusterAutoscaler(in, out, s) -} - -func autoConvert_v1beta1_ClusterAutoscalerList_To_extensions_ClusterAutoscalerList(in *ClusterAutoscalerList, out *extensions.ClusterAutoscalerList, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*ClusterAutoscalerList))(in) - } - 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 { - out.Items = make([]extensions.ClusterAutoscaler, len(in.Items)) - for i := range in.Items { - if err := Convert_v1beta1_ClusterAutoscaler_To_extensions_ClusterAutoscaler(&in.Items[i], &out.Items[i], s); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func Convert_v1beta1_ClusterAutoscalerList_To_extensions_ClusterAutoscalerList(in *ClusterAutoscalerList, out *extensions.ClusterAutoscalerList, s conversion.Scope) error { - return autoConvert_v1beta1_ClusterAutoscalerList_To_extensions_ClusterAutoscalerList(in, out, s) -} - -func autoConvert_v1beta1_ClusterAutoscalerSpec_To_extensions_ClusterAutoscalerSpec(in *ClusterAutoscalerSpec, out *extensions.ClusterAutoscalerSpec, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*ClusterAutoscalerSpec))(in) - } - out.MinNodes = int(in.MinNodes) - out.MaxNodes = int(in.MaxNodes) - if in.TargetUtilization != nil { - out.TargetUtilization = make([]extensions.NodeUtilization, len(in.TargetUtilization)) - for i := range in.TargetUtilization { - if err := Convert_v1beta1_NodeUtilization_To_extensions_NodeUtilization(&in.TargetUtilization[i], &out.TargetUtilization[i], s); err != nil { - return err - } - } - } else { - out.TargetUtilization = nil - } - return nil -} - -func Convert_v1beta1_ClusterAutoscalerSpec_To_extensions_ClusterAutoscalerSpec(in *ClusterAutoscalerSpec, out *extensions.ClusterAutoscalerSpec, s conversion.Scope) error { - return autoConvert_v1beta1_ClusterAutoscalerSpec_To_extensions_ClusterAutoscalerSpec(in, out, s) -} - func autoConvert_v1beta1_DaemonSet_To_extensions_DaemonSet(in *DaemonSet, out *extensions.DaemonSet, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*DaemonSet))(in) @@ -4265,6 +4094,7 @@ func autoConvert_v1beta1_DeploymentStatus_To_extensions_DeploymentStatus(in *Dep if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*DeploymentStatus))(in) } + out.ObservedGeneration = in.ObservedGeneration out.Replicas = int(in.Replicas) out.UpdatedReplicas = int(in.UpdatedReplicas) out.AvailableReplicas = int(in.AvailableReplicas) @@ -4728,16 +4558,13 @@ func autoConvert_v1beta1_JobSpec_To_extensions_JobSpec(in *JobSpec, out *extensi } else { out.Selector = nil } + // in.AutoSelector has no peer in out if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { return err } return nil } -func Convert_v1beta1_JobSpec_To_extensions_JobSpec(in *JobSpec, out *extensions.JobSpec, s conversion.Scope) error { - return autoConvert_v1beta1_JobSpec_To_extensions_JobSpec(in, out, s) -} - func autoConvert_v1beta1_JobStatus_To_extensions_JobStatus(in *JobStatus, out *extensions.JobStatus, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*JobStatus))(in) @@ -4858,19 +4685,6 @@ func Convert_v1beta1_ListOptions_To_api_ListOptions(in *ListOptions, out *api.Li return autoConvert_v1beta1_ListOptions_To_api_ListOptions(in, out, s) } -func autoConvert_v1beta1_NodeUtilization_To_extensions_NodeUtilization(in *NodeUtilization, out *extensions.NodeUtilization, s conversion.Scope) error { - if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*NodeUtilization))(in) - } - out.Resource = extensions.NodeResource(in.Resource) - out.Value = in.Value - return nil -} - -func Convert_v1beta1_NodeUtilization_To_extensions_NodeUtilization(in *NodeUtilization, out *extensions.NodeUtilization, s conversion.Scope) error { - return autoConvert_v1beta1_NodeUtilization_To_extensions_NodeUtilization(in, out, s) -} - func autoConvert_v1beta1_PodSecurityPolicy_To_extensions_PodSecurityPolicy(in *PodSecurityPolicy, out *extensions.PodSecurityPolicy, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*PodSecurityPolicy))(in) @@ -4952,7 +4766,7 @@ func autoConvert_v1beta1_PodSecurityPolicySpec_To_extensions_PodSecurityPolicySp } out.HostPID = in.HostPID out.HostIPC = in.HostIPC - if err := Convert_v1beta1_SELinuxContextStrategyOptions_To_extensions_SELinuxContextStrategyOptions(&in.SELinuxContext, &out.SELinuxContext, s); err != nil { + if err := Convert_v1beta1_SELinuxStrategyOptions_To_extensions_SELinuxStrategyOptions(&in.SELinux, &out.SELinux, s); err != nil { return err } if err := Convert_v1beta1_RunAsUserStrategyOptions_To_extensions_RunAsUserStrategyOptions(&in.RunAsUser, &out.RunAsUser, s); err != nil { @@ -5029,14 +4843,8 @@ func autoConvert_v1beta1_ReplicaSetSpec_To_extensions_ReplicaSetSpec(in *Replica } else { out.Selector = nil } - // unable to generate simple pointer conversion for v1.PodTemplateSpec -> api.PodTemplateSpec - if in.Template != nil { - out.Template = new(api.PodTemplateSpec) - if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in.Template, out.Template, s); err != nil { - return err - } - } else { - out.Template = nil + if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err } return nil } @@ -5046,6 +4854,7 @@ func autoConvert_v1beta1_ReplicaSetStatus_To_extensions_ReplicaSetStatus(in *Rep defaulting.(func(*ReplicaSetStatus))(in) } out.Replicas = int(in.Replicas) + out.FullyLabeledReplicas = int(in.FullyLabeledReplicas) out.ObservedGeneration = in.ObservedGeneration return nil } @@ -5093,7 +4902,7 @@ func autoConvert_v1beta1_RunAsUserStrategyOptions_To_extensions_RunAsUserStrateg if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*RunAsUserStrategyOptions))(in) } - out.Type = extensions.RunAsUserStrategy(in.Type) + out.Rule = extensions.RunAsUserStrategy(in.Rule) if in.Ranges != nil { out.Ranges = make([]extensions.IDRange, len(in.Ranges)) for i := range in.Ranges { @@ -5111,11 +4920,11 @@ func Convert_v1beta1_RunAsUserStrategyOptions_To_extensions_RunAsUserStrategyOpt return autoConvert_v1beta1_RunAsUserStrategyOptions_To_extensions_RunAsUserStrategyOptions(in, out, s) } -func autoConvert_v1beta1_SELinuxContextStrategyOptions_To_extensions_SELinuxContextStrategyOptions(in *SELinuxContextStrategyOptions, out *extensions.SELinuxContextStrategyOptions, s conversion.Scope) error { +func autoConvert_v1beta1_SELinuxStrategyOptions_To_extensions_SELinuxStrategyOptions(in *SELinuxStrategyOptions, out *extensions.SELinuxStrategyOptions, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { - defaulting.(func(*SELinuxContextStrategyOptions))(in) + defaulting.(func(*SELinuxStrategyOptions))(in) } - out.Type = extensions.SELinuxContextStrategy(in.Type) + out.Rule = extensions.SELinuxStrategy(in.Rule) // unable to generate simple pointer conversion for v1.SELinuxOptions -> api.SELinuxOptions if in.SELinuxOptions != nil { out.SELinuxOptions = new(api.SELinuxOptions) @@ -5128,8 +4937,8 @@ func autoConvert_v1beta1_SELinuxContextStrategyOptions_To_extensions_SELinuxCont return nil } -func Convert_v1beta1_SELinuxContextStrategyOptions_To_extensions_SELinuxContextStrategyOptions(in *SELinuxContextStrategyOptions, out *extensions.SELinuxContextStrategyOptions, s conversion.Scope) error { - return autoConvert_v1beta1_SELinuxContextStrategyOptions_To_extensions_SELinuxContextStrategyOptions(in, out, s) +func Convert_v1beta1_SELinuxStrategyOptions_To_extensions_SELinuxStrategyOptions(in *SELinuxStrategyOptions, out *extensions.SELinuxStrategyOptions, s conversion.Scope) error { + return autoConvert_v1beta1_SELinuxStrategyOptions_To_extensions_SELinuxStrategyOptions(in, out, s) } func autoConvert_v1beta1_Scale_To_extensions_Scale(in *Scale, out *extensions.Scale, s conversion.Scope) error { @@ -5172,21 +4981,11 @@ func autoConvert_v1beta1_ScaleStatus_To_extensions_ScaleStatus(in *ScaleStatus, defaulting.(func(*ScaleStatus))(in) } out.Replicas = int(in.Replicas) - if in.Selector != nil { - out.Selector = make(map[string]string) - for key, val := range in.Selector { - out.Selector[key] = val - } - } else { - out.Selector = nil - } + // in.Selector has no peer in out + // in.TargetSelector has no peer in out return nil } -func Convert_v1beta1_ScaleStatus_To_extensions_ScaleStatus(in *ScaleStatus, out *extensions.ScaleStatus, s conversion.Scope) error { - return autoConvert_v1beta1_ScaleStatus_To_extensions_ScaleStatus(in, out, s) -} - func autoConvert_v1beta1_SubresourceReference_To_extensions_SubresourceReference(in *SubresourceReference, out *extensions.SubresourceReference, s conversion.Scope) error { if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { defaulting.(func(*SubresourceReference))(in) @@ -5357,9 +5156,6 @@ func init() { autoConvert_api_Volume_To_v1_Volume, autoConvert_extensions_APIVersion_To_v1beta1_APIVersion, autoConvert_extensions_CPUTargetUtilization_To_v1beta1_CPUTargetUtilization, - autoConvert_extensions_ClusterAutoscalerList_To_v1beta1_ClusterAutoscalerList, - autoConvert_extensions_ClusterAutoscalerSpec_To_v1beta1_ClusterAutoscalerSpec, - autoConvert_extensions_ClusterAutoscaler_To_v1beta1_ClusterAutoscaler, autoConvert_extensions_DaemonSetList_To_v1beta1_DaemonSetList, autoConvert_extensions_DaemonSetSpec_To_v1beta1_DaemonSetSpec, autoConvert_extensions_DaemonSetStatus_To_v1beta1_DaemonSetStatus, @@ -5391,7 +5187,6 @@ func init() { autoConvert_extensions_JobSpec_To_v1beta1_JobSpec, autoConvert_extensions_JobStatus_To_v1beta1_JobStatus, autoConvert_extensions_Job_To_v1beta1_Job, - autoConvert_extensions_NodeUtilization_To_v1beta1_NodeUtilization, autoConvert_extensions_PodSecurityPolicyList_To_v1beta1_PodSecurityPolicyList, autoConvert_extensions_PodSecurityPolicySpec_To_v1beta1_PodSecurityPolicySpec, autoConvert_extensions_PodSecurityPolicy_To_v1beta1_PodSecurityPolicy, @@ -5403,7 +5198,7 @@ func init() { autoConvert_extensions_RollbackConfig_To_v1beta1_RollbackConfig, autoConvert_extensions_RollingUpdateDeployment_To_v1beta1_RollingUpdateDeployment, autoConvert_extensions_RunAsUserStrategyOptions_To_v1beta1_RunAsUserStrategyOptions, - autoConvert_extensions_SELinuxContextStrategyOptions_To_v1beta1_SELinuxContextStrategyOptions, + autoConvert_extensions_SELinuxStrategyOptions_To_v1beta1_SELinuxStrategyOptions, autoConvert_extensions_ScaleSpec_To_v1beta1_ScaleSpec, autoConvert_extensions_ScaleStatus_To_v1beta1_ScaleStatus, autoConvert_extensions_Scale_To_v1beta1_Scale, @@ -5464,9 +5259,6 @@ func init() { autoConvert_v1_Volume_To_api_Volume, autoConvert_v1beta1_APIVersion_To_extensions_APIVersion, autoConvert_v1beta1_CPUTargetUtilization_To_extensions_CPUTargetUtilization, - autoConvert_v1beta1_ClusterAutoscalerList_To_extensions_ClusterAutoscalerList, - autoConvert_v1beta1_ClusterAutoscalerSpec_To_extensions_ClusterAutoscalerSpec, - autoConvert_v1beta1_ClusterAutoscaler_To_extensions_ClusterAutoscaler, autoConvert_v1beta1_DaemonSetList_To_extensions_DaemonSetList, autoConvert_v1beta1_DaemonSetSpec_To_extensions_DaemonSetSpec, autoConvert_v1beta1_DaemonSetStatus_To_extensions_DaemonSetStatus, @@ -5500,7 +5292,6 @@ func init() { autoConvert_v1beta1_LabelSelectorRequirement_To_unversioned_LabelSelectorRequirement, autoConvert_v1beta1_LabelSelector_To_unversioned_LabelSelector, autoConvert_v1beta1_ListOptions_To_api_ListOptions, - autoConvert_v1beta1_NodeUtilization_To_extensions_NodeUtilization, autoConvert_v1beta1_PodSecurityPolicyList_To_extensions_PodSecurityPolicyList, autoConvert_v1beta1_PodSecurityPolicySpec_To_extensions_PodSecurityPolicySpec, autoConvert_v1beta1_PodSecurityPolicy_To_extensions_PodSecurityPolicy, @@ -5512,7 +5303,7 @@ func init() { autoConvert_v1beta1_RollbackConfig_To_extensions_RollbackConfig, autoConvert_v1beta1_RollingUpdateDeployment_To_extensions_RollingUpdateDeployment, autoConvert_v1beta1_RunAsUserStrategyOptions_To_extensions_RunAsUserStrategyOptions, - autoConvert_v1beta1_SELinuxContextStrategyOptions_To_extensions_SELinuxContextStrategyOptions, + autoConvert_v1beta1_SELinuxStrategyOptions_To_extensions_SELinuxStrategyOptions, autoConvert_v1beta1_ScaleSpec_To_extensions_ScaleSpec, autoConvert_v1beta1_ScaleStatus_To_extensions_ScaleStatus, autoConvert_v1beta1_Scale_To_extensions_Scale, diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/deep_copy_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/deep_copy_generated.go index d1ba9f6de..845e4dd7f 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/deep_copy_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/deep_copy_generated.go @@ -1030,55 +1030,6 @@ func deepCopy_v1beta1_CPUTargetUtilization(in CPUTargetUtilization, out *CPUTarg return nil } -func deepCopy_v1beta1_ClusterAutoscaler(in ClusterAutoscaler, out *ClusterAutoscaler, c *conversion.Cloner) error { - if err := 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_v1beta1_ClusterAutoscalerSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func deepCopy_v1beta1_ClusterAutoscalerList(in ClusterAutoscalerList, out *ClusterAutoscalerList, 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 - } - if in.Items != nil { - out.Items = make([]ClusterAutoscaler, len(in.Items)) - for i := range in.Items { - if err := deepCopy_v1beta1_ClusterAutoscaler(in.Items[i], &out.Items[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func deepCopy_v1beta1_ClusterAutoscalerSpec(in ClusterAutoscalerSpec, out *ClusterAutoscalerSpec, c *conversion.Cloner) error { - out.MinNodes = in.MinNodes - out.MaxNodes = in.MaxNodes - if in.TargetUtilization != nil { - out.TargetUtilization = make([]NodeUtilization, len(in.TargetUtilization)) - for i := range in.TargetUtilization { - if err := deepCopy_v1beta1_NodeUtilization(in.TargetUtilization[i], &out.TargetUtilization[i], c); err != nil { - return err - } - } - } else { - out.TargetUtilization = nil - } - return nil -} - func deepCopy_v1beta1_DaemonSet(in DaemonSet, out *DaemonSet, c *conversion.Cloner) error { if err := deepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { return err @@ -1233,6 +1184,7 @@ func deepCopy_v1beta1_DeploymentSpec(in DeploymentSpec, out *DeploymentSpec, c * } 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 @@ -1564,6 +1516,12 @@ func deepCopy_v1beta1_JobSpec(in JobSpec, out *JobSpec, c *conversion.Cloner) er } else { out.Selector = nil } + if in.AutoSelector != nil { + out.AutoSelector = new(bool) + *out.AutoSelector = *in.AutoSelector + } else { + out.AutoSelector = nil + } if err := deepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { return err } @@ -1656,12 +1614,6 @@ func deepCopy_v1beta1_ListOptions(in ListOptions, out *ListOptions, c *conversio return nil } -func deepCopy_v1beta1_NodeUtilization(in NodeUtilization, out *NodeUtilization, c *conversion.Cloner) error { - out.Resource = in.Resource - out.Value = in.Value - return nil -} - func deepCopy_v1beta1_PodSecurityPolicy(in PodSecurityPolicy, out *PodSecurityPolicy, c *conversion.Cloner) error { if err := deepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { return err @@ -1726,7 +1678,7 @@ func deepCopy_v1beta1_PodSecurityPolicySpec(in PodSecurityPolicySpec, out *PodSe } out.HostPID = in.HostPID out.HostIPC = in.HostIPC - if err := deepCopy_v1beta1_SELinuxContextStrategyOptions(in.SELinuxContext, &out.SELinuxContext, c); err != nil { + 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 { @@ -1786,19 +1738,15 @@ func deepCopy_v1beta1_ReplicaSetSpec(in ReplicaSetSpec, out *ReplicaSetSpec, c * } else { out.Selector = nil } - if in.Template != nil { - out.Template = new(v1.PodTemplateSpec) - if err := deepCopy_v1_PodTemplateSpec(*in.Template, out.Template, c); err != nil { - return err - } - } else { - out.Template = nil + if err := 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 } @@ -1836,7 +1784,7 @@ func deepCopy_v1beta1_RollingUpdateDeployment(in RollingUpdateDeployment, out *R } func deepCopy_v1beta1_RunAsUserStrategyOptions(in RunAsUserStrategyOptions, out *RunAsUserStrategyOptions, c *conversion.Cloner) error { - out.Type = in.Type + out.Rule = in.Rule if in.Ranges != nil { out.Ranges = make([]IDRange, len(in.Ranges)) for i := range in.Ranges { @@ -1850,8 +1798,8 @@ func deepCopy_v1beta1_RunAsUserStrategyOptions(in RunAsUserStrategyOptions, out return nil } -func deepCopy_v1beta1_SELinuxContextStrategyOptions(in SELinuxContextStrategyOptions, out *SELinuxContextStrategyOptions, c *conversion.Cloner) error { - out.Type = in.Type +func deepCopy_v1beta1_SELinuxStrategyOptions(in SELinuxStrategyOptions, out *SELinuxStrategyOptions, c *conversion.Cloner) error { + out.Rule = in.Rule if in.SELinuxOptions != nil { out.SELinuxOptions = new(v1.SELinuxOptions) if err := deepCopy_v1_SELinuxOptions(*in.SELinuxOptions, out.SELinuxOptions, c); err != nil { @@ -1894,6 +1842,7 @@ func deepCopy_v1beta1_ScaleStatus(in ScaleStatus, out *ScaleStatus, c *conversio } else { out.Selector = nil } + out.TargetSelector = in.TargetSelector return nil } @@ -2048,9 +1997,6 @@ func init() { deepCopy_v1_VolumeSource, deepCopy_v1beta1_APIVersion, deepCopy_v1beta1_CPUTargetUtilization, - deepCopy_v1beta1_ClusterAutoscaler, - deepCopy_v1beta1_ClusterAutoscalerList, - deepCopy_v1beta1_ClusterAutoscalerSpec, deepCopy_v1beta1_DaemonSet, deepCopy_v1beta1_DaemonSetList, deepCopy_v1beta1_DaemonSetSpec, @@ -2085,7 +2031,6 @@ func init() { deepCopy_v1beta1_LabelSelector, deepCopy_v1beta1_LabelSelectorRequirement, deepCopy_v1beta1_ListOptions, - deepCopy_v1beta1_NodeUtilization, deepCopy_v1beta1_PodSecurityPolicy, deepCopy_v1beta1_PodSecurityPolicyList, deepCopy_v1beta1_PodSecurityPolicySpec, @@ -2097,7 +2042,7 @@ func init() { deepCopy_v1beta1_RollbackConfig, deepCopy_v1beta1_RollingUpdateDeployment, deepCopy_v1beta1_RunAsUserStrategyOptions, - deepCopy_v1beta1_SELinuxContextStrategyOptions, + deepCopy_v1beta1_SELinuxStrategyOptions, deepCopy_v1beta1_Scale, deepCopy_v1beta1_ScaleSpec, deepCopy_v1beta1_ScaleStatus, diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go index cb197a965..46d4c3785 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go @@ -86,7 +86,14 @@ func addDefaultingFuncs(scheme *runtime.Scheme) { labels := obj.Spec.Template.Labels // TODO: support templates defined elsewhere when we support them in the API if labels != nil { - if obj.Spec.Selector == nil { + // if an autoselector is requested, we'll build the selector later with controller-uid and job-name + autoSelector := bool(obj.Spec.AutoSelector != nil && *obj.Spec.AutoSelector) + + // otherwise, we are using a manual selector + manualSelector := !autoSelector + + // and default behavior for an unspecified manual selector is to use the pod template labels + if manualSelector && obj.Spec.Selector == nil { obj.Spec.Selector = &LabelSelector{ MatchLabels: labels, } @@ -118,10 +125,8 @@ func addDefaultingFuncs(scheme *runtime.Scheme) { } }, func(obj *ReplicaSet) { - var labels map[string]string - if obj.Spec.Template != nil { - labels = obj.Spec.Template.Labels - } + labels := obj.Spec.Template.Labels + // TODO: support templates defined elsewhere when we support them in the API if labels != nil { if obj.Spec.Selector == nil { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults_test.go deleted file mode 100644 index 85b991980..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults_test.go +++ /dev/null @@ -1,663 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package v1beta1_test - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - _ "k8s.io/kubernetes/pkg/api/install" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/v1" - _ "k8s.io/kubernetes/pkg/apis/extensions/install" - . "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/intstr" -) - -func TestSetDefaultDaemonSet(t *testing.T) { - defaultLabels := map[string]string{"foo": "bar"} - period := int64(v1.DefaultTerminationGracePeriodSeconds) - defaultTemplate := v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - DNSPolicy: v1.DNSClusterFirst, - RestartPolicy: v1.RestartPolicyAlways, - SecurityContext: &v1.PodSecurityContext{}, - TerminationGracePeriodSeconds: &period, - }, - ObjectMeta: v1.ObjectMeta{ - Labels: defaultLabels, - }, - } - templateNoLabel := v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - DNSPolicy: v1.DNSClusterFirst, - RestartPolicy: v1.RestartPolicyAlways, - SecurityContext: &v1.PodSecurityContext{}, - TerminationGracePeriodSeconds: &period, - }, - } - tests := []struct { - original *DaemonSet - expected *DaemonSet - }{ - { // Labels change/defaulting test. - original: &DaemonSet{ - Spec: DaemonSetSpec{ - Template: defaultTemplate, - }, - }, - expected: &DaemonSet{ - ObjectMeta: v1.ObjectMeta{ - Labels: defaultLabels, - }, - Spec: DaemonSetSpec{ - Selector: &LabelSelector{ - MatchLabels: defaultLabels, - }, - Template: defaultTemplate, - }, - }, - }, - { // Labels change/defaulting test. - original: &DaemonSet{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: DaemonSetSpec{ - Template: defaultTemplate, - }, - }, - expected: &DaemonSet{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: DaemonSetSpec{ - Selector: &LabelSelector{ - MatchLabels: defaultLabels, - }, - Template: defaultTemplate, - }, - }, - }, - { // Update strategy. - original: &DaemonSet{}, - expected: &DaemonSet{ - Spec: DaemonSetSpec{ - Template: templateNoLabel, - }, - }, - }, - { // Update strategy. - original: &DaemonSet{ - Spec: DaemonSetSpec{}, - }, - expected: &DaemonSet{ - Spec: DaemonSetSpec{ - Template: templateNoLabel, - }, - }, - }, - { // Custom unique label key. - original: &DaemonSet{ - Spec: DaemonSetSpec{}, - }, - expected: &DaemonSet{ - Spec: DaemonSetSpec{ - Template: templateNoLabel, - }, - }, - }, - } - - for i, test := range tests { - original := test.original - expected := test.expected - obj2 := roundTrip(t, runtime.Object(original)) - got, ok := obj2.(*DaemonSet) - if !ok { - t.Errorf("(%d) unexpected object: %v", i, got) - t.FailNow() - } - if !reflect.DeepEqual(got.Spec, expected.Spec) { - t.Errorf("(%d) got different than expected\ngot:\n\t%+v\nexpected:\n\t%+v", i, got.Spec, expected.Spec) - } - } -} - -func TestSetDefaultDeployment(t *testing.T) { - defaultIntOrString := intstr.FromInt(1) - differentIntOrString := intstr.FromInt(5) - period := int64(v1.DefaultTerminationGracePeriodSeconds) - defaultTemplate := v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - DNSPolicy: v1.DNSClusterFirst, - RestartPolicy: v1.RestartPolicyAlways, - SecurityContext: &v1.PodSecurityContext{}, - TerminationGracePeriodSeconds: &period, - }, - } - tests := []struct { - original *Deployment - expected *Deployment - }{ - { - original: &Deployment{}, - expected: &Deployment{ - Spec: DeploymentSpec{ - Replicas: newInt32(1), - Strategy: DeploymentStrategy{ - Type: RollingUpdateDeploymentStrategyType, - RollingUpdate: &RollingUpdateDeployment{ - MaxSurge: &defaultIntOrString, - MaxUnavailable: &defaultIntOrString, - }, - }, - Template: defaultTemplate, - }, - }, - }, - { - original: &Deployment{ - Spec: DeploymentSpec{ - Replicas: newInt32(5), - Strategy: DeploymentStrategy{ - RollingUpdate: &RollingUpdateDeployment{ - MaxSurge: &differentIntOrString, - }, - }, - }, - }, - expected: &Deployment{ - Spec: DeploymentSpec{ - Replicas: newInt32(5), - Strategy: DeploymentStrategy{ - Type: RollingUpdateDeploymentStrategyType, - RollingUpdate: &RollingUpdateDeployment{ - MaxSurge: &differentIntOrString, - MaxUnavailable: &defaultIntOrString, - }, - }, - Template: defaultTemplate, - }, - }, - }, - { - original: &Deployment{ - Spec: DeploymentSpec{ - Replicas: newInt32(5), - Strategy: DeploymentStrategy{ - Type: RecreateDeploymentStrategyType, - }, - }, - }, - expected: &Deployment{ - Spec: DeploymentSpec{ - Replicas: newInt32(5), - Strategy: DeploymentStrategy{ - Type: RecreateDeploymentStrategyType, - }, - Template: defaultTemplate, - }, - }, - }, - { - original: &Deployment{ - Spec: DeploymentSpec{ - Replicas: newInt32(5), - Strategy: DeploymentStrategy{ - Type: RecreateDeploymentStrategyType, - }, - }, - }, - expected: &Deployment{ - Spec: DeploymentSpec{ - Replicas: newInt32(5), - Strategy: DeploymentStrategy{ - Type: RecreateDeploymentStrategyType, - }, - Template: defaultTemplate, - }, - }, - }, - } - - for _, test := range tests { - original := test.original - expected := test.expected - obj2 := roundTrip(t, runtime.Object(original)) - got, ok := obj2.(*Deployment) - if !ok { - t.Errorf("unexpected object: %v", got) - t.FailNow() - } - if !reflect.DeepEqual(got.Spec, expected.Spec) { - t.Errorf("got different than expected:\n\t%+v\ngot:\n\t%+v", got.Spec, expected.Spec) - } - } -} - -func TestSetDefaultJobParallelismAndCompletions(t *testing.T) { - tests := []struct { - original *Job - expected *Job - }{ - // both unspecified -> sets both to 1 - { - original: &Job{ - Spec: JobSpec{}, - }, - expected: &Job{ - Spec: JobSpec{ - Completions: newInt32(1), - Parallelism: newInt32(1), - }, - }, - }, - // WQ: Parallelism explicitly 0 and completions unset -> no change - { - original: &Job{ - Spec: JobSpec{ - Parallelism: newInt32(0), - }, - }, - expected: &Job{ - Spec: JobSpec{ - Parallelism: newInt32(0), - }, - }, - }, - // WQ: Parallelism explicitly 2 and completions unset -> no change - { - original: &Job{ - Spec: JobSpec{ - Parallelism: newInt32(2), - }, - }, - expected: &Job{ - Spec: JobSpec{ - Parallelism: newInt32(2), - }, - }, - }, - // Completions explicitly 2 and parallelism unset -> parallelism is defaulted - { - original: &Job{ - Spec: JobSpec{ - Completions: newInt32(2), - }, - }, - expected: &Job{ - Spec: JobSpec{ - Completions: newInt32(2), - Parallelism: newInt32(1), - }, - }, - }, - // Both set -> no change - { - original: &Job{ - Spec: JobSpec{ - Completions: newInt32(10), - Parallelism: newInt32(11), - }, - }, - expected: &Job{ - Spec: JobSpec{ - Completions: newInt32(10), - Parallelism: newInt32(11), - }, - }, - }, - // Both set, flipped -> no change - { - original: &Job{ - Spec: JobSpec{ - Completions: newInt32(11), - Parallelism: newInt32(10), - }, - }, - expected: &Job{ - Spec: JobSpec{ - Completions: newInt32(11), - Parallelism: newInt32(10), - }, - }, - }, - } - - for _, tc := range tests { - original := tc.original - expected := tc.expected - obj2 := roundTrip(t, runtime.Object(original)) - got, ok := obj2.(*Job) - if !ok { - t.Errorf("unexpected object: %v", got) - t.FailNow() - } - if (got.Spec.Completions == nil) != (expected.Spec.Completions == nil) { - t.Errorf("got different *completions than expected: %v %v", got.Spec.Completions, expected.Spec.Completions) - } - if got.Spec.Completions != nil && expected.Spec.Completions != nil { - if *got.Spec.Completions != *expected.Spec.Completions { - t.Errorf("got different completions than expected: %d %d", *got.Spec.Completions, *expected.Spec.Completions) - } - } - if (got.Spec.Parallelism == nil) != (expected.Spec.Parallelism == nil) { - t.Errorf("got different *Parallelism than expected: %v %v", got.Spec.Parallelism, expected.Spec.Parallelism) - } - if got.Spec.Parallelism != nil && expected.Spec.Parallelism != nil { - if *got.Spec.Parallelism != *expected.Spec.Parallelism { - t.Errorf("got different parallelism than expected: %d %d", *got.Spec.Parallelism, *expected.Spec.Parallelism) - } - } - } -} - -func TestSetDefaultJobSelector(t *testing.T) { - expected := &Job{ - Spec: JobSpec{ - Selector: &LabelSelector{ - MatchLabels: map[string]string{"job": "selector"}, - }, - Completions: newInt32(1), - Parallelism: newInt32(1), - }, - } - tests := []*Job{ - // selector set explicitly, completions and parallelism - default - { - Spec: JobSpec{ - Selector: &LabelSelector{ - MatchLabels: map[string]string{"job": "selector"}, - }, - }, - }, - // selector from template labels, completions and parallelism - default - { - Spec: JobSpec{ - Template: v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{"job": "selector"}, - }, - }, - }, - }, - } - - for _, original := range tests { - obj2 := roundTrip(t, runtime.Object(original)) - got, ok := obj2.(*Job) - if !ok { - t.Errorf("unexpected object: %v", got) - t.FailNow() - } - if !reflect.DeepEqual(got.Spec.Selector, expected.Spec.Selector) { - t.Errorf("got different selectors %#v %#v", got.Spec.Selector, expected.Spec.Selector) - } - } -} - -func TestSetDefaultReplicaSet(t *testing.T) { - tests := []struct { - rs *ReplicaSet - expectLabels bool - expectSelector bool - }{ - { - rs: &ReplicaSet{ - Spec: ReplicaSetSpec{ - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: true, - expectSelector: true, - }, - { - rs: &ReplicaSet{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: ReplicaSetSpec{ - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: false, - expectSelector: true, - }, - { - rs: &ReplicaSet{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: ReplicaSetSpec{ - Selector: &LabelSelector{ - MatchLabels: map[string]string{ - "some": "other", - }, - }, - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: false, - expectSelector: false, - }, - { - rs: &ReplicaSet{ - Spec: ReplicaSetSpec{ - Selector: &LabelSelector{ - MatchLabels: map[string]string{ - "some": "other", - }, - }, - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: true, - expectSelector: false, - }, - } - - for _, test := range tests { - rs := test.rs - obj2 := roundTrip(t, runtime.Object(rs)) - rs2, ok := obj2.(*ReplicaSet) - if !ok { - t.Errorf("unexpected object: %v", rs2) - t.FailNow() - } - if test.expectSelector != reflect.DeepEqual(rs2.Spec.Selector.MatchLabels, rs2.Spec.Template.Labels) { - if test.expectSelector { - t.Errorf("expected: %v, got: %v", rs2.Spec.Template.Labels, rs2.Spec.Selector) - } else { - t.Errorf("unexpected equality: %v", rs.Spec.Selector) - } - } - if test.expectLabels != reflect.DeepEqual(rs2.Labels, rs2.Spec.Template.Labels) { - if test.expectLabels { - t.Errorf("expected: %v, got: %v", rs2.Spec.Template.Labels, rs2.Labels) - } else { - t.Errorf("unexpected equality: %v", rs.Labels) - } - } - } -} - -func TestSetDefaultReplicaSetReplicas(t *testing.T) { - tests := []struct { - rs ReplicaSet - expectReplicas int32 - }{ - { - rs: ReplicaSet{ - Spec: ReplicaSetSpec{ - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 1, - }, - { - rs: ReplicaSet{ - Spec: ReplicaSetSpec{ - Replicas: newInt32(0), - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 0, - }, - { - rs: ReplicaSet{ - Spec: ReplicaSetSpec{ - Replicas: newInt32(3), - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 3, - }, - } - - for _, test := range tests { - rs := &test.rs - obj2 := roundTrip(t, runtime.Object(rs)) - rs2, ok := obj2.(*ReplicaSet) - if !ok { - t.Errorf("unexpected object: %v", rs2) - t.FailNow() - } - if rs2.Spec.Replicas == nil { - t.Errorf("unexpected nil Replicas") - } else if test.expectReplicas != *rs2.Spec.Replicas { - t.Errorf("expected: %d replicas, got: %d", test.expectReplicas, *rs2.Spec.Replicas) - } - } -} - -func TestDefaultRequestIsNotSetForReplicaSet(t *testing.T) { - s := v1.PodSpec{} - s.Containers = []v1.Container{ - { - Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("100m"), - }, - }, - }, - } - rs := &ReplicaSet{ - Spec: ReplicaSetSpec{ - Replicas: newInt32(3), - Template: &v1.PodTemplateSpec{ - ObjectMeta: v1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - Spec: s, - }, - }, - } - output := roundTrip(t, runtime.Object(rs)) - rs2 := output.(*ReplicaSet) - defaultRequest := rs2.Spec.Template.Spec.Containers[0].Resources.Requests - requestValue := defaultRequest[v1.ResourceCPU] - if requestValue.String() != "0" { - t.Errorf("Expected 0 request value, got: %s", requestValue.String()) - } -} - -func roundTrip(t *testing.T, obj runtime.Object) runtime.Object { - data, err := runtime.Encode(api.Codecs.LegacyCodec(SchemeGroupVersion), obj) - if err != nil { - t.Errorf("%v\n %#v", err, obj) - return nil - } - obj2, err := runtime.Decode(api.Codecs.UniversalDecoder(), data) - if err != nil { - t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), obj) - return nil - } - obj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object) - err = api.Scheme.Convert(obj2, obj3) - if err != nil { - t.Errorf("%v\nSource: %#v", err, obj2) - return nil - } - return obj3 -} - -func newInt32(val int32) *int32 { - p := new(int32) - *p = val - return p -} - -func newString(val string) *string { - p := new(string) - *p = val - return p -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go index d2750a639..026a9f681 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go @@ -37,8 +37,6 @@ func AddToScheme(scheme *runtime.Scheme) { // Adds the list of known types to api.Scheme. func addKnownTypes(scheme *runtime.Scheme) { scheme.AddKnownTypes(SchemeGroupVersion, - &ClusterAutoscaler{}, - &ClusterAutoscalerList{}, &Deployment{}, &DeploymentList{}, &DeploymentRollback{}, @@ -65,8 +63,6 @@ func addKnownTypes(scheme *runtime.Scheme) { ) } -func (obj *ClusterAutoscaler) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ClusterAutoscalerList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *Deployment) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *DeploymentList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } func (obj *DeploymentRollback) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go index 1e2b081ec..ffdeebcf5 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go @@ -260,13 +260,14 @@ func (x *ScaleStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [2]bool + var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[1] = len(x.Selector) != 0 + yyq2[2] = x.TargetSelector != "" var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(2) + r.EncodeArrayStart(3) } else { yynn2 = 1 for _, b := range yyq2 { @@ -329,6 +330,31 @@ func (x *ScaleStatus) CodecEncodeSelf(e *codec1978.Encoder) { } } } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.TargetSelector)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("targetSelector")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.TargetSelector)) + } + } + } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { @@ -408,6 +434,12 @@ func (x *ScaleStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { z.F.DecMapStringStringX(yyv5, false, d) } } + case "targetSelector": + if r.TryDecodeAsNil() { + x.TargetSelector = "" + } else { + x.TargetSelector = string(r.DecodeString()) + } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 @@ -419,16 +451,16 @@ func (x *ScaleStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj7 int - var yyb7 bool - var yyhl7 bool = l >= 0 - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l + var yyj8 int + var yyb8 bool + var yyhl8 bool = l >= 0 + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l } else { - yyb7 = r.CheckBreak() + yyb8 = r.CheckBreak() } - if yyb7 { + if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -438,13 +470,13 @@ func (x *ScaleStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } else { x.Replicas = int32(r.DecodeInt(32)) } - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l } else { - yyb7 = r.CheckBreak() + yyb8 = r.CheckBreak() } - if yyb7 { + if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -452,26 +484,42 @@ func (x *ScaleStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if r.TryDecodeAsNil() { x.Selector = nil } else { - yyv9 := &x.Selector - yym10 := z.DecBinary() - _ = yym10 + yyv10 := &x.Selector + yym11 := z.DecBinary() + _ = yym11 if false { } else { - z.F.DecMapStringStringX(yyv9, false, d) + z.F.DecMapStringStringX(yyv10, false, 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.TargetSelector = "" + } else { + x.TargetSelector = string(r.DecodeString()) + } for { - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l } else { - yyb7 = r.CheckBreak() + yyb8 = r.CheckBreak() } - if yyb7 { + if yyb8 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj7-1, "") + z.DecStructFieldNotFound(yyj8-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -7056,16 +7104,17 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [4]bool + var yyq2 [5]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[0] = x.Replicas != 0 - yyq2[1] = x.UpdatedReplicas != 0 - yyq2[2] = x.AvailableReplicas != 0 - yyq2[3] = x.UnavailableReplicas != 0 + yyq2[0] = x.ObservedGeneration != 0 + yyq2[1] = x.Replicas != 0 + yyq2[2] = x.UpdatedReplicas != 0 + yyq2[3] = x.AvailableReplicas != 0 + yyq2[4] = x.UnavailableReplicas != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(4) + r.EncodeArrayStart(5) } else { yynn2 = 0 for _, b := range yyq2 { @@ -7083,7 +7132,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym4 if false { } else { - r.EncodeInt(int64(x.Replicas)) + r.EncodeInt(int64(x.ObservedGeneration)) } } else { r.EncodeInt(0) @@ -7091,13 +7140,13 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[0] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("replicas")) + r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym5 := z.EncBinary() _ = yym5 if false { } else { - r.EncodeInt(int64(x.Replicas)) + r.EncodeInt(int64(x.ObservedGeneration)) } } } @@ -7108,7 +7157,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym7 if false { } else { - r.EncodeInt(int64(x.UpdatedReplicas)) + r.EncodeInt(int64(x.Replicas)) } } else { r.EncodeInt(0) @@ -7116,13 +7165,13 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("updatedReplicas")) + r.EncodeString(codecSelferC_UTF81234, string("replicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { } else { - r.EncodeInt(int64(x.UpdatedReplicas)) + r.EncodeInt(int64(x.Replicas)) } } } @@ -7133,7 +7182,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym10 if false { } else { - r.EncodeInt(int64(x.AvailableReplicas)) + r.EncodeInt(int64(x.UpdatedReplicas)) } } else { r.EncodeInt(0) @@ -7141,13 +7190,13 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("availableReplicas")) + r.EncodeString(codecSelferC_UTF81234, string("updatedReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym11 := z.EncBinary() _ = yym11 if false { } else { - r.EncodeInt(int64(x.AvailableReplicas)) + r.EncodeInt(int64(x.UpdatedReplicas)) } } } @@ -7158,7 +7207,7 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym13 if false { } else { - r.EncodeInt(int64(x.UnavailableReplicas)) + r.EncodeInt(int64(x.AvailableReplicas)) } } else { r.EncodeInt(0) @@ -7166,11 +7215,36 @@ func (x *DeploymentStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[3] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("unavailableReplicas")) + r.EncodeString(codecSelferC_UTF81234, string("availableReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym14 := z.EncBinary() _ = yym14 if false { + } else { + r.EncodeInt(int64(x.AvailableReplicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeInt(int64(x.UnavailableReplicas)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("unavailableReplicas")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym17 := z.EncBinary() + _ = yym17 + if false { } else { r.EncodeInt(int64(x.UnavailableReplicas)) } @@ -7237,6 +7311,12 @@ func (x *DeploymentStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { + case "observedGeneration": + if r.TryDecodeAsNil() { + x.ObservedGeneration = 0 + } else { + x.ObservedGeneration = int64(r.DecodeInt(64)) + } case "replicas": if r.TryDecodeAsNil() { x.Replicas = 0 @@ -7272,16 +7352,32 @@ func (x *DeploymentStatus) 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 + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ObservedGeneration = 0 + } else { + x.ObservedGeneration = int64(r.DecodeInt(64)) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7291,13 +7387,13 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.Replicas = int32(r.DecodeInt(32)) } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7307,13 +7403,13 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.UpdatedReplicas = int32(r.DecodeInt(32)) } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7323,13 +7419,13 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.AvailableReplicas = int32(r.DecodeInt(32)) } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -7340,17 +7436,17 @@ func (x *DeploymentStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) x.UnavailableReplicas = int32(r.DecodeInt(32)) } for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l } else { - yyb8 = r.CheckBreak() + yyb9 = r.CheckBreak() } - if yyb8 { + if yyb9 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj8-1, "") + z.DecStructFieldNotFound(yyj9-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -9887,16 +9983,17 @@ func (x *JobSpec) 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] = x.Parallelism != nil yyq2[1] = x.Completions != nil yyq2[2] = x.ActiveDeadlineSeconds != nil yyq2[3] = x.Selector != nil + yyq2[4] = x.AutoSelector != nil var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(5) + r.EncodeArrayStart(6) } else { yynn2 = 1 for _, b := range yyq2 { @@ -10037,14 +10134,49 @@ func (x *JobSpec) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy22 := &x.Template - yy22.CodecEncodeSelf(e) + if yyq2[4] { + if x.AutoSelector == nil { + r.EncodeNil() + } else { + yy22 := *x.AutoSelector + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeBool(bool(yy22)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("autoSelector")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.AutoSelector == nil { + r.EncodeNil() + } else { + yy24 := *x.AutoSelector + yym25 := z.EncBinary() + _ = yym25 + if false { + } else { + r.EncodeBool(bool(yy24)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy27 := &x.Template + yy27.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("template")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy24 := &x.Template - yy24.CodecEncodeSelf(e) + yy29 := &x.Template + yy29.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) @@ -10166,12 +10298,28 @@ func (x *JobSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { } x.Selector.CodecDecodeSelf(d) } + case "autoSelector": + if r.TryDecodeAsNil() { + if x.AutoSelector != nil { + x.AutoSelector = nil + } + } else { + if x.AutoSelector == nil { + x.AutoSelector = new(bool) + } + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *((*bool)(x.AutoSelector)) = r.DecodeBool() + } + } case "template": if r.TryDecodeAsNil() { x.Template = pkg2_v1.PodTemplateSpec{} } else { - yyv11 := &x.Template - yyv11.CodecDecodeSelf(d) + yyv13 := &x.Template + yyv13.CodecDecodeSelf(d) } default: z.DecStructFieldNotFound(-1, yys3) @@ -10184,16 +10332,16 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj12 int - var yyb12 bool - var yyhl12 bool = l >= 0 - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l + var yyj14 int + var yyb14 bool + var yyhl14 bool = l >= 0 + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l } else { - yyb12 = r.CheckBreak() + yyb14 = r.CheckBreak() } - if yyb12 { + if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10206,20 +10354,20 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.Parallelism == nil { x.Parallelism = new(int32) } - yym14 := z.DecBinary() - _ = yym14 + yym16 := z.DecBinary() + _ = yym16 if false { } else { *((*int32)(x.Parallelism)) = int32(r.DecodeInt(32)) } } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l } else { - yyb12 = r.CheckBreak() + yyb14 = r.CheckBreak() } - if yyb12 { + if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10232,20 +10380,20 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.Completions == nil { x.Completions = new(int32) } - yym16 := z.DecBinary() - _ = yym16 + yym18 := z.DecBinary() + _ = yym18 if false { } else { *((*int32)(x.Completions)) = int32(r.DecodeInt(32)) } } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l } else { - yyb12 = r.CheckBreak() + yyb14 = r.CheckBreak() } - if yyb12 { + if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10258,20 +10406,20 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if x.ActiveDeadlineSeconds == nil { x.ActiveDeadlineSeconds = new(int64) } - yym18 := z.DecBinary() - _ = yym18 + yym20 := z.DecBinary() + _ = yym20 if false { } else { *((*int64)(x.ActiveDeadlineSeconds)) = int64(r.DecodeInt(64)) } } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l } else { - yyb12 = r.CheckBreak() + yyb14 = r.CheckBreak() } - if yyb12 { + if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10286,13 +10434,39 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } x.Selector.CodecDecodeSelf(d) } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l } else { - yyb12 = r.CheckBreak() + yyb14 = r.CheckBreak() } - if yyb12 { + if yyb14 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.AutoSelector != nil { + x.AutoSelector = nil + } + } else { + if x.AutoSelector == nil { + x.AutoSelector = new(bool) + } + yym23 := z.DecBinary() + _ = yym23 + if false { + } else { + *((*bool)(x.AutoSelector)) = r.DecodeBool() + } + } + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l + } else { + yyb14 = r.CheckBreak() + } + if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -10300,21 +10474,21 @@ func (x *JobSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if r.TryDecodeAsNil() { x.Template = pkg2_v1.PodTemplateSpec{} } else { - yyv20 := &x.Template - yyv20.CodecDecodeSelf(d) + yyv24 := &x.Template + yyv24.CodecDecodeSelf(d) } for { - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l + yyj14++ + if yyhl14 { + yyb14 = yyj14 > l } else { - yyb12 = r.CheckBreak() + yyb14 = r.CheckBreak() } - if yyb12 { + if yyb14 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj12-1, "") + z.DecStructFieldNotFound(yyj14-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -13752,1134 +13926,6 @@ func (x *IngressBackend) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } -func (x NodeResource) 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 *NodeResource) 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 *NodeUtilization) 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 - var yynn2 int - if yyr2 || yy2arr2 { - r.EncodeArrayStart(2) - } else { - yynn2 = 2 - for _, b := range yyq2 { - if b { - yynn2++ - } - } - r.EncodeMapStart(yynn2) - yynn2 = 0 - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - x.Resource.CodecEncodeSelf(e) - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("resource")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - x.Resource.CodecEncodeSelf(e) - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym7 := z.EncBinary() - _ = yym7 - if false { - } else { - r.EncodeFloat64(float64(x.Value)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("value")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym8 := z.EncBinary() - _ = yym8 - if false { - } else { - r.EncodeFloat64(float64(x.Value)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayEnd1234) - } else { - z.EncSendContainerState(codecSelfer_containerMapEnd1234) - } - } - } -} - -func (x *NodeUtilization) 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 *NodeUtilization) 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 "resource": - if r.TryDecodeAsNil() { - x.Resource = "" - } else { - x.Resource = NodeResource(r.DecodeString()) - } - case "value": - if r.TryDecodeAsNil() { - x.Value = 0 - } else { - x.Value = float64(r.DecodeFloat(false)) - } - default: - z.DecStructFieldNotFound(-1, yys3) - } // end switch yys3 - } // end for yyj3 - z.DecSendContainerState(codecSelfer_containerMapEnd1234) -} - -func (x *NodeUtilization) 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.Resource = "" - } else { - x.Resource = NodeResource(r.DecodeString()) - } - 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.Value = 0 - } else { - x.Value = float64(r.DecodeFloat(false)) - } - 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 *ClusterAutoscalerSpec) 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 [3]bool - _, _, _ = yysep2, yyq2, yy2arr2 - const yyr2 bool = false - var yynn2 int - if yyr2 || yy2arr2 { - r.EncodeArrayStart(3) - } else { - yynn2 = 3 - for _, b := range yyq2 { - if b { - yynn2++ - } - } - r.EncodeMapStart(yynn2) - yynn2 = 0 - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym4 := z.EncBinary() - _ = yym4 - if false { - } else { - r.EncodeInt(int64(x.MinNodes)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("minNodes")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym5 := z.EncBinary() - _ = yym5 - if false { - } else { - r.EncodeInt(int64(x.MinNodes)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym7 := z.EncBinary() - _ = yym7 - if false { - } else { - r.EncodeInt(int64(x.MaxNodes)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("maxNodes")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym8 := z.EncBinary() - _ = yym8 - if false { - } else { - r.EncodeInt(int64(x.MaxNodes)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if x.TargetUtilization == nil { - r.EncodeNil() - } else { - yym10 := z.EncBinary() - _ = yym10 - if false { - } else { - h.encSliceNodeUtilization(([]NodeUtilization)(x.TargetUtilization), e) - } - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("target")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - if x.TargetUtilization == nil { - r.EncodeNil() - } else { - yym11 := z.EncBinary() - _ = yym11 - if false { - } else { - h.encSliceNodeUtilization(([]NodeUtilization)(x.TargetUtilization), e) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayEnd1234) - } else { - z.EncSendContainerState(codecSelfer_containerMapEnd1234) - } - } - } -} - -func (x *ClusterAutoscalerSpec) 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 *ClusterAutoscalerSpec) 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 "minNodes": - if r.TryDecodeAsNil() { - x.MinNodes = 0 - } else { - x.MinNodes = int32(r.DecodeInt(32)) - } - case "maxNodes": - if r.TryDecodeAsNil() { - x.MaxNodes = 0 - } else { - x.MaxNodes = int32(r.DecodeInt(32)) - } - case "target": - if r.TryDecodeAsNil() { - x.TargetUtilization = nil - } else { - yyv6 := &x.TargetUtilization - yym7 := z.DecBinary() - _ = yym7 - if false { - } else { - h.decSliceNodeUtilization((*[]NodeUtilization)(yyv6), d) - } - } - default: - z.DecStructFieldNotFound(-1, yys3) - } // end switch yys3 - } // end for yyj3 - z.DecSendContainerState(codecSelfer_containerMapEnd1234) -} - -func (x *ClusterAutoscalerSpec) 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.MinNodes = 0 - } else { - x.MinNodes = int32(r.DecodeInt(32)) - } - 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.MaxNodes = 0 - } else { - x.MaxNodes = int32(r.DecodeInt(32)) - } - 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.TargetUtilization = nil - } else { - yyv11 := &x.TargetUtilization - yym12 := z.DecBinary() - _ = yym12 - if false { - } else { - h.decSliceNodeUtilization((*[]NodeUtilization)(yyv11), d) - } - } - 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 *ClusterAutoscaler) 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] = true - 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.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] { - yym14 := z.EncBinary() - _ = yym14 - 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) - yym15 := z.EncBinary() - _ = yym15 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[3] { - yym17 := z.EncBinary() - _ = yym17 - 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) - yym18 := z.EncBinary() - _ = yym18 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayEnd1234) - } else { - z.EncSendContainerState(codecSelfer_containerMapEnd1234) - } - } - } -} - -func (x *ClusterAutoscaler) 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 *ClusterAutoscaler) 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 = ClusterAutoscalerSpec{} - } else { - yyv5 := &x.Spec - yyv5.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 *ClusterAutoscaler) 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.ObjectMeta = pkg2_v1.ObjectMeta{} - } else { - yyv9 := &x.ObjectMeta - yyv9.CodecDecodeSelf(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.Spec = ClusterAutoscalerSpec{} - } else { - yyv10 := &x.Spec - yyv10.CodecDecodeSelf(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.Kind = "" - } else { - x.Kind = string(r.DecodeString()) - } - 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.APIVersion = "" - } else { - x.APIVersion = string(r.DecodeString()) - } - 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 *ClusterAutoscalerList) 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.encSliceClusterAutoscaler(([]ClusterAutoscaler)(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.encSliceClusterAutoscaler(([]ClusterAutoscaler)(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 *ClusterAutoscalerList) 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 *ClusterAutoscalerList) 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.decSliceClusterAutoscaler((*[]ClusterAutoscaler)(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 *ClusterAutoscalerList) 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.decSliceClusterAutoscaler((*[]ClusterAutoscaler)(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 *ExportOptions) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -16916,7 +15962,7 @@ func (x *ReplicaSetSpec) CodecEncodeSelf(e *codec1978.Encoder) { const yyr2 bool = false yyq2[0] = x.Replicas != nil yyq2[1] = x.Selector != nil - yyq2[2] = x.Template != nil + yyq2[2] = true var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(3) @@ -16991,11 +16037,8 @@ func (x *ReplicaSetSpec) CodecEncodeSelf(e *codec1978.Encoder) { if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { - if x.Template == nil { - r.EncodeNil() - } else { - x.Template.CodecEncodeSelf(e) - } + yy12 := &x.Template + yy12.CodecEncodeSelf(e) } else { r.EncodeNil() } @@ -17004,11 +16047,8 @@ func (x *ReplicaSetSpec) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("template")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - if x.Template == nil { - r.EncodeNil() - } else { - x.Template.CodecEncodeSelf(e) - } + yy14 := &x.Template + yy14.CodecEncodeSelf(e) } } if yyr2 || yy2arr2 { @@ -17101,14 +16141,10 @@ func (x *ReplicaSetSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { } case "template": if r.TryDecodeAsNil() { - if x.Template != nil { - x.Template = nil - } + x.Template = pkg2_v1.PodTemplateSpec{} } else { - if x.Template == nil { - x.Template = new(pkg2_v1.PodTemplateSpec) - } - x.Template.CodecDecodeSelf(d) + yyv7 := &x.Template + yyv7.CodecDecodeSelf(d) } default: z.DecStructFieldNotFound(-1, yys3) @@ -17183,14 +16219,10 @@ func (x *ReplicaSetSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - if x.Template != nil { - x.Template = nil - } + x.Template = pkg2_v1.PodTemplateSpec{} } else { - if x.Template == nil { - x.Template = new(pkg2_v1.PodTemplateSpec) - } - x.Template.CodecDecodeSelf(d) + yyv12 := &x.Template + yyv12.CodecDecodeSelf(d) } for { yyj8++ @@ -17222,13 +16254,14 @@ func (x *ReplicaSetStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [2]bool + var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[1] = x.ObservedGeneration != 0 + yyq2[1] = x.FullyLabeledReplicas != 0 + yyq2[2] = x.ObservedGeneration != 0 var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(2) + r.EncodeArrayStart(3) } else { yynn2 = 1 for _, b := range yyq2 { @@ -17265,7 +16298,7 @@ func (x *ReplicaSetStatus) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym7 if false { } else { - r.EncodeInt(int64(x.ObservedGeneration)) + r.EncodeInt(int64(x.FullyLabeledReplicas)) } } else { r.EncodeInt(0) @@ -17273,11 +16306,36 @@ func (x *ReplicaSetStatus) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + r.EncodeString(codecSelferC_UTF81234, string("fullyLabeledReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { + } else { + r.EncodeInt(int64(x.FullyLabeledReplicas)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeInt(int64(x.ObservedGeneration)) + } + } else { + r.EncodeInt(0) + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { } else { r.EncodeInt(int64(x.ObservedGeneration)) } @@ -17350,6 +16408,12 @@ func (x *ReplicaSetStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { } else { x.Replicas = int32(r.DecodeInt(32)) } + case "fullyLabeledReplicas": + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int32(r.DecodeInt(32)) + } case "observedGeneration": if r.TryDecodeAsNil() { x.ObservedGeneration = 0 @@ -17367,16 +16431,16 @@ func (x *ReplicaSetStatus) 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 + var yyj7 int + var yyb7 bool + var yyhl7 bool = l >= 0 + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -17386,13 +16450,29 @@ func (x *ReplicaSetStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) } else { x.Replicas = int32(r.DecodeInt(32)) } - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.FullyLabeledReplicas = 0 + } else { + x.FullyLabeledReplicas = int32(r.DecodeInt(32)) + } + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l + } else { + yyb7 = r.CheckBreak() + } + if yyb7 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -17403,17 +16483,17 @@ func (x *ReplicaSetStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) x.ObservedGeneration = int64(r.DecodeInt(64)) } for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l + yyj7++ + if yyhl7 { + yyb7 = yyj7 > l } else { - yyb6 = r.CheckBreak() + yyb7 = r.CheckBreak() } - if yyb6 { + if yyb7 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj6-1, "") + z.DecStructFieldNotFound(yyj7-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -17960,7 +17040,7 @@ func (x *PodSecurityPolicySpec) CodecEncodeSelf(e *codec1978.Encoder) { if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[7] { - yy25 := &x.SELinuxContext + yy25 := &x.SELinux yy25.CodecEncodeSelf(e) } else { r.EncodeNil() @@ -17968,9 +17048,9 @@ func (x *PodSecurityPolicySpec) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[7] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("seLinuxContext")) + r.EncodeString(codecSelferC_UTF81234, string("seLinux")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy27 := &x.SELinuxContext + yy27 := &x.SELinux yy27.CodecEncodeSelf(e) } } @@ -18112,11 +17192,11 @@ func (x *PodSecurityPolicySpec) codecDecodeSelfFromMap(l int, d *codec1978.Decod } else { x.HostIPC = bool(r.DecodeBool()) } - case "seLinuxContext": + case "seLinux": if r.TryDecodeAsNil() { - x.SELinuxContext = SELinuxContextStrategyOptions{} + x.SELinux = SELinuxStrategyOptions{} } else { - yyv14 := &x.SELinuxContext + yyv14 := &x.SELinux yyv14.CodecDecodeSelf(d) } case "runAsUser": @@ -18282,9 +17362,9 @@ func (x *PodSecurityPolicySpec) codecDecodeSelfFromArray(l int, d *codec1978.Dec } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.SELinuxContext = SELinuxContextStrategyOptions{} + x.SELinux = SELinuxStrategyOptions{} } else { - yyv27 := &x.SELinuxContext + yyv27 := &x.SELinux yyv27.CodecDecodeSelf(d) } yyj16++ @@ -18549,7 +17629,7 @@ func (x *HostPortRange) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } -func (x *SELinuxContextStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { +func (x *SELinuxStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r @@ -18582,12 +17662,12 @@ func (x *SELinuxContextStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("type")) + r.EncodeString(codecSelferC_UTF81234, string("rule")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) @@ -18621,7 +17701,7 @@ func (x *SELinuxContextStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { } } -func (x *SELinuxContextStrategyOptions) CodecDecodeSelf(d *codec1978.Decoder) { +func (x *SELinuxStrategyOptions) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -18651,7 +17731,7 @@ func (x *SELinuxContextStrategyOptions) CodecDecodeSelf(d *codec1978.Decoder) { } } -func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { +func (x *SELinuxStrategyOptions) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -18673,11 +17753,11 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromMap(l int, d *codec19 yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { - case "type": + case "rule": if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = SELinuxContextStrategy(r.DecodeString()) + x.Rule = SELinuxStrategy(r.DecodeString()) } case "seLinuxOptions": if r.TryDecodeAsNil() { @@ -18697,7 +17777,7 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromMap(l int, d *codec19 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } -func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { +func (x *SELinuxStrategyOptions) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -18716,9 +17796,9 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromArray(l int, d *codec } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = SELinuxContextStrategy(r.DecodeString()) + x.Rule = SELinuxStrategy(r.DecodeString()) } yyj6++ if yyhl6 { @@ -18757,7 +17837,7 @@ func (x *SELinuxContextStrategyOptions) codecDecodeSelfFromArray(l int, d *codec z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } -func (x SELinuxContextStrategy) CodecEncodeSelf(e *codec1978.Encoder) { +func (x SELinuxStrategy) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r @@ -18770,7 +17850,7 @@ func (x SELinuxContextStrategy) CodecEncodeSelf(e *codec1978.Encoder) { } } -func (x *SELinuxContextStrategy) CodecDecodeSelf(d *codec1978.Decoder) { +func (x *SELinuxStrategy) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r @@ -18816,12 +17896,12 @@ func (x *RunAsUserStrategyOptions) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("type")) + r.EncodeString(codecSelferC_UTF81234, string("rule")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - x.Type.CodecEncodeSelf(e) + x.Rule.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) @@ -18917,11 +17997,11 @@ func (x *RunAsUserStrategyOptions) codecDecodeSelfFromMap(l int, d *codec1978.De yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { - case "type": + case "rule": if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = RunAsUserStrategy(r.DecodeString()) + x.Rule = RunAsUserStrategy(r.DecodeString()) } case "ranges": if r.TryDecodeAsNil() { @@ -18961,9 +18041,9 @@ func (x *RunAsUserStrategyOptions) codecDecodeSelfFromArray(l int, d *codec1978. } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.Type = "" + x.Rule = "" } else { - x.Type = RunAsUserStrategy(r.DecodeString()) + x.Rule = RunAsUserStrategy(r.DecodeString()) } yyj7++ if yyhl7 { @@ -20210,7 +19290,7 @@ func (x codecSelfer1234) decSliceDeployment(v *[]Deployment, d *codec1978.Decode yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 632) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 640) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] @@ -20567,7 +19647,7 @@ func (x codecSelfer1234) decSliceJob(v *[]Job, d *codec1978.Decoder) { yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 632) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 640) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] @@ -21242,244 +20322,6 @@ func (x codecSelfer1234) decSliceHTTPIngressPath(v *[]HTTPIngressPath, d *codec1 } } -func (x codecSelfer1234) encSliceNodeUtilization(v []NodeUtilization, 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) decSliceNodeUtilization(v *[]NodeUtilization, 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 = []NodeUtilization{} - 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, 24) - if yyrt1 { - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]NodeUtilization, yyrl1) - } - } else { - yyv1 = make([]NodeUtilization, 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] = NodeUtilization{} - } else { - yyv2 := &yyv1[yyj1] - yyv2.CodecDecodeSelf(d) - } - - } - if yyrt1 { - for ; yyj1 < yyl1; yyj1++ { - yyv1 = append(yyv1, NodeUtilization{}) - yyh1.ElemContainerState(yyj1) - if r.TryDecodeAsNil() { - yyv1[yyj1] = NodeUtilization{} - } else { - yyv3 := &yyv1[yyj1] - yyv3.CodecDecodeSelf(d) - } - - } - } - - } else { - yyj1 := 0 - for ; !r.CheckBreak(); yyj1++ { - - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, NodeUtilization{}) // var yyz1 NodeUtilization - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - if yyj1 < len(yyv1) { - if r.TryDecodeAsNil() { - yyv1[yyj1] = NodeUtilization{} - } 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 = []NodeUtilization{} - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer1234) encSliceClusterAutoscaler(v []ClusterAutoscaler, 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) decSliceClusterAutoscaler(v *[]ClusterAutoscaler, 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 = []ClusterAutoscaler{} - 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, 224) - if yyrt1 { - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]ClusterAutoscaler, yyrl1) - } - } else { - yyv1 = make([]ClusterAutoscaler, 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] = ClusterAutoscaler{} - } else { - yyv2 := &yyv1[yyj1] - yyv2.CodecDecodeSelf(d) - } - - } - if yyrt1 { - for ; yyj1 < yyl1; yyj1++ { - yyv1 = append(yyv1, ClusterAutoscaler{}) - yyh1.ElemContainerState(yyj1) - if r.TryDecodeAsNil() { - yyv1[yyj1] = ClusterAutoscaler{} - } else { - yyv3 := &yyv1[yyj1] - yyv3.CodecDecodeSelf(d) - } - - } - } - - } else { - yyj1 := 0 - for ; !r.CheckBreak(); yyj1++ { - - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, ClusterAutoscaler{}) // var yyz1 ClusterAutoscaler - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - if yyj1 < len(yyv1) { - if r.TryDecodeAsNil() { - yyv1[yyj1] = ClusterAutoscaler{} - } 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 = []ClusterAutoscaler{} - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - func (x codecSelfer1234) encSliceLabelSelectorRequirement(v []LabelSelectorRequirement, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -21638,7 +20480,7 @@ func (x codecSelfer1234) decSliceReplicaSet(v *[]ReplicaSet, d *codec1978.Decode yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 232) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 576) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go index 4de157e3c..1a67438b8 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go @@ -34,8 +34,16 @@ type ScaleStatus struct { // actual number of observed instances of the scaled object. Replicas int32 `json:"replicas"` - // label query over pods that should match the replicas count. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors + // label query over pods that should match the replicas count. More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors Selector map[string]string `json:"selector,omitempty"` + + // 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.2/docs/user-guide/labels.md#label-selectors + TargetSelector string `json:"targetSelector,omitempty"` } // +genclient=true,noMethods=true @@ -43,13 +51,13 @@ type ScaleStatus struct { // represents a scaling request for a resource. type Scale struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata. v1.ObjectMeta `json:"metadata,omitempty"` - // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Spec ScaleSpec `json:"spec,omitempty"` - // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Read-only. Status ScaleStatus `json:"status,omitempty"` } @@ -60,9 +68,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/HEAD/docs/devel/api-conventions.md#types-kinds" + // Kind of the referent; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds" Kind string `json:"kind,omitempty"` - // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names Name string `json:"name,omitempty"` // API version of the referent APIVersion string `json:"apiVersion,omitempty"` @@ -138,10 +146,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/HEAD/docs/devel/api-conventions.md#metadata + // Standard object metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty"` - // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Spec HorizontalPodAutoscalerSpec `json:"spec,omitempty"` // current information about the autoscaler. @@ -328,6 +336,9 @@ type RollingUpdateDeployment struct { // DeploymentStatus is the most recently observed status of the Deployment. type DeploymentStatus struct { + // The generation observed by the deployment controller. + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + // Total number of non-terminated pods targeted by this deployment (their labels match the selector). Replicas int32 `json:"replicas,omitempty"` @@ -402,14 +413,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/HEAD/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors Selector *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/HEAD/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#pod-template Template v1.PodTemplateSpec `json:"template"` // TODO(madhusudancs): Uncomment while implementing DaemonSet updates. @@ -439,17 +450,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/HEAD/docs/admin/daemon.md + // More info: http://releases.k8s.io/release-1.2/docs/admin/daemons.md CurrentNumberScheduled int32 `json:"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/HEAD/docs/admin/daemon.md + // More info: http://releases.k8s.io/release-1.2/docs/admin/daemons.md NumberMisscheduled int32 `json:"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/HEAD/docs/admin/daemon.md + // More info: http://releases.k8s.io/release-1.2/docs/admin/daemons.md DesiredNumberScheduled int32 `json:"desiredNumberScheduled"` } @@ -459,18 +470,18 @@ type DaemonSetStatus struct { type DaemonSet struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty"` // Spec defines the desired behavior of this daemon set. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status DaemonSetStatus `json:"status,omitempty"` } @@ -478,7 +489,7 @@ type DaemonSet struct { type DaemonSetList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of daemon sets. @@ -489,7 +500,7 @@ type DaemonSetList struct { type ThirdPartyResourceDataList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of ThirdpartyResourceData. @@ -502,15 +513,15 @@ type ThirdPartyResourceDataList struct { type Job struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status JobStatus `json:"status,omitempty"` } @@ -518,7 +529,7 @@ type Job struct { type JobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of Job. @@ -532,7 +543,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/HEAD/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/jobs.md Parallelism *int32 `json:"parallelism,omitempty"` // Completions specifies the desired number of successfully finished pods the @@ -540,6 +551,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.2/docs/user-guide/jobs.md Completions *int32 `json:"completions,omitempty"` // Optional duration in seconds relative to the startTime that the job may be active @@ -547,12 +559,20 @@ type JobSpec struct { ActiveDeadlineSeconds *int64 `json:"activeDeadlineSeconds,omitempty"` // Selector is a label query over pods that should match the pod count. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors + // Normally, the system sets this field for you. + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors Selector *LabelSelector `json:"selector,omitempty"` + // 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.2/docs/design/selector-generation.md + AutoSelector *bool `json:"autoSelector,omitempty"` + // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/jobs.md Template v1.PodTemplateSpec `json:"template"` } @@ -560,7 +580,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/HEAD/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/jobs.md Conditions []JobCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` // StartTime represents time when the job was acknowledged by the Job Manager. @@ -618,15 +638,15 @@ type JobCondition struct { type Ingress struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty"` // Spec is the desired state of the Ingress. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/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/HEAD/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status IngressStatus `json:"status,omitempty"` } @@ -634,7 +654,7 @@ type Ingress struct { type IngressList struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of Ingress. @@ -760,67 +780,6 @@ type IngressBackend struct { ServicePort intstr.IntOrString `json:"servicePort"` } -type NodeResource string - -const ( - // Percentage of node's CPUs that is currently used. - CpuConsumption NodeResource = "CpuConsumption" - - // Percentage of node's CPUs that is currently requested for pods. - CpuRequest NodeResource = "CpuRequest" - - // Percentage od node's memory that is currently used. - MemConsumption NodeResource = "MemConsumption" - - // Percentage of node's CPUs that is currently requested for pods. - MemRequest NodeResource = "MemRequest" -) - -// NodeUtilization describes what percentage of a particular resource is used on a node. -type NodeUtilization struct { - Resource NodeResource `json:"resource"` - - // The accepted values are from 0 to 1. - Value float64 `json:"value"` -} - -// Configuration of the Cluster Autoscaler -type ClusterAutoscalerSpec struct { - // Minimum number of nodes that the cluster should have. - MinNodes int32 `json:"minNodes"` - - // Maximum number of nodes that the cluster should have. - MaxNodes int32 `json:"maxNodes"` - - // Target average utilization of the cluster nodes. New nodes will be added if one of the - // targets is exceeded. Cluster size will be decreased if the current utilization is too low - // for all targets. - TargetUtilization []NodeUtilization `json:"target"` -} - -type ClusterAutoscaler struct { - unversioned.TypeMeta `json:",inline"` - - // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata - // For now (experimental api) it is required that the name is set to "ClusterAutoscaler" and namespace is "default". - v1.ObjectMeta `json:"metadata,omitempty"` - - // Spec defines the desired behavior of this daemon set. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status - Spec ClusterAutoscalerSpec `json:"spec,omitempty"` -} - -// There will be just one (or none) ClusterAutoscaler. -type ClusterAutoscalerList struct { - unversioned.TypeMeta `json:",inline"` - // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata - unversioned.ListMeta `json:"metadata,omitempty"` - - Items []ClusterAutoscaler `json:"items"` -} - // ExportOptions is the query options to the standard REST get call. type ExportOptions struct { unversioned.TypeMeta `json:",inline"` @@ -895,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/HEAD/docs/devel/api-conventions.md#metadata + // Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Spec ReplicaSetSpec `json:"spec,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status Status ReplicaSetStatus `json:"status,omitempty"` } @@ -914,11 +873,11 @@ type ReplicaSet struct { type ReplicaSetList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty"` // List of ReplicaSets. - // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md Items []ReplicaSet `json:"items"` } @@ -927,27 +886,30 @@ 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/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas *int32 `json:"replicas,omitempty"` // 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 + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/labels.md#label-selectors Selector *LabelSelector `json:"selector,omitempty"` // 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 - Template *v1.PodTemplateSpec `json:"template,omitempty"` + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#pod-template + Template v1.PodTemplateSpec `json:"template,omitempty"` } // 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/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas int32 `json:"replicas"` + // The number of pods that have labels matching the labels of the pod template of the replicaset. + FullyLabeledReplicas int32 `json:"fullyLabeledReplicas,omitempty"` + // ObservedGeneration reflects the generation of the most recently observed ReplicaSet. ObservedGeneration int64 `json:"observedGeneration,omitempty"` } @@ -957,7 +919,7 @@ type ReplicaSetStatus struct { type PodSecurityPolicy struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty"` // spec defines the policy enforced. @@ -981,8 +943,8 @@ type PodSecurityPolicySpec struct { HostPID bool `json:"hostPID,omitempty"` // hostIPC determines if the policy allows the use of HostIPC in the pod spec. HostIPC bool `json:"hostIPC,omitempty"` - // seLinuxContext is the strategy that will dictate the allowable labels that may be set. - SELinuxContext SELinuxContextStrategyOptions `json:"seLinuxContext,omitempty"` + // seLinux is the strategy that will dictate the allowable labels that may be set. + SELinux SELinuxStrategyOptions `json:"seLinux,omitempty"` // runAsUser is the strategy that will dictate the allowable RunAsUser values that may be set. RunAsUser RunAsUserStrategyOptions `json:"runAsUser,omitempty"` } @@ -1017,30 +979,30 @@ type HostPortRange struct { Max int32 `json:"max"` } -// SELinux Context Strategy Options defines the strategy type and any options used to create the strategy. -type SELinuxContextStrategyOptions struct { +// SELinux Strategy Options defines the strategy type and any options used to create the strategy. +type SELinuxStrategyOptions struct { // type is the strategy that will dictate the allowable labels that may be set. - Type SELinuxContextStrategy `json:"type"` + Rule SELinuxStrategy `json:"rule"` // seLinuxOptions required to run as; required for MustRunAs - // More info: http://releases.k8s.io/HEAD/docs/design/security_context.md#security-context + // More info: http://releases.k8s.io/release-1.2/docs/design/security_context.md#security-context SELinuxOptions *v1.SELinuxOptions `json:"seLinuxOptions,omitempty"` } -// SELinux Context Strategy Type denotes strategy types for generating SELinux options for a +// SELinuxStrategy denotes strategy types for generating SELinux options for a // Security Context. -type SELinuxContextStrategy string +type SELinuxStrategy string const ( // container must have SELinux labels of X applied. - SELinuxStrategyMustRunAs SELinuxContextStrategy = "MustRunAs" + SELinuxStrategyMustRunAs SELinuxStrategy = "MustRunAs" // container may make requests for any SELinux context labels. - SELinuxStrategyRunAsAny SELinuxContextStrategy = "RunAsAny" + SELinuxStrategyRunAsAny SELinuxStrategy = "RunAsAny" ) // Run A sUser Strategy Options defines the strategy type and any options used to create the strategy. type RunAsUserStrategyOptions struct { - // type is the strategy that will dictate the allowable RunAsUser values that may be set. - Type RunAsUserStrategy `json:"type"` + // Rule is the strategy that will dictate the allowable RunAsUser values that may be set. + Rule RunAsUserStrategy `json:"rule"` // Ranges are the allowed ranges of uids that may be used. Ranges []IDRange `json:"ranges,omitempty"` } @@ -1053,7 +1015,7 @@ type IDRange struct { Max int64 `json:"max"` } -// Run As User Strategy Type denotes strategy types for generating RunAsUser values for a +// RunAsUserStrategy denotes strategy types for generating RunAsUser values for a // Security Context. type RunAsUserStrategy string @@ -1070,7 +1032,7 @@ const ( type PodSecurityPolicyList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://docs.k8s.io/api-conventions.md#metadata + // More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of schema objects. diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go index e6176c293..44e446215 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go @@ -16,7 +16,7 @@ limitations under the License. package v1beta1 -// This file contains a collection of methods that can be used from go-resful to +// 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 // @@ -45,35 +45,6 @@ func (CPUTargetUtilization) SwaggerDoc() map[string]string { return map_CPUTargetUtilization } -var map_ClusterAutoscaler = map[string]string{ - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata For now (experimental api) it is required that the name is set to \"ClusterAutoscaler\" and namespace is \"default\".", - "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", -} - -func (ClusterAutoscaler) SwaggerDoc() map[string]string { - return map_ClusterAutoscaler -} - -var map_ClusterAutoscalerList = map[string]string{ - "": "There will be just one (or none) ClusterAutoscaler.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", -} - -func (ClusterAutoscalerList) SwaggerDoc() map[string]string { - return map_ClusterAutoscalerList -} - -var map_ClusterAutoscalerSpec = map[string]string{ - "": "Configuration of the Cluster Autoscaler", - "minNodes": "Minimum number of nodes that the cluster should have.", - "maxNodes": "Maximum number of nodes that the cluster should have.", - "target": "Target average utilization of the cluster nodes. New nodes will be added if one of the targets is exceeded. Cluster size will be decreased if the current utilization is too low for all targets.", -} - -func (ClusterAutoscalerSpec) SwaggerDoc() map[string]string { - return map_ClusterAutoscalerSpec -} - var map_CustomMetricCurrentStatus = map[string]string{ "name": "Custom Metric name.", "value": "Custom Metric value (average).", @@ -95,9 +66,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the desired behavior of this daemon set. More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (DaemonSet) SwaggerDoc() map[string]string { @@ -106,7 +77,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "items": "Items is a list of daemon sets.", } @@ -116,8 +87,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/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", + "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.2/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.2/docs/user-guide/replication-controller.md#pod-template", } func (DaemonSetSpec) SwaggerDoc() map[string]string { @@ -126,9 +97,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/HEAD/docs/admin/daemon.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/daemon.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/daemon.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/release-1.2/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.2/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.2/docs/admin/daemons.md", } func (DaemonSetStatus) SwaggerDoc() map[string]string { @@ -185,6 +156,7 @@ func (DeploymentSpec) SwaggerDoc() map[string]string { var map_DeploymentStatus = map[string]string{ "": "DeploymentStatus is the most recently observed status of the Deployment.", + "observedGeneration": "The generation observed by the deployment controller.", "replicas": "Total number of non-terminated pods targeted by this deployment (their labels match the selector).", "updatedReplicas": "Total number of non-terminated pods targeted by this deployment that have the desired template spec.", "availableReplicas": "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.", @@ -236,8 +208,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/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.", + "metadata": "Standard object metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "behaviour of autoscaler. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status.", "status": "current information about the autoscaler.", } @@ -302,9 +274,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", + "spec": "Spec is the desired state of the Ingress. More info: http://releases.k8s.io/release-1.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (Ingress) SwaggerDoc() map[string]string { @@ -323,7 +295,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "items": "Items is the list of Ingress.", } @@ -380,9 +352,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/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", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/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.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (Job) SwaggerDoc() map[string]string { @@ -405,7 +377,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "items": "Items is the list of Job.", } @@ -415,11 +387,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/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.", + "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.2/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.2/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. 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 when executing a job. More info: http://releases.k8s.io/HEAD/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/release-1.2/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.2/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.2/docs/user-guide/jobs.md", } func (JobSpec) SwaggerDoc() map[string]string { @@ -428,7 +401,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/HEAD/docs/user-guide/jobs.md", + "conditions": "Conditions represent the latest available observations of an object's current state. More info: http://releases.k8s.io/release-1.2/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.", @@ -474,18 +447,9 @@ func (ListOptions) SwaggerDoc() map[string]string { return map_ListOptions } -var map_NodeUtilization = map[string]string{ - "": "NodeUtilization describes what percentage of a particular resource is used on a node.", - "value": "The accepted values are from 0 to 1.", -} - -func (NodeUtilization) SwaggerDoc() map[string]string { - return map_NodeUtilization -} - 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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "spec": "spec defines the policy enforced.", } @@ -495,7 +459,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://docs.k8s.io/api-conventions.md#metadata", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "items": "Items is a list of schema objects.", } @@ -504,16 +468,16 @@ func (PodSecurityPolicyList) SwaggerDoc() map[string]string { } var map_PodSecurityPolicySpec = map[string]string{ - "": "Pod Security Policy Spec defines the policy enforced.", - "privileged": "privileged determines if a pod can request to be run as privileged.", - "capabilities": "capabilities is a list of capabilities that can be added.", - "volumes": "volumes is a white list of allowed volume plugins. Empty indicates that all plugins may be used.", - "hostNetwork": "hostNetwork determines if the policy allows the use of HostNetwork in the pod spec.", - "hostPorts": "hostPorts determines which host port ranges are allowed to be exposed.", - "hostPID": "hostPID determines if the policy allows the use of HostPID in the pod spec.", - "hostIPC": "hostIPC determines if the policy allows the use of HostIPC in the pod spec.", - "seLinuxContext": "seLinuxContext is the strategy that will dictate the allowable labels that may be set.", - "runAsUser": "runAsUser is the strategy that will dictate the allowable RunAsUser values that may be set.", + "": "Pod Security Policy Spec defines the policy enforced.", + "privileged": "privileged determines if a pod can request to be run as privileged.", + "capabilities": "capabilities is a list of capabilities that can be added.", + "volumes": "volumes is a white list of allowed volume plugins. Empty indicates that all plugins may be used.", + "hostNetwork": "hostNetwork determines if the policy allows the use of HostNetwork in the pod spec.", + "hostPorts": "hostPorts determines which host port ranges are allowed to be exposed.", + "hostPID": "hostPID determines if the policy allows the use of HostPID in the pod spec.", + "hostIPC": "hostIPC determines if the policy allows the use of HostIPC in the pod spec.", + "seLinux": "seLinux is the strategy that will dictate the allowable labels that may be set.", + "runAsUser": "runAsUser is the strategy that will dictate the allowable RunAsUser values that may be set.", } func (PodSecurityPolicySpec) SwaggerDoc() map[string]string { @@ -522,9 +486,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/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", + "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.2/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.2/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.2/docs/devel/api-conventions.md#spec-and-status", } func (ReplicaSet) SwaggerDoc() map[string]string { @@ -533,8 +497,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/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", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds", + "items": "List of ReplicaSets. More info: http://releases.k8s.io/release-1.2/docs/user-guide/replication-controller.md", } func (ReplicaSetList) SwaggerDoc() map[string]string { @@ -543,9 +507,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/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", + "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.2/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.2/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.2/docs/user-guide/replication-controller.md#pod-template", } func (ReplicaSetSpec) SwaggerDoc() map[string]string { @@ -553,9 +517,10 @@ 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/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller", - "observedGeneration": "ObservedGeneration reflects the generation of the most recently observed ReplicaSet.", + "": "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.2/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.", } func (ReplicaSetStatus) SwaggerDoc() map[string]string { @@ -590,7 +555,7 @@ func (RollingUpdateDeployment) SwaggerDoc() map[string]string { var map_RunAsUserStrategyOptions = map[string]string{ "": "Run A sUser Strategy Options defines the strategy type and any options used to create the strategy.", - "type": "type is the strategy that will dictate the allowable RunAsUser values that may be set.", + "rule": "Rule is the strategy that will dictate the allowable RunAsUser values that may be set.", "ranges": "Ranges are the allowed ranges of uids that may be used.", } @@ -598,21 +563,21 @@ func (RunAsUserStrategyOptions) SwaggerDoc() map[string]string { return map_RunAsUserStrategyOptions } -var map_SELinuxContextStrategyOptions = map[string]string{ - "": "SELinux Context Strategy Options defines the strategy type and any options used to create the strategy.", - "type": "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/HEAD/docs/design/security_context.md#security-context", +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.2/docs/design/security_context.md#security-context", } -func (SELinuxContextStrategyOptions) SwaggerDoc() map[string]string { - return map_SELinuxContextStrategyOptions +func (SELinuxStrategyOptions) SwaggerDoc() map[string]string { + return map_SELinuxStrategyOptions } var map_Scale = map[string]string{ "": "represents a scaling request for a resource.", - "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.", + "metadata": "Standard object metadata; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata.", + "spec": "defines the behavior of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status.", + "status": "current status of the scale. More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#spec-and-status. Read-only.", } func (Scale) SwaggerDoc() map[string]string { @@ -629,9 +594,10 @@ 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/HEAD/docs/user-guide/labels.md#label-selectors", + "": "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.2/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.2/docs/user-guide/labels.md#label-selectors", } func (ScaleStatus) SwaggerDoc() map[string]string { @@ -640,8 +606,8 @@ func (ScaleStatus) SwaggerDoc() map[string]string { 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/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", + "kind": "Kind of the referent; More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#types-kinds\"", + "name": "Name of the referent; More info: http://releases.k8s.io/release-1.2/docs/user-guide/identifiers.md#names", "apiVersion": "API version of the referent", "subresource": "Subresource name of the referent", } @@ -673,7 +639,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/HEAD/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.2/docs/devel/api-conventions.md#metadata", "items": "Items is the list of ThirdpartyResourceData.", } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/validation/validation.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/validation/validation.go deleted file mode 100644 index 8a12486f5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/validation/validation.go +++ /dev/null @@ -1,820 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package validation - -import ( - "encoding/json" - "net" - "regexp" - "strconv" - "strings" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - unversionedvalidation "k8s.io/kubernetes/pkg/api/unversioned/validation" - apivalidation "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/controller/podautoscaler" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/util/intstr" - "k8s.io/kubernetes/pkg/util/sets" - "k8s.io/kubernetes/pkg/util/validation" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -// ValidateHorizontalPodAutoscaler can be used to check whether the given autoscaler name is valid. -// Prefix indicates this name will be used as part of generation, in which case trailing dashes are allowed. -func ValidateHorizontalPodAutoscalerName(name string, prefix bool) (bool, string) { - // TODO: finally move it to pkg/api/validation and use nameIsDNSSubdomain function - return apivalidation.ValidateReplicationControllerName(name, prefix) -} - -func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("minReplicas"), *autoscaler.MinReplicas, "must be greater than 0")) - } - if autoscaler.MaxReplicas < 1 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, "must be greater than 0")) - } - if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas { - allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, "must be greater than or equal to `minReplicas`")) - } - if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("cpuUtilization", "targetPercentage"), autoscaler.CPUUtilization.TargetPercentage, "must be greater than 0")) - } - if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef, fldPath.Child("scaleRef")); len(refErrs) > 0 { - allErrs = append(allErrs, refErrs...) - } else if autoscaler.ScaleRef.Subresource != "scale" { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("scaleRef", "subresource"), autoscaler.ScaleRef.Subresource, []string{"scale"})) - } - return allErrs -} - -func ValidateSubresourceReference(ref extensions.SubresourceReference, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if len(ref.Kind) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("kind"), "")) - } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok { - allErrs = append(allErrs, field.Invalid(fldPath.Child("kind"), ref.Kind, msg)) - } - - if len(ref.Name) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("name"), "")) - } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok { - allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), ref.Name, msg)) - } - - if len(ref.Subresource) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("subresource"), "")) - } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok { - allErrs = append(allErrs, field.Invalid(fldPath.Child("subresource"), ref.Subresource, msg)) - } - return allErrs -} - -func validateHorizontalPodAutoscalerAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if annotationValue, found := annotations[podautoscaler.HpaCustomMetricsTargetAnnotationName]; found { - // Try to parse the annotation - var targetList extensions.CustomMetricTargetList - if err := json.Unmarshal([]byte(annotationValue), &targetList); err != nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("annotations"), annotations, "failed to parse custom metrics target annotation")) - } else { - if len(targetList.Items) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("annotations", "items"), "custom metrics target must not be empty")) - } - for _, target := range targetList.Items { - if target.Name == "" { - allErrs = append(allErrs, field.Required(fldPath.Child("annotations", "items", "name"), "missing custom metric target name")) - } - if target.TargetValue.MilliValue() <= 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("annotations", "items", "value"), target.TargetValue, "custom metric target value must be greater than 0")) - } - } - } - } - return allErrs -} - -func ValidateHorizontalPodAutoscaler(autoscaler *extensions.HorizontalPodAutoscaler) field.ErrorList { - allErrs := apivalidation.ValidateObjectMeta(&autoscaler.ObjectMeta, true, ValidateHorizontalPodAutoscalerName, field.NewPath("metadata")) - allErrs = append(allErrs, validateHorizontalPodAutoscalerSpec(autoscaler.Spec, field.NewPath("spec"))...) - allErrs = append(allErrs, validateHorizontalPodAutoscalerAnnotations(autoscaler.Annotations, field.NewPath("metadata"))...) - return allErrs -} - -func ValidateHorizontalPodAutoscalerUpdate(newAutoscaler, oldAutoscaler *extensions.HorizontalPodAutoscaler) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&newAutoscaler.ObjectMeta, &oldAutoscaler.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, validateHorizontalPodAutoscalerSpec(newAutoscaler.Spec, field.NewPath("spec"))...) - return allErrs -} - -func ValidateHorizontalPodAutoscalerStatusUpdate(newAutoscaler, oldAutoscaler *extensions.HorizontalPodAutoscaler) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&newAutoscaler.ObjectMeta, &oldAutoscaler.ObjectMeta, field.NewPath("metadata")) - status := newAutoscaler.Status - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.CurrentReplicas), field.NewPath("status", "currentReplicas"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.DesiredReplicas), field.NewPath("status", "desiredReplicasa"))...) - return allErrs -} - -func ValidateThirdPartyResourceUpdate(update, old *extensions.ThirdPartyResource) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&update.ObjectMeta, &old.ObjectMeta, field.NewPath("metadata"))...) - allErrs = append(allErrs, ValidateThirdPartyResource(update)...) - return allErrs -} - -func ValidateThirdPartyResourceName(name string, prefix bool) (bool, string) { - return apivalidation.NameIsDNSSubdomain(name, prefix) -} - -func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&obj.ObjectMeta, true, ValidateThirdPartyResourceName, field.NewPath("metadata"))...) - - versions := sets.String{} - for ix := range obj.Versions { - version := &obj.Versions[ix] - if len(version.Name) == 0 { - allErrs = append(allErrs, field.Invalid(field.NewPath("versions").Index(ix).Child("name"), version, "must not be empty")) - } - if versions.Has(version.Name) { - allErrs = append(allErrs, field.Duplicate(field.NewPath("versions").Index(ix).Child("name"), version)) - } - versions.Insert(version.Name) - } - return allErrs -} - -// ValidateDaemonSet tests if required fields in the DaemonSet are set. -func ValidateDaemonSet(ds *extensions.DaemonSet) field.ErrorList { - allErrs := apivalidation.ValidateObjectMeta(&ds.ObjectMeta, true, ValidateDaemonSetName, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateDaemonSetSpec(&ds.Spec, field.NewPath("spec"))...) - return allErrs -} - -// ValidateDaemonSetUpdate tests if required fields in the DaemonSet are set. -func ValidateDaemonSetUpdate(ds, oldDS *extensions.DaemonSet) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&ds.ObjectMeta, &oldDS.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateDaemonSetSpec(&ds.Spec, field.NewPath("spec"))...) - return allErrs -} - -// validateDaemonSetStatus validates a DaemonSetStatus -func validateDaemonSetStatus(status *extensions.DaemonSetStatus, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.CurrentNumberScheduled), fldPath.Child("currentNumberScheduled"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.NumberMisscheduled), fldPath.Child("numberMisscheduled"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.DesiredNumberScheduled), fldPath.Child("desiredNumberScheduled"))...) - return allErrs -} - -// ValidateDaemonSetStatus validates tests if required fields in the DaemonSet Status section -func ValidateDaemonSetStatusUpdate(ds, oldDS *extensions.DaemonSet) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&ds.ObjectMeta, &oldDS.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, validateDaemonSetStatus(&ds.Status, field.NewPath("status"))...) - return allErrs -} - -// ValidateDaemonSetSpec tests if required fields in the DaemonSetSpec are set. -func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - - allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) - - selector, err := unversioned.LabelSelectorAsSelector(spec.Selector) - if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "`selector` does not match template `labels`")) - } - - allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template, fldPath.Child("template"))...) - // Daemons typically run on more than one node, so mark Read-Write persistent disks as invalid. - allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes, fldPath.Child("template", "spec", "volumes"))...) - // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). - if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("template", "spec", "restartPolicy"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) - } - return allErrs -} - -// ValidateDaemonSetName can be used to check whether the given daemon set name is valid. -// Prefix indicates this name will be used as part of generation, in which case -// trailing dashes are allowed. -func ValidateDaemonSetName(name string, prefix bool) (bool, string) { - return apivalidation.NameIsDNSSubdomain(name, prefix) -} - -// Validates that the given name can be used as a deployment name. -func ValidateDeploymentName(name string, prefix bool) (bool, string) { - return apivalidation.NameIsDNSSubdomain(name, prefix) -} - -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%')")) - } - } else if intOrPercent.Type == intstr.Int { - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(intOrPercent.IntValue()), fldPath)...) - } - return allErrs -} - -func getPercentValue(intOrStringValue intstr.IntOrString) (int, bool) { - if intOrStringValue.Type != intstr.String || !validation.IsValidPercent(intOrStringValue.StrVal) { - return 0, false - } - value, _ := strconv.Atoi(intOrStringValue.StrVal[:len(intOrStringValue.StrVal)-1]) - return value, true -} - -func getIntOrPercentValue(intOrStringValue intstr.IntOrString) int { - value, isPercent := getPercentValue(intOrStringValue) - if isPercent { - return value - } - return intOrStringValue.IntValue() -} - -func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - value, isPercent := getPercentValue(intOrStringValue) - if !isPercent || value <= 100 { - return nil - } - allErrs = append(allErrs, field.Invalid(fldPath, intOrStringValue, "must not be greater than 100%")) - return allErrs -} - -func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDeployment, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxUnavailable, fldPath.Child("maxUnavailable"))...) - allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fldPath.Child("maxSurge"))...) - if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 { - // Both MaxSurge and MaxUnavailable cannot be zero. - allErrs = append(allErrs, field.Invalid(fldPath.Child("maxUnavailable"), rollingUpdate.MaxUnavailable, "may not be 0 when `maxSurge` is 0")) - } - // Validate that MaxUnavailable is not more than 100%. - allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fldPath.Child("maxUnavailable"))...) - return allErrs -} - -func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if strategy.RollingUpdate == nil { - return allErrs - } - switch strategy.Type { - case extensions.RecreateDeploymentStrategyType: - allErrs = append(allErrs, field.Forbidden(fldPath.Child("rollingUpdate"), "may not be specified when strategy `type` is '"+string(extensions.RecreateDeploymentStrategyType+"'"))) - case extensions.RollingUpdateDeploymentStrategyType: - allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, fldPath.Child("rollingUpdate"))...) - } - return allErrs -} - -func ValidateRollback(rollback *extensions.RollbackConfig, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - v := rollback.Revision - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(v), fldPath.Child("version"))...) - return allErrs -} - -// Validates given deployment spec. -func ValidateDeploymentSpec(spec *extensions.DeploymentSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child("replicas"))...) - - if spec.Selector == nil { - allErrs = append(allErrs, field.Required(fldPath.Child("selector"), "")) - } else { - allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) - if len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("selector"), spec.Selector, "empty selector is not valid for deployment.")) - } - } - - selector, err := unversioned.LabelSelectorAsSelector(spec.Selector) - if err != nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("selector"), spec.Selector, "invalid label selector.")) - } else { - allErrs = append(allErrs, ValidatePodTemplateSpecForReplicaSet(&spec.Template, selector, spec.Replicas, fldPath.Child("template"))...) - } - - allErrs = append(allErrs, ValidateDeploymentStrategy(&spec.Strategy, fldPath.Child("strategy"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child("minReadySeconds"))...) - if spec.RevisionHistoryLimit != nil { - // zero is a valid RevisionHistoryLimit - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.RevisionHistoryLimit), fldPath.Child("revisionHistoryLimit"))...) - } - if spec.RollbackTo != nil { - allErrs = append(allErrs, ValidateRollback(spec.RollbackTo, fldPath.Child("rollback"))...) - } - return allErrs -} - -func ValidateDeploymentUpdate(update, old *extensions.Deployment) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&update.ObjectMeta, &old.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateDeploymentSpec(&update.Spec, field.NewPath("spec"))...) - return allErrs -} - -func ValidateDeployment(obj *extensions.Deployment) field.ErrorList { - allErrs := apivalidation.ValidateObjectMeta(&obj.ObjectMeta, true, ValidateDeploymentName, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateDeploymentSpec(&obj.Spec, field.NewPath("spec"))...) - return allErrs -} - -func ValidateDeploymentRollback(obj *extensions.DeploymentRollback) field.ErrorList { - allErrs := apivalidation.ValidateAnnotations(obj.UpdatedAnnotations, field.NewPath("updatedAnnotations")) - if len(obj.Name) == 0 { - allErrs = append(allErrs, field.Required(field.NewPath("name"), "name is required")) - } - allErrs = append(allErrs, ValidateRollback(&obj.RollbackTo, field.NewPath("rollback"))...) - return allErrs -} - -func ValidateThirdPartyResourceDataUpdate(update, old *extensions.ThirdPartyResourceData) field.ErrorList { - return ValidateThirdPartyResourceData(update) -} - -func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) field.ErrorList { - allErrs := field.ErrorList{} - if len(obj.Name) == 0 { - allErrs = append(allErrs, field.Required(field.NewPath("name"), "")) - } - return allErrs -} - -func ValidateJob(job *extensions.Job) field.ErrorList { - // Jobs and rcs have the same name validation - allErrs := apivalidation.ValidateObjectMeta(&job.ObjectMeta, true, apivalidation.ValidateReplicationControllerName, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateJobSpec(&job.Spec, field.NewPath("spec"))...) - return allErrs -} - -func ValidateJobSpec(spec *extensions.JobSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - - if spec.Parallelism != nil { - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.Parallelism), fldPath.Child("parallelism"))...) - } - if spec.Completions != nil { - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.Completions), fldPath.Child("completions"))...) - } - if spec.ActiveDeadlineSeconds != nil { - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.ActiveDeadlineSeconds), fldPath.Child("activeDeadlineSeconds"))...) - } - if spec.Selector == nil { - allErrs = append(allErrs, field.Required(fldPath.Child("selector"), "")) - } else { - allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) - } - - if selector, err := unversioned.LabelSelectorAsSelector(spec.Selector); err == nil { - labels := labels.Set(spec.Template.Labels) - if !selector.Matches(labels) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "`selector` does not match template `labels`")) - } - } - - allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template, fldPath.Child("template"))...) - if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure && - spec.Template.Spec.RestartPolicy != api.RestartPolicyNever { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("template", "spec", "restartPolicy"), - spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)})) - } - return allErrs -} - -func ValidateJobStatus(status *extensions.JobStatus, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Active), fldPath.Child("active"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Succeeded), fldPath.Child("succeeded"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Failed), fldPath.Child("failed"))...) - return allErrs -} - -func ValidateJobUpdate(job, oldJob *extensions.Job) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&oldJob.ObjectMeta, &job.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateJobSpecUpdate(job.Spec, oldJob.Spec, field.NewPath("spec"))...) - return allErrs -} - -func ValidateJobUpdateStatus(job, oldJob *extensions.Job) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&oldJob.ObjectMeta, &job.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateJobStatusUpdate(job.Status, oldJob.Status)...) - return allErrs -} - -func ValidateJobSpecUpdate(spec, oldSpec extensions.JobSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, ValidateJobSpec(&spec, fldPath)...) - allErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.Completions, oldSpec.Completions, fldPath.Child("completions"))...) - allErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.Selector, oldSpec.Selector, fldPath.Child("selector"))...) - allErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.Template, oldSpec.Template, fldPath.Child("template"))...) - return allErrs -} - -func ValidateJobStatusUpdate(status, oldStatus extensions.JobStatus) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, ValidateJobStatus(&status, field.NewPath("status"))...) - return allErrs -} - -// ValidateIngress tests if required fields in the Ingress are set. -func ValidateIngress(ingress *extensions.Ingress) field.ErrorList { - allErrs := apivalidation.ValidateObjectMeta(&ingress.ObjectMeta, true, ValidateIngressName, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateIngressSpec(&ingress.Spec, field.NewPath("spec"))...) - return allErrs -} - -// ValidateIngressName validates that the given name can be used as an Ingress name. -func ValidateIngressName(name string, prefix bool) (bool, string) { - return apivalidation.NameIsDNSSubdomain(name, prefix) -} - -func validateIngressTLS(spec *extensions.IngressSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - // Currently the Ingress only supports HTTP(S), so a secretName is required. - // This will not be the case if we support SSL routing at L4 via SNI. - for i, t := range spec.TLS { - if t.SecretName == "" { - allErrs = append(allErrs, field.Required(fldPath.Index(i).Child("secretName"), spec.TLS[i].SecretName)) - } - } - // TODO: Perform a more thorough validation of spec.TLS.Hosts that takes - // the wildcard spec from RFC 6125 into account. - return allErrs -} - -// ValidateIngressSpec tests if required fields in the IngressSpec are set. -func ValidateIngressSpec(spec *extensions.IngressSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - // TODO: Is a default backend mandatory? - if spec.Backend != nil { - allErrs = append(allErrs, validateIngressBackend(spec.Backend, fldPath.Child("backend"))...) - } else if len(spec.Rules) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath, spec.Rules, "either `backend` or `rules` must be specified")) - } - if len(spec.Rules) > 0 { - allErrs = append(allErrs, validateIngressRules(spec.Rules, fldPath.Child("rules"))...) - } - if len(spec.TLS) > 0 { - allErrs = append(allErrs, validateIngressTLS(spec, fldPath.Child("tls"))...) - } - return allErrs -} - -// ValidateIngressUpdate tests if required fields in the Ingress are set. -func ValidateIngressUpdate(ingress, oldIngress *extensions.Ingress) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&ingress.ObjectMeta, &oldIngress.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateIngressSpec(&ingress.Spec, field.NewPath("spec"))...) - return allErrs -} - -// ValidateIngressStatusUpdate tests if required fields in the Ingress are set when updating status. -func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) field.ErrorList { - allErrs := apivalidation.ValidateObjectMetaUpdate(&ingress.ObjectMeta, &oldIngress.ObjectMeta, field.NewPath("metadata")) - allErrs = append(allErrs, apivalidation.ValidateLoadBalancerStatus(&ingress.Status.LoadBalancer, field.NewPath("status", "loadBalancer"))...) - return allErrs -} - -func validateIngressRules(IngressRules []extensions.IngressRule, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if len(IngressRules) == 0 { - return append(allErrs, field.Required(fldPath, "")) - } - for i, ih := range IngressRules { - if len(ih.Host) > 0 { - // TODO: Ports and ips are allowed in the host part of a url - // according to RFC 3986, consider allowing them. - if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid { - allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("host"), ih.Host, errMsg)) - } - if isIP := (net.ParseIP(ih.Host) != nil); isIP { - allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("host"), ih.Host, "must be a DNS name, not an IP address")) - } - } - allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue, fldPath.Index(0))...) - } - return allErrs -} - -func validateIngressRuleValue(ingressRule *extensions.IngressRuleValue, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if ingressRule.HTTP != nil { - allErrs = append(allErrs, validateHTTPIngressRuleValue(ingressRule.HTTP, fldPath.Child("http"))...) - } - return allErrs -} - -func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if len(httpIngressRuleValue.Paths) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("paths"), "")) - } - for i, rule := range httpIngressRuleValue.Paths { - if len(rule.Path) > 0 { - if !strings.HasPrefix(rule.Path, "/") { - allErrs = append(allErrs, field.Invalid(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must be an absolute path")) - } - // TODO: More draconian path regex validation. - // Path must be a valid regex. This is the basic requirement. - // In addition to this any characters not allowed in a path per - // RFC 3986 section-3.3 cannot appear as a literal in the regex. - // Consider the example: http://host/valid?#bar, everything after - // the last '/' is a valid regex that matches valid#bar, which - // isn't a valid path, because the path terminates at the first ? - // or #. A more sophisticated form of validation would detect that - // the user is confusing url regexes with path regexes. - _, err := regexp.CompilePOSIX(rule.Path) - if err != nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must be a valid regex")) - } - } - allErrs = append(allErrs, validateIngressBackend(&rule.Backend, fldPath.Child("backend"))...) - } - return allErrs -} - -// validateIngressBackend tests if a given backend is valid. -func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - - // All backends must reference a single local service by name, and a single service port by name or number. - if len(backend.ServiceName) == 0 { - return append(allErrs, field.Required(fldPath.Child("serviceName"), "")) - } else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok { - allErrs = append(allErrs, field.Invalid(fldPath.Child("serviceName"), backend.ServiceName, errMsg)) - } - if backend.ServicePort.Type == intstr.String { - if !validation.IsDNS1123Label(backend.ServicePort.StrVal) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg)) - } - 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)) - } - return allErrs -} - -func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if spec.MinNodes < 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("minNodes"), spec.MinNodes, "must be greater than or equal to 0")) - } - if spec.MaxNodes < spec.MinNodes { - allErrs = append(allErrs, field.Invalid(fldPath.Child("maxNodes"), spec.MaxNodes, "must be greater than or equal to `minNodes`")) - } - if len(spec.TargetUtilization) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("targetUtilization"), "")) - } - for _, target := range spec.TargetUtilization { - if len(target.Resource) == 0 { - allErrs = append(allErrs, field.Required(fldPath.Child("targetUtilization", "resource"), "")) - } - if target.Value <= 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("targetUtilization", "value"), target.Value, "must be greater than 0")) - } - if target.Value > 1 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("targetUtilization", "value"), target.Value, "must be less than or equal to 1")) - } - } - return allErrs -} - -func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) field.ErrorList { - allErrs := field.ErrorList{} - if autoscaler.Name != "ClusterAutoscaler" { - allErrs = append(allErrs, field.Invalid(field.NewPath("metadata", "name"), autoscaler.Name, "must be 'ClusterAutoscaler'")) - } - if autoscaler.Namespace != api.NamespaceDefault { - allErrs = append(allErrs, field.Invalid(field.NewPath("metadata", "namespace"), autoscaler.Namespace, "must be 'default'")) - } - allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec, field.NewPath("spec"))...) - return allErrs -} - -func ValidateScale(scale *extensions.Scale) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain, field.NewPath("metadata"))...) - - if scale.Spec.Replicas < 0 { - allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "replicas"), scale.Spec.Replicas, "must be greater than or equal to 0")) - } - - return allErrs -} - -// ValidateReplicaSetName can be used to check whether the given ReplicaSet -// name is valid. -// Prefix indicates this name will be used as part of generation, in which case -// trailing dashes are allowed. -func ValidateReplicaSetName(name string, prefix bool) (bool, string) { - return apivalidation.NameIsDNSSubdomain(name, prefix) -} - -// ValidateReplicaSet tests if required fields in the ReplicaSet are set. -func ValidateReplicaSet(rs *extensions.ReplicaSet) field.ErrorList { - allErrs := apivalidation.ValidateObjectMeta(&rs.ObjectMeta, true, ValidateReplicaSetName, field.NewPath("metadata")) - allErrs = append(allErrs, ValidateReplicaSetSpec(&rs.Spec, field.NewPath("spec"))...) - return allErrs -} - -// ValidateReplicaSetUpdate tests if required fields in the ReplicaSet are set. -func ValidateReplicaSetUpdate(rs, oldRs *extensions.ReplicaSet) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&rs.ObjectMeta, &oldRs.ObjectMeta, field.NewPath("metadata"))...) - allErrs = append(allErrs, ValidateReplicaSetSpec(&rs.Spec, field.NewPath("spec"))...) - return allErrs -} - -// ValidateReplicaSetStatusUpdate tests if required fields in the ReplicaSet are set. -func ValidateReplicaSetStatusUpdate(rs, oldRs *extensions.ReplicaSet) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&rs.ObjectMeta, &oldRs.ObjectMeta, field.NewPath("metadata"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(rs.Status.Replicas), field.NewPath("status", "replicas"))...) - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(rs.Status.ObservedGeneration), field.NewPath("status", "observedGeneration"))...) - return allErrs -} - -// ValidateReplicaSetSpec tests if required fields in the ReplicaSet spec are set. -func ValidateReplicaSetSpec(spec *extensions.ReplicaSetSpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - - allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child("replicas"))...) - - if spec.Selector == nil { - allErrs = append(allErrs, field.Required(fldPath.Child("selector"), "")) - } else { - allErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) - if len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("selector"), spec.Selector, "empty selector is not valid for deployment.")) - } - } - - selector, err := unversioned.LabelSelectorAsSelector(spec.Selector) - if err != nil { - allErrs = append(allErrs, field.Invalid(fldPath.Child("selector"), spec.Selector, "invalid label selector.")) - } else { - allErrs = append(allErrs, ValidatePodTemplateSpecForReplicaSet(spec.Template, selector, spec.Replicas, fldPath.Child("template"))...) - } - return allErrs -} - -// Validates the given template and ensures that it is in accordance with the desired selector and replicas. -func ValidatePodTemplateSpecForReplicaSet(template *api.PodTemplateSpec, selector labels.Selector, replicas int, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - if template == nil { - allErrs = append(allErrs, field.Required(fldPath, "")) - } else { - if !selector.Empty() { - // Verify that the ReplicaSet selector matches the labels in template. - labels := labels.Set(template.Labels) - if !selector.Matches(labels) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("metadata", "labels"), template.Labels, "`selector` does not match template `labels`")) - } - } - allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(template, fldPath)...) - if replicas > 1 { - allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(template.Spec.Volumes, fldPath.Child("spec", "volumes"))...) - } - // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). - if template.Spec.RestartPolicy != api.RestartPolicyAlways { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("spec", "restartPolicy"), template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) - } - } - return allErrs -} - -// ValidatePodSecurityPolicyName can be used to check whether the given -// pod security policy name is valid. -// Prefix indicates this name will be used as part of generation, in which case -// trailing dashes are allowed. -func ValidatePodSecurityPolicyName(name string, prefix bool) (bool, string) { - return apivalidation.NameIsDNSSubdomain(name, prefix) -} - -func ValidatePodSecurityPolicy(psp *extensions.PodSecurityPolicy) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&psp.ObjectMeta, false, ValidatePodSecurityPolicyName, field.NewPath("metadata"))...) - allErrs = append(allErrs, ValidatePodSecurityPolicySpec(&psp.Spec, field.NewPath("spec"))...) - return allErrs -} - -func ValidatePodSecurityPolicySpec(spec *extensions.PodSecurityPolicySpec, fldPath *field.Path) field.ErrorList { - allErrs := field.ErrorList{} - - allErrs = append(allErrs, validatePSPRunAsUser(fldPath.Child("runAsUser"), &spec.RunAsUser)...) - allErrs = append(allErrs, validatePSPSELinuxContext(fldPath.Child("seLinuxContext"), &spec.SELinuxContext)...) - allErrs = append(allErrs, validatePodSecurityPolicyVolumes(fldPath, spec.Volumes)...) - - return allErrs -} - -// validatePSPSELinuxContext validates the SELinuxContext fields of PodSecurityPolicy. -func validatePSPSELinuxContext(fldPath *field.Path, seLinuxContext *extensions.SELinuxContextStrategyOptions) field.ErrorList { - allErrs := field.ErrorList{} - - // ensure the selinux strategy has a valid type - supportedSELinuxContextTypes := sets.NewString(string(extensions.SELinuxStrategyMustRunAs), - string(extensions.SELinuxStrategyRunAsAny)) - if !supportedSELinuxContextTypes.Has(string(seLinuxContext.Type)) { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("type"), seLinuxContext.Type, supportedSELinuxContextTypes.List())) - } - - return allErrs -} - -// validatePSPRunAsUser validates the RunAsUser fields of PodSecurityPolicy. -func validatePSPRunAsUser(fldPath *field.Path, runAsUser *extensions.RunAsUserStrategyOptions) field.ErrorList { - allErrs := field.ErrorList{} - - // ensure the user strategy has a valid type - supportedRunAsUserTypes := sets.NewString(string(extensions.RunAsUserStrategyMustRunAs), - string(extensions.RunAsUserStrategyMustRunAsNonRoot), - string(extensions.RunAsUserStrategyRunAsAny)) - if !supportedRunAsUserTypes.Has(string(runAsUser.Type)) { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("type"), runAsUser.Type, supportedRunAsUserTypes.List())) - } - - // validate range settings - for idx, rng := range runAsUser.Ranges { - allErrs = append(allErrs, validateIDRanges(fldPath.Child("ranges").Index(idx), rng)...) - } - - return allErrs -} - -// validatePodSecurityPolicyVolumes validates the volume fields of PodSecurityPolicy. -func validatePodSecurityPolicyVolumes(fldPath *field.Path, volumes []extensions.FSType) field.ErrorList { - allErrs := field.ErrorList{} - allowed := sets.NewString(string(extensions.HostPath), - string(extensions.EmptyDir), - string(extensions.GCEPersistentDisk), - string(extensions.AWSElasticBlockStore), - string(extensions.GitRepo), - string(extensions.Secret), - string(extensions.NFS), - string(extensions.ISCSI), - string(extensions.Glusterfs), - string(extensions.PersistentVolumeClaim), - string(extensions.RBD), - string(extensions.Cinder), - string(extensions.CephFS), - string(extensions.DownwardAPI), - string(extensions.FC)) - for _, v := range volumes { - if !allowed.Has(string(v)) { - allErrs = append(allErrs, field.NotSupported(fldPath.Child("volumes"), v, allowed.List())) - } - } - - return allErrs -} - -// validateIDRanges ensures the range is valid. -func validateIDRanges(fldPath *field.Path, rng extensions.IDRange) field.ErrorList { - allErrs := field.ErrorList{} - - // if 0 <= Min <= Max then we do not need to validate max. It is always greater than or - // equal to 0 and Min. - if rng.Min < 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("min"), rng.Min, "min cannot be negative")) - } - if rng.Max < 0 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("max"), rng.Max, "max cannot be negative")) - } - if rng.Min > rng.Max { - allErrs = append(allErrs, field.Invalid(fldPath.Child("min"), rng.Min, "min cannot be greater than max")) - } - - return allErrs -} - -// ValidatePodSecurityPolicyUpdate validates a PSP for updates. -func ValidatePodSecurityPolicyUpdate(old *extensions.PodSecurityPolicy, new *extensions.PodSecurityPolicy) field.ErrorList { - allErrs := field.ErrorList{} - allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&old.ObjectMeta, &new.ObjectMeta, field.NewPath("metadata"))...) - allErrs = append(allErrs, ValidatePodSecurityPolicySpec(&new.Spec, field.NewPath("spec"))...) - return allErrs -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/validation/validation_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/validation/validation_test.go deleted file mode 100644 index c421bdd40..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/apis/extensions/validation/validation_test.go +++ /dev/null @@ -1,2072 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package validation - -import ( - "fmt" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/controller/podautoscaler" - "k8s.io/kubernetes/pkg/util/intstr" -) - -func TestValidateHorizontalPodAutoscaler(t *testing.T) { - successCases := []extensions.HorizontalPodAutoscaler{ - { - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Kind: "ReplicationController", - Name: "myrc", - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Kind: "ReplicationController", - Name: "myrc", - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - podautoscaler.HpaCustomMetricsTargetAnnotationName: "{\"items\":[{\"name\":\"qps\",\"value\":\"20\"}]}", - }, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Kind: "ReplicationController", - Name: "myrc", - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateHorizontalPodAutoscaler(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []struct { - horizontalPodAutoscaler extensions.HorizontalPodAutoscaler - msg string - }{ - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault}, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{Name: "myrc", Subresource: "scale"}, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - msg: "scaleRef.kind: Required", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault}, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{Kind: "..", Name: "myrc", Subresource: "scale"}, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - msg: "scaleRef.kind: Invalid", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault}, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Subresource: "scale"}, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - msg: "scaleRef.name: Required", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault}, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "..", Subresource: "scale"}, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - msg: "scaleRef.name: Invalid", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault}, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "myrc", Subresource: ""}, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - msg: "scaleRef.subresource: Required", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault}, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "myrc", Subresource: ".."}, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - msg: "scaleRef.subresource: Invalid", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{Name: "myautoscaler", Namespace: api.NamespaceDefault}, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{Kind: "ReplicationController", Name: "myrc", Subresource: "randomsubresource"}, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: 70}, - }, - }, - msg: "scaleRef.subresource: Unsupported", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Subresource: "scale", - }, - MinReplicas: newInt(-1), - MaxReplicas: 5, - }, - }, - msg: "must be greater than 0", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Subresource: "scale", - }, - MinReplicas: newInt(7), - MaxReplicas: 5, - }, - }, - msg: "must be greater than or equal to `minReplicas`", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - CPUUtilization: &extensions.CPUTargetUtilization{TargetPercentage: -70}, - }, - }, - msg: "must be greater than 0", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - podautoscaler.HpaCustomMetricsTargetAnnotationName: "broken", - }, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Kind: "ReplicationController", - Name: "myrc", - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - }, - }, - msg: "failed to parse custom metrics target annotation", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - podautoscaler.HpaCustomMetricsTargetAnnotationName: "{}", - }, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Kind: "ReplicationController", - Name: "myrc", - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - }, - }, - msg: "custom metrics target must not be empty", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - podautoscaler.HpaCustomMetricsTargetAnnotationName: "{\"items\":[{\"value\":\"20\"}]}", - }, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Kind: "ReplicationController", - Name: "myrc", - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - }, - }, - msg: "missing custom metric target name", - }, - { - horizontalPodAutoscaler: extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "myautoscaler", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - podautoscaler.HpaCustomMetricsTargetAnnotationName: "{\"items\":[{\"name\":\"qps\",\"value\":\"0\"}]}", - }, - }, - Spec: extensions.HorizontalPodAutoscalerSpec{ - ScaleRef: extensions.SubresourceReference{ - Kind: "ReplicationController", - Name: "myrc", - Subresource: "scale", - }, - MinReplicas: newInt(1), - MaxReplicas: 5, - }, - }, - msg: "custom metric target value must be greater than 0", - }, - } - - for _, c := range errorCases { - errs := ValidateHorizontalPodAutoscaler(&c.horizontalPodAutoscaler) - if len(errs) == 0 { - t.Errorf("expected failure for %q", c.msg) - } else if !strings.Contains(errs[0].Error(), c.msg) { - t.Errorf("unexpected error: %q, expected: %q", errs[0], c.msg) - } - } -} - -func TestValidateDaemonSetStatusUpdate(t *testing.T) { - type dsUpdateTest struct { - old extensions.DaemonSet - update extensions.DaemonSet - } - - successCases := []dsUpdateTest{ - { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Status: extensions.DaemonSetStatus{ - CurrentNumberScheduled: 1, - NumberMisscheduled: 2, - DesiredNumberScheduled: 3, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Status: extensions.DaemonSetStatus{ - CurrentNumberScheduled: 1, - NumberMisscheduled: 1, - DesiredNumberScheduled: 3, - }, - }, - }, - } - - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateDaemonSetStatusUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]dsUpdateTest{ - "negative values": { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Status: extensions.DaemonSetStatus{ - CurrentNumberScheduled: 1, - NumberMisscheduled: 2, - DesiredNumberScheduled: 3, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Status: extensions.DaemonSetStatus{ - CurrentNumberScheduled: -1, - NumberMisscheduled: -1, - DesiredNumberScheduled: -3, - }, - }, - }, - } - - for testName, errorCase := range errorCases { - if errs := ValidateDaemonSetStatusUpdate(&errorCase.old, &errorCase.update); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } -} - -func TestValidateDaemonSetUpdate(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validSelector2 := map[string]string{"c": "d"} - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - - validPodSpecAbc := api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - } - validPodSpecDef := api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "def", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - } - validPodSpecNodeSelector := api.PodSpec{ - NodeSelector: validSelector, - NodeName: "xyz", - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - } - validPodSpecVolume := api.PodSpec{ - Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - } - - validPodTemplateAbc := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: validPodSpecAbc, - }, - } - validPodTemplateNodeSelector := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: validPodSpecNodeSelector, - }, - } - validPodTemplateAbc2 := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector2, - }, - Spec: validPodSpecAbc, - }, - } - validPodTemplateDef := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector2, - }, - Spec: validPodSpecDef, - }, - } - invalidPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - ObjectMeta: api.ObjectMeta{ - Labels: invalidSelector, - }, - }, - } - readWriteVolumePodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: validPodSpecVolume, - }, - } - - type dsUpdateTest struct { - old extensions.DaemonSet - update extensions.DaemonSet - } - successCases := []dsUpdateTest{ - { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - }, - { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector2}, - Template: validPodTemplateAbc2.Template, - }, - }, - }, - { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateNodeSelector.Template, - }, - }, - }, - } - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateDaemonSetUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]dsUpdateTest{ - "change daemon name": { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - }, - "invalid selector": { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: invalidSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - }, - "invalid pod": { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: invalidPodTemplate.Template, - }, - }, - }, - "change container image": { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateDef.Template, - }, - }, - }, - "read-write volume": { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: readWriteVolumePodTemplate.Template, - }, - }, - }, - "invalid update strategy": { - old: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - update: extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: invalidSelector}, - Template: validPodTemplateAbc.Template, - }, - }, - }, - } - for testName, errorCase := range errorCases { - if errs := ValidateDaemonSetUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } -} - -func TestValidateDaemonSet(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - invalidPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - ObjectMeta: api.ObjectMeta{ - Labels: invalidSelector, - }, - }, - } - successCases := []extensions.DaemonSet{ - { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplate.Template, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplate.Template, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateDaemonSet(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]extensions.DaemonSet{ - "zero-length ID": { - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplate.Template, - }, - }, - "missing-namespace": { - ObjectMeta: api.ObjectMeta{Name: "abc-123"}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplate.Template, - }, - }, - "empty selector": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Template: validPodTemplate.Template, - }, - }, - "selector_doesnt_match": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - Template: validPodTemplate.Template, - }, - }, - "invalid template": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - }, - }, - "invalid_label": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplate.Template, - }, - }, - "invalid_label 2": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: extensions.DaemonSetSpec{ - Template: invalidPodTemplate.Template, - }, - }, - "invalid_annotation": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: validPodTemplate.Template, - }, - }, - "invalid restart policy 1": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - }, - }, - }, - "invalid restart policy 2": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validSelector}, - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - ObjectMeta: api.ObjectMeta{ - Labels: validSelector, - }, - }, - }, - }, - } - for k, v := range errorCases { - errs := ValidateDaemonSet(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - field := errs[i].Field - if !strings.HasPrefix(field, "spec.template.") && - !strings.HasPrefix(field, "spec.updateStrategy") && - field != "metadata.name" && - field != "metadata.namespace" && - field != "spec.selector" && - field != "spec.template" && - field != "GCEPersistentDisk.ReadOnly" && - field != "spec.template.labels" && - field != "metadata.annotations" && - field != "metadata.labels" { - t.Errorf("%s: missing prefix for: %v", k, errs[i]) - } - } - } -} - -func validDeployment() *extensions.Deployment { - return &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.DeploymentSpec{ - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{ - "name": "abc", - }, - }, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: api.NamespaceDefault, - Labels: map[string]string{ - "name": "abc", - }, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSDefault, - Containers: []api.Container{ - { - Name: "nginx", - Image: "image", - ImagePullPolicy: api.PullNever, - }, - }, - }, - }, - RollbackTo: &extensions.RollbackConfig{ - Revision: 1, - }, - }, - } -} - -func TestValidateDeployment(t *testing.T) { - successCases := []*extensions.Deployment{ - validDeployment(), - } - for _, successCase := range successCases { - if errs := ValidateDeployment(successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]*extensions.Deployment{} - errorCases["metadata.name: Required value"] = &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Namespace: api.NamespaceDefault, - }, - } - // selector should match the labels in pod template. - invalidSelectorDeployment := validDeployment() - invalidSelectorDeployment.Spec.Selector = &unversioned.LabelSelector{ - MatchLabels: map[string]string{ - "name": "def", - }, - } - errorCases["`selector` does not match template `labels`"] = invalidSelectorDeployment - - // RestartPolicy should be always. - invalidRestartPolicyDeployment := validDeployment() - invalidRestartPolicyDeployment.Spec.Template.Spec.RestartPolicy = api.RestartPolicyNever - errorCases["Unsupported value: \"Never\""] = invalidRestartPolicyDeployment - - // rollingUpdate should be nil for recreate. - invalidRecreateDeployment := validDeployment() - invalidRecreateDeployment.Spec.Strategy = extensions.DeploymentStrategy{ - Type: extensions.RecreateDeploymentStrategyType, - RollingUpdate: &extensions.RollingUpdateDeployment{}, - } - errorCases["may not be specified when strategy `type` is 'Recreate'"] = invalidRecreateDeployment - - // MaxSurge should be in the form of 20%. - invalidMaxSurgeDeployment := validDeployment() - invalidMaxSurgeDeployment.Spec.Strategy = extensions.DeploymentStrategy{ - Type: extensions.RollingUpdateDeploymentStrategyType, - RollingUpdate: &extensions.RollingUpdateDeployment{ - MaxSurge: intstr.FromString("20Percent"), - }, - } - errorCases["must be an integer or percentage"] = invalidMaxSurgeDeployment - - // MaxSurge and MaxUnavailable cannot both be zero. - invalidRollingUpdateDeployment := validDeployment() - invalidRollingUpdateDeployment.Spec.Strategy = extensions.DeploymentStrategy{ - Type: extensions.RollingUpdateDeploymentStrategyType, - RollingUpdate: &extensions.RollingUpdateDeployment{ - MaxSurge: intstr.FromString("0%"), - MaxUnavailable: intstr.FromInt(0), - }, - } - errorCases["may not be 0 when `maxSurge` is 0"] = invalidRollingUpdateDeployment - - // MaxUnavailable should not be more than 100%. - invalidMaxUnavailableDeployment := validDeployment() - invalidMaxUnavailableDeployment.Spec.Strategy = extensions.DeploymentStrategy{ - Type: extensions.RollingUpdateDeploymentStrategyType, - RollingUpdate: &extensions.RollingUpdateDeployment{ - MaxUnavailable: intstr.FromString("110%"), - }, - } - errorCases["must not be greater than 100%"] = invalidMaxUnavailableDeployment - - // Rollback.Revision must be non-negative - invalidRollbackRevisionDeployment := validDeployment() - invalidRollbackRevisionDeployment.Spec.RollbackTo.Revision = -3 - errorCases["must be greater than or equal to 0"] = invalidRollbackRevisionDeployment - - for k, v := range errorCases { - errs := ValidateDeployment(v) - if len(errs) == 0 { - t.Errorf("[%s] expected failure", k) - } else if !strings.Contains(errs[0].Error(), k) { - t.Errorf("unexpected error: %q, expected: %q", errs[0].Error(), k) - } - } -} - -func validDeploymentRollback() *extensions.DeploymentRollback { - return &extensions.DeploymentRollback{ - Name: "abc", - UpdatedAnnotations: map[string]string{ - "created-by": "abc", - }, - RollbackTo: extensions.RollbackConfig{ - Revision: 1, - }, - } -} - -func TestValidateDeploymentRollback(t *testing.T) { - noAnnotation := validDeploymentRollback() - noAnnotation.UpdatedAnnotations = nil - successCases := []*extensions.DeploymentRollback{ - validDeploymentRollback(), - noAnnotation, - } - for _, successCase := range successCases { - if errs := ValidateDeploymentRollback(successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]*extensions.DeploymentRollback{} - invalidNoName := validDeploymentRollback() - invalidNoName.Name = "" - errorCases["name: Required value"] = invalidNoName - - for k, v := range errorCases { - errs := ValidateDeploymentRollback(v) - if len(errs) == 0 { - t.Errorf("[%s] expected failure", k) - } else if !strings.Contains(errs[0].Error(), k) { - t.Errorf("unexpected error: %q, expected: %q", errs[0].Error(), k) - } - } -} - -func TestValidateJob(t *testing.T) { - validSelector := &unversioned.LabelSelector{ - MatchLabels: map[string]string{"a": "b"}, - } - validPodTemplateSpec := api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector.MatchLabels, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - } - successCases := []extensions.Job{ - { - ObjectMeta: api.ObjectMeta{ - Name: "myjob", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.JobSpec{ - Selector: validSelector, - Template: validPodTemplateSpec, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateJob(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - negative := -1 - negative64 := int64(-1) - errorCases := map[string]extensions.Job{ - "spec.parallelism:must be greater than or equal to 0": { - ObjectMeta: api.ObjectMeta{ - Name: "myjob", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.JobSpec{ - Parallelism: &negative, - Selector: validSelector, - Template: validPodTemplateSpec, - }, - }, - "spec.completions:must be greater than or equal to 0": { - ObjectMeta: api.ObjectMeta{ - Name: "myjob", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.JobSpec{ - Completions: &negative, - Selector: validSelector, - Template: validPodTemplateSpec, - }, - }, - "spec.activeDeadlineSeconds:must be greater than or equal to 0": { - ObjectMeta: api.ObjectMeta{ - Name: "myjob", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.JobSpec{ - ActiveDeadlineSeconds: &negative64, - Selector: validSelector, - Template: validPodTemplateSpec, - }, - }, - "spec.selector:Required value": { - ObjectMeta: api.ObjectMeta{ - Name: "myjob", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.JobSpec{ - Template: validPodTemplateSpec, - }, - }, - "spec.template.metadata.labels: Invalid value: {\"y\":\"z\"}: `selector` does not match template `labels`": { - ObjectMeta: api.ObjectMeta{ - Name: "myjob", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.JobSpec{ - Selector: validSelector, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"y": "z"}, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - }, - }, - "spec.template.spec.restartPolicy: Unsupported value": { - ObjectMeta: api.ObjectMeta{ - Name: "myjob", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.JobSpec{ - Selector: validSelector, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validSelector.MatchLabels, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - }, - }, - } - - for k, v := range errorCases { - errs := ValidateJob(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } else { - s := strings.Split(k, ":") - err := errs[0] - if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) { - t.Errorf("unexpected error: %v, expected: %s", err, k) - } - } - } -} - -type ingressRules map[string]string - -func TestValidateIngress(t *testing.T) { - defaultBackend := extensions.IngressBackend{ - ServiceName: "default-backend", - ServicePort: intstr.FromInt(80), - } - - newValid := func() extensions.Ingress { - return extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.IngressSpec{ - Backend: &extensions.IngressBackend{ - ServiceName: "default-backend", - ServicePort: intstr.FromInt(80), - }, - Rules: []extensions.IngressRule{ - { - Host: "foo.bar.com", - IngressRuleValue: extensions.IngressRuleValue{ - HTTP: &extensions.HTTPIngressRuleValue{ - Paths: []extensions.HTTPIngressPath{ - { - Path: "/foo", - Backend: defaultBackend, - }, - }, - }, - }, - }, - }, - }, - Status: extensions.IngressStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - {IP: "127.0.0.1"}, - }, - }, - }, - } - } - servicelessBackend := newValid() - servicelessBackend.Spec.Backend.ServiceName = "" - invalidNameBackend := newValid() - invalidNameBackend.Spec.Backend.ServiceName = "defaultBackend" - noPortBackend := newValid() - noPortBackend.Spec.Backend = &extensions.IngressBackend{ServiceName: defaultBackend.ServiceName} - noForwardSlashPath := newValid() - noForwardSlashPath.Spec.Rules[0].IngressRuleValue.HTTP.Paths = []extensions.HTTPIngressPath{ - { - Path: "invalid", - Backend: defaultBackend, - }, - } - noPaths := newValid() - noPaths.Spec.Rules[0].IngressRuleValue.HTTP.Paths = []extensions.HTTPIngressPath{} - badHost := newValid() - badHost.Spec.Rules[0].Host = "foobar:80" - badRegexPath := newValid() - badPathExpr := "/invalid[" - badRegexPath.Spec.Rules[0].IngressRuleValue.HTTP.Paths = []extensions.HTTPIngressPath{ - { - Path: badPathExpr, - Backend: defaultBackend, - }, - } - badPathErr := fmt.Sprintf("spec.rules[0].http.paths[0].path: Invalid value: '%v'", badPathExpr) - hostIP := "127.0.0.1" - badHostIP := newValid() - badHostIP.Spec.Rules[0].Host = hostIP - badHostIPErr := fmt.Sprintf("spec.rules[0].host: Invalid value: '%v'", hostIP) - noSecretName := newValid() - noSecretName.Spec.TLS = []extensions.IngressTLS{{SecretName: ""}} - - errorCases := map[string]extensions.Ingress{ - "spec.backend.serviceName: Required value": servicelessBackend, - "spec.backend.serviceName: Invalid value": invalidNameBackend, - "spec.backend.servicePort: Invalid value": noPortBackend, - "spec.rules[0].host: Invalid value": badHost, - "spec.rules[0].http.paths: Required value": noPaths, - "spec.rules[0].http.paths[0].path: Invalid value": noForwardSlashPath, - "spec.tls[0].secretName: Required value": noSecretName, - } - errorCases[badPathErr] = badRegexPath - errorCases[badHostIPErr] = badHostIP - - for k, v := range errorCases { - errs := ValidateIngress(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %q", k) - } else { - s := strings.Split(k, ":") - err := errs[0] - if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) { - t.Errorf("unexpected error: %q, expected: %q", err, k) - } - } - } -} - -func TestValidateIngressStatusUpdate(t *testing.T) { - defaultBackend := extensions.IngressBackend{ - ServiceName: "default-backend", - ServicePort: intstr.FromInt(80), - } - - newValid := func() extensions.Ingress { - return extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: api.NamespaceDefault, - ResourceVersion: "9", - }, - Spec: extensions.IngressSpec{ - Backend: &extensions.IngressBackend{ - ServiceName: "default-backend", - ServicePort: intstr.FromInt(80), - }, - Rules: []extensions.IngressRule{ - { - Host: "foo.bar.com", - IngressRuleValue: extensions.IngressRuleValue{ - HTTP: &extensions.HTTPIngressRuleValue{ - Paths: []extensions.HTTPIngressPath{ - { - Path: "/foo", - Backend: defaultBackend, - }, - }, - }, - }, - }, - }, - }, - Status: extensions.IngressStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - {IP: "127.0.0.1", Hostname: "foo.bar.com"}, - }, - }, - }, - } - } - oldValue := newValid() - newValue := newValid() - newValue.Status = extensions.IngressStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - {IP: "127.0.0.2", Hostname: "foo.com"}, - }, - }, - } - invalidIP := newValid() - invalidIP.Status = extensions.IngressStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - {IP: "abcd", Hostname: "foo.com"}, - }, - }, - } - invalidHostname := newValid() - invalidHostname.Status = extensions.IngressStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - {IP: "127.0.0.1", Hostname: "127.0.0.1"}, - }, - }, - } - - errs := ValidateIngressStatusUpdate(&newValue, &oldValue) - if len(errs) != 0 { - t.Errorf("Unexpected error %v", errs) - } - - errorCases := map[string]extensions.Ingress{ - "status.loadBalancer.ingress[0].ip: Invalid value": invalidIP, - "status.loadBalancer.ingress[0].hostname: Invalid value": invalidHostname, - } - for k, v := range errorCases { - errs := ValidateIngressStatusUpdate(&v, &oldValue) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } else { - s := strings.Split(k, ":") - err := errs[0] - if err.Field != s[0] || !strings.Contains(err.Error(), s[1]) { - t.Errorf("unexpected error: %q, expected: %q", err, k) - } - } - } -} - -func TestValidateClusterAutoscaler(t *testing.T) { - successCases := []extensions.ClusterAutoscaler{ - { - ObjectMeta: api.ObjectMeta{ - Name: "ClusterAutoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ClusterAutoscalerSpec{ - MinNodes: 1, - MaxNodes: 5, - TargetUtilization: []extensions.NodeUtilization{ - { - Resource: extensions.CpuRequest, - Value: 0.7, - }, - }, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateClusterAutoscaler(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]extensions.ClusterAutoscaler{ - "must be 'ClusterAutoscaler'": { - ObjectMeta: api.ObjectMeta{ - Name: "TestClusterAutoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ClusterAutoscalerSpec{ - MinNodes: 1, - MaxNodes: 5, - TargetUtilization: []extensions.NodeUtilization{ - { - Resource: extensions.CpuRequest, - Value: 0.7, - }, - }, - }, - }, - "must be 'default'": { - ObjectMeta: api.ObjectMeta{ - Name: "ClusterAutoscaler", - Namespace: "test", - }, - Spec: extensions.ClusterAutoscalerSpec{ - MinNodes: 1, - MaxNodes: 5, - TargetUtilization: []extensions.NodeUtilization{ - { - Resource: extensions.CpuRequest, - Value: 0.7, - }, - }, - }, - }, - - `must be greater than or equal to 0`: { - ObjectMeta: api.ObjectMeta{ - Name: "ClusterAutoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ClusterAutoscalerSpec{ - MinNodes: -1, - MaxNodes: 5, - TargetUtilization: []extensions.NodeUtilization{ - { - Resource: extensions.CpuRequest, - Value: 0.7, - }, - }, - }, - }, - "must be greater than or equal to `minNodes`": { - ObjectMeta: api.ObjectMeta{ - Name: "ClusterAutoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ClusterAutoscalerSpec{ - MinNodes: 10, - MaxNodes: 5, - TargetUtilization: []extensions.NodeUtilization{ - { - Resource: extensions.CpuRequest, - Value: 0.7, - }, - }, - }, - }, - "Required value": { - ObjectMeta: api.ObjectMeta{ - Name: "ClusterAutoscaler", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ClusterAutoscalerSpec{ - MinNodes: 1, - MaxNodes: 5, - TargetUtilization: []extensions.NodeUtilization{}, - }, - }, - } - - for k, v := range errorCases { - errs := ValidateClusterAutoscaler(&v) - if len(errs) == 0 { - t.Errorf("[%s] expected failure", k) - } else if !strings.Contains(errs[0].Error(), k) { - t.Errorf("unexpected error: %v, expected: %q", errs[0], k) - } - } -} - -func TestValidateScale(t *testing.T) { - successCases := []extensions.Scale{ - { - ObjectMeta: api.ObjectMeta{ - Name: "frontend", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ScaleSpec{ - Replicas: 1, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "frontend", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ScaleSpec{ - Replicas: 10, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "frontend", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ScaleSpec{ - Replicas: 0, - }, - }, - } - - for _, successCase := range successCases { - if errs := ValidateScale(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []struct { - scale extensions.Scale - msg string - }{ - { - scale: extensions.Scale{ - ObjectMeta: api.ObjectMeta{ - Name: "frontend", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ScaleSpec{ - Replicas: -1, - }, - }, - msg: "must be greater than or equal to 0", - }, - } - - for _, c := range errorCases { - if errs := ValidateScale(&c.scale); len(errs) == 0 { - t.Errorf("expected failure for %s", c.msg) - } else if !strings.Contains(errs[0].Error(), c.msg) { - t.Errorf("unexpected error: %v, expected: %s", errs[0], c.msg) - } - } -} - -func TestValidateReplicaSetStatusUpdate(t *testing.T) { - validLabels := map[string]string{"a": "b"} - validPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validLabels, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - type rcUpdateTest struct { - old extensions.ReplicaSet - update extensions.ReplicaSet - } - successCases := []rcUpdateTest{ - { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - Status: extensions.ReplicaSetStatus{ - Replicas: 2, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 3, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - Status: extensions.ReplicaSetStatus{ - Replicas: 4, - }, - }, - }, - } - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateReplicaSetStatusUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]rcUpdateTest{ - "negative replicas": { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - Status: extensions.ReplicaSetStatus{ - Replicas: 3, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - Status: extensions.ReplicaSetStatus{ - Replicas: -3, - }, - }, - }, - } - for testName, errorCase := range errorCases { - if errs := ValidateReplicaSetStatusUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } - -} - -func TestValidateReplicaSetUpdate(t *testing.T) { - validLabels := map[string]string{"a": "b"} - validPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validLabels, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - readWriteVolumePodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validLabels, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}}, - }, - }, - } - invalidLabels := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - invalidPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - ObjectMeta: api.ObjectMeta{ - Labels: invalidLabels, - }, - }, - } - type rcUpdateTest struct { - old extensions.ReplicaSet - update extensions.ReplicaSet - } - successCases := []rcUpdateTest{ - { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 3, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - }, - { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 1, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - }, - } - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateReplicaSetUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]rcUpdateTest{ - "more than one read/write": { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - }, - "invalid selector": { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Selector: &unversioned.LabelSelector{MatchLabels: invalidLabels}, - Template: &validPodTemplate.Template, - }, - }, - }, - "invalid pod": { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &invalidPodTemplate.Template, - }, - }, - }, - "negative replicas": { - old: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - update: extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: -1, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - }, - } - for testName, errorCase := range errorCases { - if errs := ValidateReplicaSetUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } -} - -func TestValidateReplicaSet(t *testing.T) { - validLabels := map[string]string{"a": "b"} - validPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validLabels, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - readWriteVolumePodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: validLabels, - }, - Spec: api.PodSpec{ - Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}}, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - }, - } - invalidLabels := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - invalidPodTemplate := api.PodTemplate{ - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - }, - ObjectMeta: api.ObjectMeta{ - Labels: invalidLabels, - }, - }, - } - successCases := []extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 1, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateReplicaSet(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]extensions.ReplicaSet{ - "zero-length ID": { - ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - "missing-namespace": { - ObjectMeta: api.ObjectMeta{Name: "abc-123"}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - "empty selector": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Template: &validPodTemplate.Template, - }, - }, - "selector_doesnt_match": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - Template: &validPodTemplate.Template, - }, - }, - "invalid manifest": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - }, - }, - "read-write persistent disk with > 1 pod": { - ObjectMeta: api.ObjectMeta{Name: "abc"}, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - "negative_replicas": { - ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault}, - Spec: extensions.ReplicaSetSpec{ - Replicas: -1, - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - }, - }, - "invalid_label": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - "invalid_label 2": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Template: &invalidPodTemplate.Template, - }, - }, - "invalid_annotation": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - Annotations: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &validPodTemplate.Template, - }, - }, - "invalid restart policy 1": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - ObjectMeta: api.ObjectMeta{ - Labels: validLabels, - }, - }, - }, - }, - "invalid restart policy 2": { - ObjectMeta: api.ObjectMeta{ - Name: "abc-123", - Namespace: api.NamespaceDefault, - }, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: validLabels}, - Template: &api.PodTemplateSpec{ - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyNever, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, - }, - ObjectMeta: api.ObjectMeta{ - Labels: validLabels, - }, - }, - }, - }, - } - for k, v := range errorCases { - errs := ValidateReplicaSet(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - field := errs[i].Field - if !strings.HasPrefix(field, "spec.template.") && - field != "metadata.name" && - field != "metadata.namespace" && - field != "spec.selector" && - field != "spec.template" && - field != "GCEPersistentDisk.ReadOnly" && - field != "spec.replicas" && - field != "spec.template.labels" && - field != "metadata.annotations" && - field != "metadata.labels" && - field != "status.replicas" { - t.Errorf("%s: missing prefix for: %v", k, errs[i]) - } - } - } -} - -func newInt(val int) *int { - p := new(int) - *p = val - return p -} - -func TestValidatePodSecurityPolicy(t *testing.T) { - validSCC := func() *extensions.PodSecurityPolicy { - return &extensions.PodSecurityPolicy{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: extensions.PodSecurityPolicySpec{ - SELinuxContext: extensions.SELinuxContextStrategyOptions{ - Type: extensions.SELinuxStrategyRunAsAny, - }, - RunAsUser: extensions.RunAsUserStrategyOptions{ - Type: extensions.RunAsUserStrategyRunAsAny, - }, - }, - } - } - - noUserOptions := validSCC() - noUserOptions.Spec.RunAsUser.Type = "" - - noSELinuxOptions := validSCC() - noSELinuxOptions.Spec.SELinuxContext.Type = "" - - invalidUserStratType := validSCC() - invalidUserStratType.Spec.RunAsUser.Type = "invalid" - - invalidSELinuxStratType := validSCC() - invalidSELinuxStratType.Spec.SELinuxContext.Type = "invalid" - - missingObjectMetaName := validSCC() - missingObjectMetaName.ObjectMeta.Name = "" - - invalidRangeMinGreaterThanMax := validSCC() - invalidRangeMinGreaterThanMax.Spec.RunAsUser.Ranges = []extensions.IDRange{ - {Min: 2, Max: 1}, - } - - invalidRangeNegativeMin := validSCC() - invalidRangeNegativeMin.Spec.RunAsUser.Ranges = []extensions.IDRange{ - {Min: -1, Max: 10}, - } - - invalidRangeNegativeMax := validSCC() - invalidRangeNegativeMax.Spec.RunAsUser.Ranges = []extensions.IDRange{ - {Min: 1, Max: -10}, - } - - errorCases := map[string]struct { - scc *extensions.PodSecurityPolicy - errorDetail string - }{ - "no user options": { - scc: noUserOptions, - errorDetail: "supported values: MustRunAs, MustRunAsNonRoot, RunAsAny", - }, - "no selinux options": { - scc: noSELinuxOptions, - errorDetail: "supported values: MustRunAs, RunAsAny", - }, - "invalid user strategy type": { - scc: invalidUserStratType, - errorDetail: "supported values: MustRunAs, MustRunAsNonRoot, RunAsAny", - }, - "invalid selinux strategy type": { - scc: invalidSELinuxStratType, - errorDetail: "supported values: MustRunAs, RunAsAny", - }, - "missing object meta name": { - scc: missingObjectMetaName, - errorDetail: "name or generateName is required", - }, - "invalid range min greater than max": { - scc: invalidRangeMinGreaterThanMax, - errorDetail: "min cannot be greater than max", - }, - "invalid range negative min": { - scc: invalidRangeNegativeMin, - errorDetail: "min cannot be negative", - }, - "invalid range negative max": { - scc: invalidRangeNegativeMax, - errorDetail: "max cannot be negative", - }, - } - - for k, v := range errorCases { - if errs := ValidatePodSecurityPolicy(v.scc); len(errs) == 0 || errs[0].Detail != v.errorDetail { - t.Errorf("Expected error with detail %s for %s, got %v", v.errorDetail, k, errs[0].Detail) - } - } - - mustRunAs := validSCC() - mustRunAs.Spec.RunAsUser.Type = extensions.RunAsUserStrategyMustRunAs - mustRunAs.Spec.RunAsUser.Ranges = []extensions.IDRange{ - { - Min: 1, - Max: 1, - }, - } - mustRunAs.Spec.SELinuxContext.Type = extensions.SELinuxStrategyMustRunAs - - runAsNonRoot := validSCC() - runAsNonRoot.Spec.RunAsUser.Type = extensions.RunAsUserStrategyMustRunAsNonRoot - - successCases := map[string]struct { - scc *extensions.PodSecurityPolicy - }{ - "must run as": { - scc: mustRunAs, - }, - "run as any": { - scc: validSCC(), - }, - "run as non-root (user only)": { - scc: runAsNonRoot, - }, - } - - for k, v := range successCases { - if errs := ValidatePodSecurityPolicy(v.scc); len(errs) != 0 { - t.Errorf("Expected success for %s, got %v", k, errs) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/delta_fifo_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/delta_fifo_test.go deleted file mode 100644 index 8efd982b5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/delta_fifo_test.go +++ /dev/null @@ -1,385 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cache - -import ( - "reflect" - "testing" - "time" -) - -// helper function to reduce stuttering -func testPop(f *DeltaFIFO) testFifoObject { - return f.Pop().(Deltas).Newest().Object.(testFifoObject) -} - -// keyLookupFunc adapts a raw function to be a KeyLookup. -type keyLookupFunc func() []string - -// ListKeys just calls kl. -func (kl keyLookupFunc) ListKeys() []string { - return kl() -} - -// GetByKey returns the key if it exists in the list returned by kl. -func (kl keyLookupFunc) GetByKey(key string) (interface{}, bool, error) { - for _, v := range kl() { - if v == key { - return key, true, nil - } - } - return nil, false, nil -} - -func TestDeltaFIFO_basic(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil, nil) - const amount = 500 - go func() { - for i := 0; i < amount; i++ { - f.Add(mkFifoObj(string([]rune{'a', rune(i)}), i+1)) - } - }() - go func() { - for u := uint64(0); u < amount; u++ { - f.Add(mkFifoObj(string([]rune{'b', rune(u)}), u+1)) - } - }() - - lastInt := int(0) - lastUint := uint64(0) - for i := 0; i < amount*2; i++ { - switch obj := testPop(f).val.(type) { - case int: - if obj <= lastInt { - t.Errorf("got %v (int) out of order, last was %v", obj, lastInt) - } - lastInt = obj - case uint64: - if obj <= lastUint { - t.Errorf("got %v (uint) out of order, last was %v", obj, lastUint) - } else { - lastUint = obj - } - default: - t.Fatalf("unexpected type %#v", obj) - } - } -} - -func TestDeltaFIFO_compressorWorks(t *testing.T) { - oldestTypes := []DeltaType{} - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - // This function just keeps the most recent delta - // and puts deleted ones in the list. - DeltaCompressorFunc(func(d Deltas) Deltas { - if n := len(d); n > 1 { - oldestTypes = append(oldestTypes, d[0].Type) - d = d[1:] - } - return d - }), - nil, - ) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("foo", 12)) - f.Replace([]interface{}{mkFifoObj("foo", 20)}, "0") - f.Delete(mkFifoObj("foo", 22)) - f.Add(mkFifoObj("foo", 25)) // flush the last one out - expect := []DeltaType{Added, Updated, Sync, Deleted} - if e, a := expect, oldestTypes; !reflect.DeepEqual(e, a) { - t.Errorf("Expected %#v, got %#v", e, a) - } - if e, a := (Deltas{{Added, mkFifoObj("foo", 25)}}), f.Pop().(Deltas); !reflect.DeepEqual(e, a) { - t.Fatalf("Expected %#v, got %#v", e, a) - } - -} - -func TestDeltaFIFO_addUpdate(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil, nil) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("foo", 12)) - f.Delete(mkFifoObj("foo", 15)) - - if e, a := []interface{}{mkFifoObj("foo", 15)}, f.List(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - if e, a := []string{"foo"}, f.ListKeys(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - - got := make(chan testFifoObject, 2) - go func() { - for { - obj := f.Pop().(Deltas).Newest().Object.(testFifoObject) - t.Logf("got a thing %#v", obj) - t.Logf("D len: %v", len(f.queue)) - got <- obj - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestDeltaFIFO_enqueueingNoLister(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil, nil) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("bar", 15)) - f.Add(mkFifoObj("qux", 17)) - f.Delete(mkFifoObj("qux", 18)) - - // This delete does not enqueue anything because baz doesn't exist. - f.Delete(mkFifoObj("baz", 20)) - - expectList := []int{10, 15, 18} - for _, expect := range expectList { - if e, a := expect, testPop(f).val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - } - if e, a := 0, len(f.items); e != a { - t.Errorf("queue unexpectedly not empty: %v != %v\n%#v", e, a, f.items) - } -} - -func TestDeltaFIFO_enqueueingWithLister(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - nil, - keyLookupFunc(func() []string { - return []string{"foo", "bar", "baz"} - }), - ) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("bar", 15)) - - // This delete does enqueue the deletion, because "baz" is in the key lister. - f.Delete(mkFifoObj("baz", 20)) - - expectList := []int{10, 15, 20} - for _, expect := range expectList { - if e, a := expect, testPop(f).val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - } - if e, a := 0, len(f.items); e != a { - t.Errorf("queue unexpectedly not empty: %v != %v", e, a) - } -} - -func TestDeltaFIFO_addReplace(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil, nil) - f.Add(mkFifoObj("foo", 10)) - f.Replace([]interface{}{mkFifoObj("foo", 15)}, "0") - got := make(chan testFifoObject, 2) - go func() { - for { - got <- testPop(f) - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestDeltaFIFO_ReplaceMakesDeletions(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - nil, - keyLookupFunc(func() []string { - return []string{"foo", "bar", "baz"} - }), - ) - f.Delete(mkFifoObj("baz", 10)) - f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") - - expectedList := []Deltas{ - {{Deleted, mkFifoObj("baz", 10)}}, - {{Sync, mkFifoObj("foo", 5)}}, - // Since "bar" didn't have a delete event and wasn't in the Replace list - // it should get a tombstone key with the right Obj. - {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: "bar"}}}, - } - - for _, expected := range expectedList { - cur := f.Pop().(Deltas) - if e, a := expected, cur; !reflect.DeepEqual(e, a) { - t.Errorf("Expected %#v, got %#v", e, a) - } - } -} - -func TestDeltaFIFO_detectLineJumpers(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil, nil) - - f.Add(mkFifoObj("foo", 10)) - f.Add(mkFifoObj("bar", 1)) - f.Add(mkFifoObj("foo", 11)) - f.Add(mkFifoObj("foo", 13)) - f.Add(mkFifoObj("zab", 30)) - - if e, a := 13, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - f.Add(mkFifoObj("foo", 14)) // ensure foo doesn't jump back in line - - if e, a := 1, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 30, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 14, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } -} - -func TestDeltaFIFO_addIfNotPresent(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil, nil) - - f.Add(mkFifoObj("b", 3)) - b3 := f.Pop() - f.Add(mkFifoObj("c", 4)) - c4 := f.Pop() - if e, a := 0, len(f.items); e != a { - t.Fatalf("Expected %v, got %v items in queue", e, a) - } - - f.Add(mkFifoObj("a", 1)) - f.Add(mkFifoObj("b", 2)) - f.AddIfNotPresent(b3) - f.AddIfNotPresent(c4) - - if e, a := 3, len(f.items); a != e { - t.Fatalf("expected queue length %d, got %d", e, a) - } - - expectedValues := []int{1, 2, 4} - for _, expected := range expectedValues { - if actual := testPop(f).val; actual != expected { - t.Fatalf("expected value %d, got %d", expected, actual) - } - } -} - -func TestDeltaFIFO_KeyOf(t *testing.T) { - f := DeltaFIFO{keyFunc: testFifoObjectKeyFunc} - - table := []struct { - obj interface{} - key string - }{ - {obj: testFifoObject{name: "A"}, key: "A"}, - {obj: DeletedFinalStateUnknown{Key: "B", Obj: nil}, key: "B"}, - {obj: Deltas{{Object: testFifoObject{name: "C"}}}, key: "C"}, - {obj: Deltas{{Object: DeletedFinalStateUnknown{Key: "D", Obj: nil}}}, key: "D"}, - } - - for _, item := range table { - got, err := f.KeyOf(item.obj) - if err != nil { - t.Errorf("Unexpected error for %q: %v", item.obj, err) - continue - } - if e, a := item.key, got; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } -} - -func TestDeltaFIFO_HasSynced(t *testing.T) { - tests := []struct { - actions []func(f *DeltaFIFO) - expectedSynced bool - }{ - { - actions: []func(f *DeltaFIFO){}, - expectedSynced: false, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Add(mkFifoObj("a", 1)) }, - }, - expectedSynced: true, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{}, "0") }, - }, - expectedSynced: true, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - }, - expectedSynced: false, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *DeltaFIFO) { f.Pop() }, - }, - expectedSynced: false, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *DeltaFIFO) { f.Pop() }, - func(f *DeltaFIFO) { f.Pop() }, - }, - expectedSynced: true, - }, - } - - for i, test := range tests { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil, nil) - - for _, action := range test.actions { - action(f) - } - if e, a := test.expectedSynced, f.HasSynced(); a != e { - t.Errorf("test case %v failed, expected: %v , got %v", i, e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go index 5eb996b66..964deda07 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go @@ -17,11 +17,11 @@ limitations under the License. package cache import ( + "sync" "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/runtime" ) // ExpirationCache implements the store interface @@ -29,12 +29,20 @@ import ( // a. The key is computed based off the original item/keyFunc // b. The value inserted under that key is the timestamped item // 2. Expiration happens lazily on read based on the expiration policy +// a. No item can be inserted into the store while we're expiring +// *any* item in the cache. // 3. Time-stamps are stripped off unexpired entries before return +// Note that the ExpirationCache is inherently slower than a normal +// threadSafeStore because it takes a write lock every time it checks if +// an item has expired. type ExpirationCache struct { cacheStorage ThreadSafeStore keyFunc KeyFunc clock util.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 + expirationLock sync.Mutex } // ExpirationPolicy dictates when an object expires. Currently only abstracted out @@ -68,7 +76,6 @@ type timestampedEntry struct { // getTimestampedEntry returnes the timestampedEntry stored under the given key. func (c *ExpirationCache) getTimestampedEntry(key string) (*timestampedEntry, bool) { item, _ := c.cacheStorage.Get(key) - // TODO: Check the cast instead if tsEntry, ok := item.(*timestampedEntry); ok { return tsEntry, true } @@ -76,24 +83,20 @@ func (c *ExpirationCache) getTimestampedEntry(key string) (*timestampedEntry, bo } // getOrExpire retrieves the object from the timestampedEntry if and only if it hasn't -// already expired. It kicks-off a go routine to delete expired objects from -// the store and sets exists=false. +// already expired. It holds a write lock across deletion. func (c *ExpirationCache) getOrExpire(key string) (interface{}, bool) { + // Prevent all inserts from the time we deem an item as "expired" to when we + // delete it, so an un-expired item doesn't sneak in under the same key, just + // before the Delete. + c.expirationLock.Lock() + defer c.expirationLock.Unlock() timestampedItem, exists := c.getTimestampedEntry(key) if !exists { return nil, false } if c.expirationPolicy.IsExpired(timestampedItem) { glog.V(4).Infof("Entry %v: %+v has expired", key, timestampedItem.obj) - // Since expiration happens lazily on read, don't hold up - // the reader trying to acquire a write lock for the delete. - // The next reader will retry the delete even if this one - // fails; as long as we only return un-expired entries a - // reader doesn't need to wait for the result of the delete. - go func() { - defer runtime.HandleCrash() - c.cacheStorage.Delete(key) - }() + c.cacheStorage.Delete(key) return nil, false } return timestampedItem.obj, true @@ -141,6 +144,8 @@ func (c *ExpirationCache) ListKeys() []string { // Add timestamps an item and inserts it into the cache, overwriting entries // that might exist under the same key. func (c *ExpirationCache) Add(obj interface{}) error { + c.expirationLock.Lock() + defer c.expirationLock.Unlock() key, err := c.keyFunc(obj) if err != nil { return KeyError{obj, err} @@ -157,6 +162,8 @@ func (c *ExpirationCache) Update(obj interface{}) error { // Delete removes an item from the cache. func (c *ExpirationCache) Delete(obj interface{}) error { + c.expirationLock.Lock() + defer c.expirationLock.Unlock() key, err := c.keyFunc(obj) if err != nil { return KeyError{obj, err} @@ -169,6 +176,8 @@ func (c *ExpirationCache) Delete(obj interface{}) error { // before attempting the replace operation. The replace operation will // delete the contents of the ExpirationCache `c`. func (c *ExpirationCache) Replace(list []interface{}, resourceVersion string) error { + c.expirationLock.Lock() + defer c.expirationLock.Unlock() items := map[string]interface{}{} ts := c.clock.Now() for _, item := range list { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go index 2e9a25d12..3b9597705 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go @@ -28,6 +28,7 @@ type fakeThreadSafeMap struct { func (c *fakeThreadSafeMap) Delete(key string) { if c.deletedKeys != nil { + c.ThreadSafeStore.Delete(key) c.deletedKeys <- key } } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache_test.go deleted file mode 100644 index 2e8cc5b57..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/expiration_cache_test.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cache - -import ( - "reflect" - "testing" - "time" - - "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/sets" - "k8s.io/kubernetes/pkg/util/wait" -) - -func TestTTLExpirationBasic(t *testing.T) { - testObj := testStoreObject{id: "foo", val: "bar"} - deleteChan := make(chan string) - ttlStore := NewFakeExpirationStore( - testStoreKeyFunc, deleteChan, - &FakeExpirationPolicy{ - NeverExpire: sets.NewString(), - RetrieveKeyFunc: func(obj interface{}) (string, error) { - return obj.(*timestampedEntry).obj.(testStoreObject).id, nil - }, - }, - util.RealClock{}, - ) - err := ttlStore.Add(testObj) - if err != nil { - t.Errorf("Unable to add obj %#v", testObj) - } - item, exists, err := ttlStore.Get(testObj) - if err != nil { - t.Errorf("Failed to get from store, %v", err) - } - if exists || item != nil { - t.Errorf("Got unexpected item %#v", item) - } - key, _ := testStoreKeyFunc(testObj) - select { - case delKey := <-deleteChan: - if delKey != key { - t.Errorf("Unexpected delete for key %s", key) - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("Unexpected timeout waiting on delete") - } - close(deleteChan) -} - -func TestTTLList(t *testing.T) { - testObjs := []testStoreObject{ - {id: "foo", val: "bar"}, - {id: "foo1", val: "bar1"}, - {id: "foo2", val: "bar2"}, - } - expireKeys := sets.NewString(testObjs[0].id, testObjs[2].id) - deleteChan := make(chan string) - defer close(deleteChan) - - ttlStore := NewFakeExpirationStore( - testStoreKeyFunc, deleteChan, - &FakeExpirationPolicy{ - NeverExpire: sets.NewString(testObjs[1].id), - RetrieveKeyFunc: func(obj interface{}) (string, error) { - return obj.(*timestampedEntry).obj.(testStoreObject).id, nil - }, - }, - util.RealClock{}, - ) - for _, obj := range testObjs { - err := ttlStore.Add(obj) - if err != nil { - t.Errorf("Unable to add obj %#v", obj) - } - } - listObjs := ttlStore.List() - if len(listObjs) != 1 || !reflect.DeepEqual(listObjs[0], testObjs[1]) { - t.Errorf("List returned unexpected results %#v", listObjs) - } - - // Make sure all our deletes come through in an acceptable rate (1/100ms) - for expireKeys.Len() != 0 { - select { - case delKey := <-deleteChan: - if !expireKeys.Has(delKey) { - t.Errorf("Unexpected delete for key %s", delKey) - } - expireKeys.Delete(delKey) - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("Unexpected timeout waiting on delete") - return - } - } -} - -func TestTTLPolicy(t *testing.T) { - fakeTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - ttl := 30 * time.Second - exactlyOnTTL := fakeTime.Add(-ttl) - expiredTime := fakeTime.Add(-(ttl + 1)) - - policy := TTLPolicy{ttl, util.NewFakeClock(fakeTime)} - fakeTimestampedEntry := ×tampedEntry{obj: struct{}{}, timestamp: exactlyOnTTL} - if policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL cache should not expire entries exactly on ttl") - } - fakeTimestampedEntry.timestamp = fakeTime - if policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL Cache should not expire entries before ttl") - } - fakeTimestampedEntry.timestamp = expiredTime - if !policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL Cache should expire entries older than ttl") - } - for _, ttl = range []time.Duration{0, -1} { - policy.Ttl = ttl - if policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL policy should only expire entries when initialized with a ttl > 0") - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/fifo_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/fifo_test.go deleted file mode 100644 index 974fa6d3b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/fifo_test.go +++ /dev/null @@ -1,235 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cache - -import ( - "reflect" - "testing" - "time" -) - -func testFifoObjectKeyFunc(obj interface{}) (string, error) { - return obj.(testFifoObject).name, nil -} - -type testFifoObject struct { - name string - val interface{} -} - -func mkFifoObj(name string, val interface{}) testFifoObject { - return testFifoObject{name: name, val: val} -} - -func TestFIFO_basic(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - const amount = 500 - go func() { - for i := 0; i < amount; i++ { - f.Add(mkFifoObj(string([]rune{'a', rune(i)}), i+1)) - } - }() - go func() { - for u := uint64(0); u < amount; u++ { - f.Add(mkFifoObj(string([]rune{'b', rune(u)}), u+1)) - } - }() - - lastInt := int(0) - lastUint := uint64(0) - for i := 0; i < amount*2; i++ { - switch obj := f.Pop().(testFifoObject).val.(type) { - case int: - if obj <= lastInt { - t.Errorf("got %v (int) out of order, last was %v", obj, lastInt) - } - lastInt = obj - case uint64: - if obj <= lastUint { - t.Errorf("got %v (uint) out of order, last was %v", obj, lastUint) - } else { - lastUint = obj - } - default: - t.Fatalf("unexpected type %#v", obj) - } - } -} - -func TestFIFO_addUpdate(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("foo", 15)) - - if e, a := []interface{}{mkFifoObj("foo", 15)}, f.List(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - if e, a := []string{"foo"}, f.ListKeys(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - - got := make(chan testFifoObject, 2) - go func() { - for { - got <- f.Pop().(testFifoObject) - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestFIFO_addReplace(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - f.Add(mkFifoObj("foo", 10)) - f.Replace([]interface{}{mkFifoObj("foo", 15)}, "15") - got := make(chan testFifoObject, 2) - go func() { - for { - got <- f.Pop().(testFifoObject) - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestFIFO_detectLineJumpers(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - - f.Add(mkFifoObj("foo", 10)) - f.Add(mkFifoObj("bar", 1)) - f.Add(mkFifoObj("foo", 11)) - f.Add(mkFifoObj("foo", 13)) - f.Add(mkFifoObj("zab", 30)) - - if e, a := 13, f.Pop().(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - f.Add(mkFifoObj("foo", 14)) // ensure foo doesn't jump back in line - - if e, a := 1, f.Pop().(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 30, f.Pop().(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 14, f.Pop().(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } -} - -func TestFIFO_addIfNotPresent(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - - f.Add(mkFifoObj("a", 1)) - f.Add(mkFifoObj("b", 2)) - f.AddIfNotPresent(mkFifoObj("b", 3)) - f.AddIfNotPresent(mkFifoObj("c", 4)) - - if e, a := 3, len(f.items); a != e { - t.Fatalf("expected queue length %d, got %d", e, a) - } - - expectedValues := []int{1, 2, 4} - for _, expected := range expectedValues { - if actual := f.Pop().(testFifoObject).val; actual != expected { - t.Fatalf("expected value %d, got %d", expected, actual) - } - } -} - -func TestFIFO_HasSynced(t *testing.T) { - tests := []struct { - actions []func(f *FIFO) - expectedSynced bool - }{ - { - actions: []func(f *FIFO){}, - expectedSynced: false, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Add(mkFifoObj("a", 1)) }, - }, - expectedSynced: true, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{}, "0") }, - }, - expectedSynced: true, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - }, - expectedSynced: false, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *FIFO) { f.Pop() }, - }, - expectedSynced: false, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *FIFO) { f.Pop() }, - func(f *FIFO) { f.Pop() }, - }, - expectedSynced: true, - }, - } - - for i, test := range tests { - f := NewFIFO(testFifoObjectKeyFunc) - - for _, action := range test.actions { - action(f) - } - if e, a := test.expectedSynced, f.HasSynced(); a != e { - t.Errorf("test case %v failed, expected: %v , got %v", i, e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/index_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/index_test.go deleted file mode 100644 index 4b0d5ff4f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/index_test.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cache - -import ( - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -func testIndexFunc(obj interface{}) ([]string, error) { - pod := obj.(*api.Pod) - return []string{pod.Labels["foo"]}, nil -} - -func TestGetIndexFuncValues(t *testing.T) { - index := NewIndexer(MetaNamespaceKeyFunc, Indexers{"testmodes": testIndexFunc}) - - pod1 := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "one", Labels: map[string]string{"foo": "bar"}}} - pod2 := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "two", Labels: map[string]string{"foo": "bar"}}} - pod3 := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "tre", Labels: map[string]string{"foo": "biz"}}} - - index.Add(pod1) - index.Add(pod2) - index.Add(pod3) - - keys := index.ListIndexFuncValues("testmodes") - if len(keys) != 2 { - t.Errorf("Expected 2 keys but got %v", len(keys)) - } - - for _, key := range keys { - if key != "bar" && key != "biz" { - t.Errorf("Expected only 'bar' or 'biz' but got %s", key) - } - } -} - -func testUsersIndexFunc(obj interface{}) ([]string, error) { - pod := obj.(*api.Pod) - usersString := pod.Annotations["users"] - - return strings.Split(usersString, ","), nil -} - -func TestMultiIndexKeys(t *testing.T) { - index := NewIndexer(MetaNamespaceKeyFunc, Indexers{"byUser": testUsersIndexFunc}) - - pod1 := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "one", Annotations: map[string]string{"users": "ernie,bert"}}} - pod2 := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "two", Annotations: map[string]string{"users": "bert,oscar"}}} - pod3 := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "tre", Annotations: map[string]string{"users": "ernie,elmo"}}} - - index.Add(pod1) - index.Add(pod2) - index.Add(pod3) - - erniePods, err := index.ByIndex("byUser", "ernie") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(erniePods) != 2 { - t.Errorf("Expected 2 pods but got %v", len(erniePods)) - } - - bertPods, err := index.ByIndex("byUser", "bert") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(bertPods) != 2 { - t.Errorf("Expected 2 pods but got %v", len(bertPods)) - } - - oscarPods, err := index.ByIndex("byUser", "oscar") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(oscarPods) != 1 { - t.Errorf("Expected 1 pods but got %v", len(erniePods)) - } - - ernieAndBertKeys, err := index.Index("byUser", pod1) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(ernieAndBertKeys) != 3 { - t.Errorf("Expected 3 pods but got %v", len(ernieAndBertKeys)) - } - - index.Delete(pod3) - erniePods, err = index.ByIndex("byUser", "ernie") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(erniePods) != 1 { - t.Errorf("Expected 1 pods but got %v", len(erniePods)) - } - elmoPods, err := index.ByIndex("byUser", "elmo") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(elmoPods) != 0 { - t.Errorf("Expected 0 pods but got %v", len(elmoPods)) - } - - obj, err := api.Scheme.DeepCopy(pod2) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - copyOfPod2 := obj.(*api.Pod) - copyOfPod2.Annotations["users"] = "oscar" - index.Update(copyOfPod2) - bertPods, err = index.ByIndex("byUser", "bert") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(bertPods) != 1 { - t.Errorf("Expected 1 pods but got %v", len(bertPods)) - } - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listers_test.go deleted file mode 100644 index e95df1f21..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listers_test.go +++ /dev/null @@ -1,721 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cache - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/util/sets" -) - -func TestStoreToNodeLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - ids := sets.NewString("foo", "bar", "baz") - for id := range ids { - store.Add(&api.Node{ObjectMeta: api.ObjectMeta{Name: id}}) - } - sml := StoreToNodeLister{store} - - gotNodes, err := sml.List() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - got := make([]string, len(gotNodes.Items)) - for ix := range gotNodes.Items { - got[ix] = gotNodes.Items[ix].Name - } - if !ids.HasAll(got...) || len(got) != len(ids) { - t.Errorf("Expected %v, got %v", ids, got) - } -} - -func TestStoreToNodeConditionLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - nodes := []*api.Node{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ - { - Type: api.NodeReady, - Status: api.ConditionTrue, - }, - { - Type: api.NodeOutOfDisk, - Status: api.ConditionFalse, - }, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar"}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ - { - Type: api.NodeOutOfDisk, - Status: api.ConditionTrue, - }, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "baz"}, - Status: api.NodeStatus{ - Conditions: []api.NodeCondition{ - { - Type: api.NodeReady, - Status: api.ConditionFalse, - }, - { - Type: api.NodeOutOfDisk, - Status: api.ConditionUnknown, - }, - }, - }, - }, - } - for _, n := range nodes { - store.Add(n) - } - - predicate := func(node api.Node) bool { - for _, cond := range node.Status.Conditions { - if cond.Type == api.NodeOutOfDisk && cond.Status == api.ConditionTrue { - return false - } - } - return true - } - - snl := StoreToNodeLister{store} - sncl := snl.NodeCondition(predicate) - - want := sets.NewString("foo", "baz") - gotNodes, err := sncl.List() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - got := make([]string, len(gotNodes.Items)) - for ix := range gotNodes.Items { - got[ix] = gotNodes.Items[ix].Name - } - if !want.HasAll(got...) || len(got) != len(want) { - t.Errorf("Expected %v, got %v", want, got) - } -} - -func TestStoreToReplicationControllerLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - lister := StoreToReplicationControllerLister{store} - testCases := []struct { - inRCs []*api.ReplicationController - list func() ([]api.ReplicationController, error) - outRCNames sets.String - expectErr bool - }{ - // Basic listing with all labels and no selectors - { - inRCs: []*api.ReplicationController{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, - }, - list: func() ([]api.ReplicationController, error) { - return lister.List() - }, - outRCNames: sets.NewString("basic"), - }, - // No pod labels - { - inRCs: []*api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{"foo": "baz"}, - }, - }, - }, - list: func() ([]api.ReplicationController, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "pod1", Namespace: "ns"}, - } - return lister.GetPodControllers(pod) - }, - outRCNames: sets.NewString(), - expectErr: true, - }, - // No RC selectors - { - inRCs: []*api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - }, - }, - list: func() ([]api.ReplicationController, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod1", - Namespace: "ns", - Labels: map[string]string{"foo": "bar"}, - }, - } - return lister.GetPodControllers(pod) - }, - outRCNames: sets.NewString(), - expectErr: true, - }, - // Matching labels to selectors and namespace - { - inRCs: []*api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{"foo": "bar"}, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{"foo": "bar"}, - }, - }, - }, - list: func() ([]api.ReplicationController, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod1", - Labels: map[string]string{"foo": "bar"}, - Namespace: "ns", - }, - } - return lister.GetPodControllers(pod) - }, - outRCNames: sets.NewString("bar"), - }, - } - for _, c := range testCases { - for _, r := range c.inRCs { - store.Add(r) - } - - gotControllers, err := c.list() - if err != nil && c.expectErr { - continue - } else if c.expectErr { - t.Error("Expected error, got none") - continue - } else if err != nil { - t.Errorf("Unexpected error %#v", err) - continue - } - gotNames := make([]string, len(gotControllers)) - for ix := range gotControllers { - gotNames[ix] = gotControllers[ix].Name - } - if !c.outRCNames.HasAll(gotNames...) || len(gotNames) != len(c.outRCNames) { - t.Errorf("Unexpected got controllers %+v expected %+v", gotNames, c.outRCNames) - } - } -} - -func TestStoreToReplicaSetLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - lister := StoreToReplicaSetLister{store} - testCases := []struct { - inRSs []*extensions.ReplicaSet - list func() ([]extensions.ReplicaSet, error) - outRSNames sets.String - expectErr bool - }{ - // Basic listing with all labels and no selectors - { - inRSs: []*extensions.ReplicaSet{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, - }, - list: func() ([]extensions.ReplicaSet, error) { - return lister.List() - }, - outRSNames: sets.NewString("basic"), - }, - // No pod labels - { - inRSs: []*extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "baz"}}, - }, - }, - }, - list: func() ([]extensions.ReplicaSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "pod1", Namespace: "ns"}, - } - return lister.GetPodReplicaSets(pod) - }, - outRSNames: sets.NewString(), - expectErr: true, - }, - // No ReplicaSet selectors - { - inRSs: []*extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - }, - }, - list: func() ([]extensions.ReplicaSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod1", - Namespace: "ns", - Labels: map[string]string{"foo": "bar"}, - }, - } - return lister.GetPodReplicaSets(pod) - }, - outRSNames: sets.NewString(), - expectErr: true, - }, - // Matching labels to selectors and namespace - { - inRSs: []*extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, - Spec: extensions.ReplicaSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - }, - }, - }, - list: func() ([]extensions.ReplicaSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod1", - Labels: map[string]string{"foo": "bar"}, - Namespace: "ns", - }, - } - return lister.GetPodReplicaSets(pod) - }, - outRSNames: sets.NewString("bar"), - }, - } - for _, c := range testCases { - for _, r := range c.inRSs { - store.Add(r) - } - - gotRSs, err := c.list() - if err != nil && c.expectErr { - continue - } else if c.expectErr { - t.Error("Expected error, got none") - continue - } else if err != nil { - t.Errorf("Unexpected error %#v", err) - continue - } - gotNames := make([]string, len(gotRSs)) - for ix := range gotRSs { - gotNames[ix] = gotRSs[ix].Name - } - if !c.outRSNames.HasAll(gotNames...) || len(gotNames) != len(c.outRSNames) { - t.Errorf("Unexpected got ReplicaSets %+v expected %+v", gotNames, c.outRSNames) - } - } -} - -func TestStoreToDaemonSetLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - lister := StoreToDaemonSetLister{store} - testCases := []struct { - inDSs []*extensions.DaemonSet - list func() ([]extensions.DaemonSet, error) - outDaemonSetNames sets.String - expectErr bool - }{ - // Basic listing - { - inDSs: []*extensions.DaemonSet{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, - }, - list: func() ([]extensions.DaemonSet, error) { - list, err := lister.List() - return list.Items, err - }, - outDaemonSetNames: sets.NewString("basic"), - }, - // Listing multiple daemon sets - { - inDSs: []*extensions.DaemonSet{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, - {ObjectMeta: api.ObjectMeta{Name: "complex"}}, - {ObjectMeta: api.ObjectMeta{Name: "complex2"}}, - }, - list: func() ([]extensions.DaemonSet, error) { - list, err := lister.List() - return list.Items, err - }, - outDaemonSetNames: sets.NewString("basic", "complex", "complex2"), - }, - // No pod labels - { - inDSs: []*extensions.DaemonSet{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "baz"}}, - }, - }, - }, - list: func() ([]extensions.DaemonSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "pod1", Namespace: "ns"}, - } - return lister.GetPodDaemonSets(pod) - }, - outDaemonSetNames: sets.NewString(), - expectErr: true, - }, - // No DS selectors - { - inDSs: []*extensions.DaemonSet{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - }, - }, - list: func() ([]extensions.DaemonSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod1", - Namespace: "ns", - Labels: map[string]string{"foo": "bar"}, - }, - } - return lister.GetPodDaemonSets(pod) - }, - outDaemonSetNames: sets.NewString(), - expectErr: true, - }, - // Matching labels to selectors and namespace - { - inDSs: []*extensions.DaemonSet{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - }, - }, - }, - list: func() ([]extensions.DaemonSet, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod1", - Labels: map[string]string{"foo": "bar"}, - Namespace: "ns", - }, - } - return lister.GetPodDaemonSets(pod) - }, - outDaemonSetNames: sets.NewString("bar"), - }, - } - for _, c := range testCases { - for _, r := range c.inDSs { - store.Add(r) - } - - daemonSets, err := c.list() - if err != nil && c.expectErr { - continue - } else if c.expectErr { - t.Error("Expected error, got none") - continue - } else if err != nil { - t.Errorf("Unexpected error %#v", err) - continue - } - daemonSetNames := make([]string, len(daemonSets)) - for ix := range daemonSets { - daemonSetNames[ix] = daemonSets[ix].Name - } - if !c.outDaemonSetNames.HasAll(daemonSetNames...) || len(daemonSetNames) != len(c.outDaemonSetNames) { - t.Errorf("Unexpected got controllers %+v expected %+v", daemonSetNames, c.outDaemonSetNames) - } - } -} - -func TestStoreToJobLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - lister := StoreToJobLister{store} - testCases := []struct { - inJobs []*extensions.Job - list func() ([]extensions.Job, error) - outJobNames sets.String - expectErr bool - msg string - }{ - // Basic listing - { - inJobs: []*extensions.Job{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, - }, - list: func() ([]extensions.Job, error) { - list, err := lister.List() - return list.Items, err - }, - outJobNames: sets.NewString("basic"), - msg: "basic listing failed", - }, - // Listing multiple jobs - { - inJobs: []*extensions.Job{ - {ObjectMeta: api.ObjectMeta{Name: "basic"}}, - {ObjectMeta: api.ObjectMeta{Name: "complex"}}, - {ObjectMeta: api.ObjectMeta{Name: "complex2"}}, - }, - list: func() ([]extensions.Job, error) { - list, err := lister.List() - return list.Items, err - }, - outJobNames: sets.NewString("basic", "complex", "complex2"), - msg: "listing multiple jobs failed", - }, - // No pod labels - { - inJobs: []*extensions.Job{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - Spec: extensions.JobSpec{ - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"foo": "baz"}, - }, - }, - }, - }, - list: func() ([]extensions.Job, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "pod", Namespace: "ns"}, - } - return lister.GetPodJobs(pod) - }, - outJobNames: sets.NewString(), - expectErr: true, - msg: "listing jobs failed when pod has no labels: expected error, got none", - }, - // No Job selectors - { - inJobs: []*extensions.Job{ - { - ObjectMeta: api.ObjectMeta{Name: "basic", Namespace: "ns"}, - }, - }, - list: func() ([]extensions.Job, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod", - Namespace: "ns", - Labels: map[string]string{"foo": "bar"}, - }, - } - return lister.GetPodJobs(pod) - }, - outJobNames: sets.NewString(), - expectErr: true, - msg: "listing jobs failed when job has no selector: expected error, got none", - }, - // Matching labels to selectors and namespace - { - inJobs: []*extensions.Job{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: extensions.JobSpec{ - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"foo": "bar"}, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "ns"}, - Spec: extensions.JobSpec{ - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"foo": "bar"}, - }, - }, - }, - }, - list: func() ([]extensions.Job, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod", - Labels: map[string]string{"foo": "bar"}, - Namespace: "ns", - }, - } - return lister.GetPodJobs(pod) - }, - outJobNames: sets.NewString("bar"), - msg: "listing jobs with namespace and selector failed", - }, - // Matching labels to selectors and namespace, error case - { - inJobs: []*extensions.Job{ - { - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "foo"}, - Spec: extensions.JobSpec{ - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"foo": "bar"}, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "bar"}, - Spec: extensions.JobSpec{ - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"foo": "bar"}, - }, - }, - }, - }, - list: func() ([]extensions.Job, error) { - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod", - Labels: map[string]string{"foo": "bar"}, - Namespace: "baz", - }, - } - return lister.GetPodJobs(pod) - }, - expectErr: true, - msg: "listing jobs with namespace and selector failed: expected error, got none", - }, - } - for _, c := range testCases { - for _, r := range c.inJobs { - store.Add(r) - } - - Jobs, err := c.list() - if err != nil && c.expectErr { - continue - } else if c.expectErr { - t.Errorf("%v", c.msg) - continue - } else if err != nil { - t.Errorf("Unexpected error %#v", err) - continue - } - JobNames := make([]string, len(Jobs)) - for ix := range Jobs { - JobNames[ix] = Jobs[ix].Name - } - if !c.outJobNames.HasAll(JobNames...) || len(JobNames) != len(c.outJobNames) { - t.Errorf("%v : expected %v, got %v", c.msg, JobNames, c.outJobNames) - } - } -} - -func TestStoreToPodLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - ids := []string{"foo", "bar", "baz"} - for _, id := range ids { - store.Add(&api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: id, - Labels: map[string]string{"name": id}, - }, - }) - } - spl := StoreToPodLister{store} - - for _, id := range ids { - got, err := spl.List(labels.Set{"name": id}.AsSelector()) - if err != nil { - t.Errorf("Unexpected error: %v", err) - continue - } - if e, a := 1, len(got); e != a { - t.Errorf("Expected %v, got %v", e, a) - continue - } - if e, a := id, got[0].Name; e != a { - t.Errorf("Expected %v, got %v", e, a) - continue - } - - exists, err := spl.Exists(&api.Pod{ObjectMeta: api.ObjectMeta{Name: id}}) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !exists { - t.Errorf("exists returned false for %v", id) - } - } - - exists, err := spl.Exists(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "qux"}}) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if exists { - t.Error("Unexpected pod exists") - } -} - -func TestStoreToServiceLister(t *testing.T) { - store := NewStore(MetaNamespaceKeyFunc) - store.Add(&api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{}, - }, - }) - store.Add(&api.Service{ObjectMeta: api.ObjectMeta{Name: "bar"}}) - ssl := StoreToServiceLister{store} - - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foopod", - Labels: map[string]string{"role": "foo"}, - }, - } - - services, err := ssl.GetPodServices(pod) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if len(services) != 1 { - t.Fatalf("Expected 1 service, got %v", len(services)) - } - if e, a := "foo", services[0].Name; e != a { - t.Errorf("Expected service %q, got %q", e, a) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listwatch.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listwatch.go index 18528d236..06c2f611b 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listwatch.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listwatch.go @@ -20,7 +20,7 @@ import ( "time" "k8s.io/kubernetes/pkg/api" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/watch" @@ -42,7 +42,7 @@ type ListWatch struct { // Getter interface knows how to access Get method from RESTClient. type Getter interface { - Get() *client.Request + Get() *restclient.Request } // NewListWatchFromClient creates a new ListWatch from the specified client, resource, namespace and field selector. diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listwatch_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listwatch_test.go deleted file mode 100644 index a0a72f5d8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/listwatch_test.go +++ /dev/null @@ -1,173 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cache - -import ( - "net/http/httptest" - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/fields" - utiltesting "k8s.io/kubernetes/pkg/util/testing" -) - -func parseSelectorOrDie(s string) fields.Selector { - selector, err := fields.ParseSelector(s) - if err != nil { - panic(err) - } - return selector -} - -// buildQueryValues is a convenience function for knowing if a namespace should be in a query param or not -func buildQueryValues(query url.Values) url.Values { - v := url.Values{} - if query != nil { - for key, values := range query { - for _, value := range values { - v.Add(key, value) - } - } - } - return v -} - -func buildLocation(resourcePath string, query url.Values) string { - return resourcePath + "?" + query.Encode() -} - -func TestListWatchesCanList(t *testing.T) { - fieldSelectorQueryParamName := unversioned.FieldSelectorQueryParam(testapi.Default.GroupVersion().String()) - table := []struct { - location string - resource string - namespace string - fieldSelector fields.Selector - }{ - // Node - { - location: testapi.Default.ResourcePath("nodes", api.NamespaceAll, ""), - resource: "nodes", - namespace: api.NamespaceAll, - fieldSelector: parseSelectorOrDie(""), - }, - // pod with "assigned" field selector. - { - location: buildLocation( - testapi.Default.ResourcePath("pods", api.NamespaceAll, ""), - buildQueryValues(url.Values{fieldSelectorQueryParamName: []string{"spec.host="}})), - resource: "pods", - namespace: api.NamespaceAll, - fieldSelector: fields.Set{"spec.host": ""}.AsSelector(), - }, - // pod in namespace "foo" - { - location: buildLocation( - testapi.Default.ResourcePath("pods", "foo", ""), - buildQueryValues(url.Values{fieldSelectorQueryParamName: []string{"spec.host="}})), - resource: "pods", - namespace: "foo", - fieldSelector: fields.Set{"spec.host": ""}.AsSelector(), - }, - } - for _, item := range table { - handler := utiltesting.FakeHandler{ - StatusCode: 500, - ResponseBody: "", - T: t, - } - server := httptest.NewServer(&handler) - // TODO: Uncomment when fix #19254 - // defer server.Close() - client := client.NewOrDie(&client.Config{Host: server.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) - lw := NewListWatchFromClient(client, item.resource, item.namespace, item.fieldSelector) - // This test merely tests that the correct request is made. - lw.List(api.ListOptions{}) - handler.ValidateRequest(t, item.location, "GET", nil) - } -} - -func TestListWatchesCanWatch(t *testing.T) { - fieldSelectorQueryParamName := unversioned.FieldSelectorQueryParam(testapi.Default.GroupVersion().String()) - table := []struct { - rv string - location string - resource string - namespace string - fieldSelector fields.Selector - }{ - // Node - { - location: buildLocation( - testapi.Default.ResourcePathWithPrefix("watch", "nodes", api.NamespaceAll, ""), - buildQueryValues(url.Values{})), - rv: "", - resource: "nodes", - namespace: api.NamespaceAll, - fieldSelector: parseSelectorOrDie(""), - }, - { - location: buildLocation( - testapi.Default.ResourcePathWithPrefix("watch", "nodes", api.NamespaceAll, ""), - buildQueryValues(url.Values{"resourceVersion": []string{"42"}})), - rv: "42", - resource: "nodes", - namespace: api.NamespaceAll, - fieldSelector: parseSelectorOrDie(""), - }, - // pod with "assigned" field selector. - { - location: buildLocation( - testapi.Default.ResourcePathWithPrefix("watch", "pods", api.NamespaceAll, ""), - buildQueryValues(url.Values{fieldSelectorQueryParamName: []string{"spec.host="}, "resourceVersion": []string{"0"}})), - rv: "0", - resource: "pods", - namespace: api.NamespaceAll, - fieldSelector: fields.Set{"spec.host": ""}.AsSelector(), - }, - // pod with namespace foo and assigned field selector - { - location: buildLocation( - testapi.Default.ResourcePathWithPrefix("watch", "pods", "foo", ""), - buildQueryValues(url.Values{fieldSelectorQueryParamName: []string{"spec.host="}, "resourceVersion": []string{"0"}})), - rv: "0", - resource: "pods", - namespace: "foo", - fieldSelector: fields.Set{"spec.host": ""}.AsSelector(), - }, - } - - for _, item := range table { - handler := utiltesting.FakeHandler{ - StatusCode: 500, - ResponseBody: "", - T: t, - } - server := httptest.NewServer(&handler) - // TODO: Uncomment when fix #19254 - // defer server.Close() - client := client.NewOrDie(&client.Config{Host: server.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) - lw := NewListWatchFromClient(client, item.resource, item.namespace, item.fieldSelector) - // This test merely tests that the correct request is made. - lw.Watch(api.ListOptions{ResourceVersion: item.rv}) - handler.ValidateRequest(t, item.location, "GET", nil) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/reflector_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/reflector_test.go deleted file mode 100644 index 223769ade..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/reflector_test.go +++ /dev/null @@ -1,404 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cache - -import ( - "fmt" - "math/rand" - "strconv" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/wait" - "k8s.io/kubernetes/pkg/watch" -) - -type testLW struct { - ListFunc func() (runtime.Object, error) - WatchFunc func(resourceVersion string) (watch.Interface, error) -} - -func (t *testLW) List(options api.ListOptions) (runtime.Object, error) { - return t.ListFunc() -} -func (t *testLW) Watch(options api.ListOptions) (watch.Interface, error) { - return t.WatchFunc(options.ResourceVersion) -} - -func TestCloseWatchChannelOnError(t *testing.T) { - r := NewReflector(&testLW{}, &api.Pod{}, NewStore(MetaNamespaceKeyFunc), 0) - pod := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}} - fw := watch.NewFake() - r.listerWatcher = &testLW{ - WatchFunc: func(rv string) (watch.Interface, error) { - return fw, nil - }, - ListFunc: func() (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil - }, - } - go r.ListAndWatch(wait.NeverStop) - fw.Error(pod) - select { - case _, ok := <-fw.ResultChan(): - if ok { - t.Errorf("Watch channel left open after cancellation") - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("the cancellation is at least %s late", wait.ForeverTestTimeout.String()) - break - } -} - -func TestRunUntil(t *testing.T) { - stopCh := make(chan struct{}) - store := NewStore(MetaNamespaceKeyFunc) - r := NewReflector(&testLW{}, &api.Pod{}, store, 0) - fw := watch.NewFake() - r.listerWatcher = &testLW{ - WatchFunc: func(rv string) (watch.Interface, error) { - return fw, nil - }, - ListFunc: func() (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil - }, - } - r.RunUntil(stopCh) - // Synchronously add a dummy pod into the watch channel so we - // know the RunUntil go routine is in the watch handler. - fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}) - stopCh <- struct{}{} - select { - case _, ok := <-fw.ResultChan(): - if ok { - t.Errorf("Watch channel left open after stopping the watch") - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("the cancellation is at least %s late", wait.ForeverTestTimeout.String()) - break - } -} - -func TestReflectorResyncChan(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, time.Millisecond) - a, _ := g.resyncChan() - b := time.After(wait.ForeverTestTimeout) - select { - case <-a: - t.Logf("got timeout as expected") - case <-b: - t.Errorf("resyncChan() is at least 99 milliseconds late??") - } -} - -func BenchmarkReflectorResyncChanMany(b *testing.B) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 25*time.Millisecond) - // The improvement to this (calling the timer's Stop() method) makes - // this benchmark about 40% faster. - for i := 0; i < b.N; i++ { - g.resyncPeriod = time.Duration(rand.Float64() * float64(time.Millisecond) * 25) - _, stop := g.resyncChan() - stop() - } -} - -func TestReflectorWatchHandlerError(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 0) - fw := watch.NewFake() - go func() { - fw.Stop() - }() - var resumeRV string - err := g.watchHandler(fw, &resumeRV, neverExitWatch, wait.NeverStop) - if err == nil { - t.Errorf("unexpected non-error") - } -} - -func TestReflectorWatchHandler(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 0) - fw := watch.NewFake() - s.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - s.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}) - go func() { - fw.Add(&api.Service{ObjectMeta: api.ObjectMeta{Name: "rejected"}}) - fw.Delete(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - fw.Modify(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar", ResourceVersion: "55"}}) - fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "baz", ResourceVersion: "32"}}) - fw.Stop() - }() - var resumeRV string - err := g.watchHandler(fw, &resumeRV, neverExitWatch, wait.NeverStop) - if err != nil { - t.Errorf("unexpected error %v", err) - } - - mkPod := func(id string, rv string) *api.Pod { - return &api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: rv}} - } - - table := []struct { - Pod *api.Pod - exists bool - }{ - {mkPod("foo", ""), false}, - {mkPod("rejected", ""), false}, - {mkPod("bar", "55"), true}, - {mkPod("baz", "32"), true}, - } - for _, item := range table { - obj, exists, _ := s.Get(item.Pod) - if e, a := item.exists, exists; e != a { - t.Errorf("%v: expected %v, got %v", item.Pod, e, a) - } - if !exists { - continue - } - if e, a := item.Pod.ResourceVersion, obj.(*api.Pod).ResourceVersion; e != a { - t.Errorf("%v: expected %v, got %v", item.Pod, e, a) - } - } - - // RV should send the last version we see. - if e, a := "32", resumeRV; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - // last sync resource version should be the last version synced with store - if e, a := "32", g.LastSyncResourceVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestReflectorWatchHandlerTimeout(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 0) - fw := watch.NewFake() - var resumeRV string - exit := make(chan time.Time, 1) - exit <- time.Now() - err := g.watchHandler(fw, &resumeRV, exit, wait.NeverStop) - if err != errorResyncRequested { - t.Errorf("expected timeout error, but got %q", err) - } -} - -func TestReflectorStopWatch(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &api.Pod{}, s, 0) - fw := watch.NewFake() - var resumeRV string - stopWatch := make(chan struct{}, 1) - stopWatch <- struct{}{} - err := g.watchHandler(fw, &resumeRV, neverExitWatch, stopWatch) - if err != errorStopRequested { - t.Errorf("expected stop error, got %q", err) - } -} - -func TestReflectorListAndWatch(t *testing.T) { - createdFakes := make(chan *watch.FakeWatcher) - - // The ListFunc says that it's at revision 1. Therefore, we expect our WatchFunc - // to get called at the beginning of the watch with 1, and again with 3 when we - // inject an error. - expectedRVs := []string{"1", "3"} - lw := &testLW{ - WatchFunc: func(rv string) (watch.Interface, error) { - fw := watch.NewFake() - if e, a := expectedRVs[0], rv; e != a { - t.Errorf("Expected rv %v, but got %v", e, a) - } - expectedRVs = expectedRVs[1:] - // channel is not buffered because the for loop below needs to block. But - // we don't want to block here, so report the new fake via a go routine. - go func() { createdFakes <- fw }() - return fw, nil - }, - ListFunc: func() (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}, nil - }, - } - s := NewFIFO(MetaNamespaceKeyFunc) - r := NewReflector(lw, &api.Pod{}, s, 0) - go r.ListAndWatch(wait.NeverStop) - - ids := []string{"foo", "bar", "baz", "qux", "zoo"} - var fw *watch.FakeWatcher - for i, id := range ids { - if fw == nil { - fw = <-createdFakes - } - sendingRV := strconv.FormatUint(uint64(i+2), 10) - fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: sendingRV}}) - if sendingRV == "3" { - // Inject a failure. - fw.Stop() - fw = nil - } - } - - // Verify we received the right ids with the right resource versions. - for i, id := range ids { - pod := s.Pop().(*api.Pod) - if e, a := id, pod.Name; e != a { - t.Errorf("%v: Expected %v, got %v", i, e, a) - } - if e, a := strconv.FormatUint(uint64(i+2), 10), pod.ResourceVersion; e != a { - t.Errorf("%v: Expected %v, got %v", i, e, a) - } - } - - if len(expectedRVs) != 0 { - t.Error("called watchStarter an unexpected number of times") - } -} - -func TestReflectorListAndWatchWithErrors(t *testing.T) { - mkPod := func(id string, rv string) *api.Pod { - return &api.Pod{ObjectMeta: api.ObjectMeta{Name: id, ResourceVersion: rv}} - } - mkList := func(rv string, pods ...*api.Pod) *api.PodList { - list := &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: rv}} - for _, pod := range pods { - list.Items = append(list.Items, *pod) - } - return list - } - table := []struct { - list *api.PodList - listErr error - events []watch.Event - watchErr error - }{ - { - list: mkList("1"), - events: []watch.Event{ - {watch.Added, mkPod("foo", "2")}, - {watch.Added, mkPod("bar", "3")}, - }, - }, { - list: mkList("3", mkPod("foo", "2"), mkPod("bar", "3")), - events: []watch.Event{ - {watch.Deleted, mkPod("foo", "4")}, - {watch.Added, mkPod("qux", "5")}, - }, - }, { - listErr: fmt.Errorf("a list error"), - }, { - list: mkList("5", mkPod("bar", "3"), mkPod("qux", "5")), - watchErr: fmt.Errorf("a watch error"), - }, { - list: mkList("5", mkPod("bar", "3"), mkPod("qux", "5")), - events: []watch.Event{ - {watch.Added, mkPod("baz", "6")}, - }, - }, { - list: mkList("6", mkPod("bar", "3"), mkPod("qux", "5"), mkPod("baz", "6")), - }, - } - - s := NewFIFO(MetaNamespaceKeyFunc) - for line, item := range table { - if item.list != nil { - // Test that the list is what currently exists in the store. - current := s.List() - checkMap := map[string]string{} - for _, item := range current { - pod := item.(*api.Pod) - checkMap[pod.Name] = pod.ResourceVersion - } - for _, pod := range item.list.Items { - if e, a := pod.ResourceVersion, checkMap[pod.Name]; e != a { - t.Errorf("%v: expected %v, got %v for pod %v", line, e, a, pod.Name) - } - } - if e, a := len(item.list.Items), len(checkMap); e != a { - t.Errorf("%v: expected %v, got %v", line, e, a) - } - } - watchRet, watchErr := item.events, item.watchErr - lw := &testLW{ - WatchFunc: func(rv string) (watch.Interface, error) { - if watchErr != nil { - return nil, watchErr - } - watchErr = fmt.Errorf("second watch") - fw := watch.NewFake() - go func() { - for _, e := range watchRet { - fw.Action(e.Type, e.Object) - } - fw.Stop() - }() - return fw, nil - }, - ListFunc: func() (runtime.Object, error) { - return item.list, item.listErr - }, - } - r := NewReflector(lw, &api.Pod{}, s, 0) - r.ListAndWatch(wait.NeverStop) - } -} - -func TestReflectorResync(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - - currentTime := time.Time{} - iteration := 0 - - lw := &testLW{ - WatchFunc: func(rv string) (watch.Interface, error) { - if iteration == 0 { - // Move time, but do not force resync. - currentTime = currentTime.Add(30 * time.Second) - } else if iteration == 1 { - // Move time to force resync. - currentTime = currentTime.Add(28 * time.Second) - } else if iteration >= 2 { - t.Fatalf("should have forced resync earlier") - } - iteration++ - fw := watch.NewFake() - // Send something to the watcher to avoid "watch too short" errors. - go func() { - fw.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: strconv.Itoa(iteration)}}) - fw.Stop() - }() - return fw, nil - }, - ListFunc: func() (runtime.Object, error) { - return &api.PodList{ListMeta: unversioned.ListMeta{ResourceVersion: "0"}}, nil - }, - } - resyncPeriod := time.Minute - r := NewReflector(lw, &api.Pod{}, s, resyncPeriod) - r.now = func() time.Time { return currentTime } - - r.ListAndWatch(wait.NeverStop) - if iteration != 2 { - t.Errorf("exactly 2 iterations were expected, got: %v", iteration) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/store_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/store_test.go deleted file mode 100644 index 07275f493..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/store_test.go +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cache - -import ( - "testing" - - "k8s.io/kubernetes/pkg/util/sets" -) - -// Test public interface -func doTestStore(t *testing.T, store Store) { - mkObj := func(id string, val string) testStoreObject { - return testStoreObject{id: id, val: val} - } - - store.Add(mkObj("foo", "bar")) - if item, ok, _ := store.Get(mkObj("foo", "")); !ok { - t.Errorf("didn't find inserted item") - } else { - if e, a := "bar", item.(testStoreObject).val; e != a { - t.Errorf("expected %v, got %v", e, a) - } - } - store.Update(mkObj("foo", "baz")) - if item, ok, _ := store.Get(mkObj("foo", "")); !ok { - t.Errorf("didn't find inserted item") - } else { - if e, a := "baz", item.(testStoreObject).val; e != a { - t.Errorf("expected %v, got %v", e, a) - } - } - store.Delete(mkObj("foo", "")) - if _, ok, _ := store.Get(mkObj("foo", "")); ok { - t.Errorf("found deleted item??") - } - - // Test List. - store.Add(mkObj("a", "b")) - store.Add(mkObj("c", "d")) - store.Add(mkObj("e", "e")) - { - found := sets.String{} - for _, item := range store.List() { - found.Insert(item.(testStoreObject).val) - } - if !found.HasAll("b", "d", "e") { - t.Errorf("missing items, found: %v", found) - } - if len(found) != 3 { - t.Errorf("extra items") - } - } - - // Test Replace. - store.Replace([]interface{}{ - mkObj("foo", "foo"), - mkObj("bar", "bar"), - }, "0") - - { - found := sets.String{} - for _, item := range store.List() { - found.Insert(item.(testStoreObject).val) - } - if !found.HasAll("foo", "bar") { - t.Errorf("missing items") - } - if len(found) != 2 { - t.Errorf("extra items") - } - } -} - -// Test public interface -func doTestIndex(t *testing.T, indexer Indexer) { - mkObj := func(id string, val string) testStoreObject { - return testStoreObject{id: id, val: val} - } - - // Test Index - expected := map[string]sets.String{} - expected["b"] = sets.NewString("a", "c") - expected["f"] = sets.NewString("e") - expected["h"] = sets.NewString("g") - indexer.Add(mkObj("a", "b")) - indexer.Add(mkObj("c", "b")) - indexer.Add(mkObj("e", "f")) - indexer.Add(mkObj("g", "h")) - { - for k, v := range expected { - found := sets.String{} - indexResults, err := indexer.Index("by_val", mkObj("", k)) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - for _, item := range indexResults { - found.Insert(item.(testStoreObject).id) - } - items := v.List() - if !found.HasAll(items...) { - t.Errorf("missing items, index %s, expected %v but found %v", k, items, found.List()) - } - } - } -} - -func testStoreKeyFunc(obj interface{}) (string, error) { - return obj.(testStoreObject).id, nil -} - -func testStoreIndexFunc(obj interface{}) ([]string, error) { - return []string{obj.(testStoreObject).val}, nil -} - -func testStoreIndexers() Indexers { - indexers := Indexers{} - indexers["by_val"] = testStoreIndexFunc - return indexers -} - -type testStoreObject struct { - id string - val string -} - -func TestCache(t *testing.T) { - doTestStore(t, NewStore(testStoreKeyFunc)) -} - -func TestFIFOCache(t *testing.T) { - doTestStore(t, NewFIFO(testStoreKeyFunc)) -} - -func TestUndeltaStore(t *testing.T) { - nop := func([]interface{}) {} - doTestStore(t, NewUndeltaStore(nop, testStoreKeyFunc)) -} - -func TestIndex(t *testing.T) { - doTestIndex(t, NewIndexer(testStoreKeyFunc, testStoreIndexers())) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/undelta_store_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/undelta_store_test.go deleted file mode 100644 index c14b7a800..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/cache/undelta_store_test.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cache - -import ( - "reflect" - "testing" -) - -// store_test.go checks that UndeltaStore conforms to the Store interface -// behavior. This test just tests that it calls the push func in addition. - -type testUndeltaObject struct { - name string - val interface{} -} - -func testUndeltaKeyFunc(obj interface{}) (string, error) { - return obj.(testUndeltaObject).name, nil -} - -/* -var ( - o1 interface{} = t{1} - o2 interface{} = t{2} - l1 []interface{} = []interface{}{t{1}} -) -*/ - -func TestUpdateCallsPush(t *testing.T) { - mkObj := func(name string, val interface{}) testUndeltaObject { - return testUndeltaObject{name: name, val: val} - } - - var got []interface{} - var callcount int = 0 - push := func(m []interface{}) { - callcount++ - got = m - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - u.Add(mkObj("a", 2)) - u.Update(mkObj("a", 1)) - if callcount != 2 { - t.Errorf("Expected 2 calls, got %d", callcount) - } - - l := []interface{}{mkObj("a", 1)} - if !reflect.DeepEqual(l, got) { - t.Errorf("Expected %#v, Got %#v", l, got) - } -} - -func TestDeleteCallsPush(t *testing.T) { - mkObj := func(name string, val interface{}) testUndeltaObject { - return testUndeltaObject{name: name, val: val} - } - - var got []interface{} - var callcount int = 0 - push := func(m []interface{}) { - callcount++ - got = m - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - u.Add(mkObj("a", 2)) - u.Delete(mkObj("a", "")) - if callcount != 2 { - t.Errorf("Expected 2 calls, got %d", callcount) - } - expected := []interface{}{} - if !reflect.DeepEqual(expected, got) { - t.Errorf("Expected %#v, Got %#v", expected, got) - } -} - -func TestReadsDoNotCallPush(t *testing.T) { - push := func(m []interface{}) { - t.Errorf("Unexpected call to push!") - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - // These should not call push. - _ = u.List() - _, _, _ = u.Get(testUndeltaObject{"a", ""}) -} - -func TestReplaceCallsPush(t *testing.T) { - mkObj := func(name string, val interface{}) testUndeltaObject { - return testUndeltaObject{name: name, val: val} - } - - var got []interface{} - var callcount int = 0 - push := func(m []interface{}) { - callcount++ - got = m - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - m := []interface{}{mkObj("a", 1)} - - u.Replace(m, "0") - if callcount != 1 { - t.Errorf("Expected 1 calls, got %d", callcount) - } - expected := []interface{}{mkObj("a", 1)} - if !reflect.DeepEqual(expected, got) { - t.Errorf("Expected %#v, Got %#v", expected, got) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go index 66a2e6863..599a0c40b 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go @@ -18,13 +18,14 @@ package internalclientset import ( "github.com/golang/glog" + restclient "k8s.io/kubernetes/pkg/client/restclient" + discovery "k8s.io/kubernetes/pkg/client/typed/discovery" unversionedcore "k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned" unversionedextensions "k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned" - unversioned "k8s.io/kubernetes/pkg/client/unversioned" ) type Interface interface { - Discovery() unversioned.DiscoveryInterface + Discovery() discovery.DiscoveryInterface Core() unversionedcore.CoreInterface Extensions() unversionedextensions.ExtensionsInterface } @@ -32,7 +33,7 @@ type Interface interface { // Clientset contains the clients for groups. Each group has exactly one // version included in a Clientset. type Clientset struct { - *unversioned.DiscoveryClient + *discovery.DiscoveryClient *unversionedcore.CoreClient *unversionedextensions.ExtensionsClient } @@ -48,12 +49,12 @@ func (c *Clientset) Extensions() unversionedextensions.ExtensionsInterface { } // Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() unversioned.DiscoveryInterface { +func (c *Clientset) Discovery() discovery.DiscoveryInterface { return c.DiscoveryClient } // NewForConfig creates a new Clientset for the given config. -func NewForConfig(c *unversioned.Config) (*Clientset, error) { +func NewForConfig(c *restclient.Config) (*Clientset, error) { var clientset Clientset var err error clientset.CoreClient, err = unversionedcore.NewForConfig(c) @@ -65,7 +66,7 @@ func NewForConfig(c *unversioned.Config) (*Clientset, error) { return &clientset, err } - clientset.DiscoveryClient, err = unversioned.NewDiscoveryClientForConfig(c) + clientset.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(c) if err != nil { glog.Errorf("failed to create the DiscoveryClient: %v", err) } @@ -74,21 +75,21 @@ func NewForConfig(c *unversioned.Config) (*Clientset, error) { // NewForConfigOrDie creates a new Clientset for the given config and // panics if there is an error in the config. -func NewForConfigOrDie(c *unversioned.Config) *Clientset { +func NewForConfigOrDie(c *restclient.Config) *Clientset { var clientset Clientset clientset.CoreClient = unversionedcore.NewForConfigOrDie(c) clientset.ExtensionsClient = unversionedextensions.NewForConfigOrDie(c) - clientset.DiscoveryClient = unversioned.NewDiscoveryClientForConfigOrDie(c) + clientset.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) return &clientset } // New creates a new Clientset for the given RESTClient. -func New(c *unversioned.RESTClient) *Clientset { +func New(c *restclient.RESTClient) *Clientset { var clientset Clientset clientset.CoreClient = unversionedcore.New(c) clientset.ExtensionsClient = unversionedextensions.New(c) - clientset.DiscoveryClient = unversioned.NewDiscoveryClient(c) + clientset.DiscoveryClient = discovery.NewDiscoveryClient(c) return &clientset } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset_adaption.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset_adaption.go index 1b721ad62..2e1214ac1 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset_adaption.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset_adaption.go @@ -17,6 +17,7 @@ limitations under the License. package internalclientset import ( + "k8s.io/kubernetes/pkg/client/typed/discovery" unversionedcore "k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned" unversionedextensions "k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned" "k8s.io/kubernetes/pkg/client/unversioned" @@ -38,5 +39,11 @@ func FromUnversionedClient(c *unversioned.Client) *Clientset { clientset.ExtensionsClient = unversionedextensions.New(nil) } + if c != nil && c.DiscoveryClient != nil { + clientset.DiscoveryClient = discovery.NewDiscoveryClient(c.DiscoveryClient.RESTClient) + } else { + clientset.DiscoveryClient = discovery.NewDiscoveryClient(nil) + } + return &clientset } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/clientset_generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/clientset_generated.go deleted file mode 100644 index 574c65ba1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/clientset_generated.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - "k8s.io/kubernetes/pkg/api" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/client/testing/core" - unversionedcore "k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned" - fakeunversionedcore "k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake" - unversionedextensions "k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned" - fakeunversionedextensions "k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake" - "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/watch" -) - -// Clientset returns a clientset that will respond with the provided objects -func NewSimpleClientset(objects ...runtime.Object) *Clientset { - o := core.NewObjects(api.Scheme, api.Codecs.UniversalDecoder()) - for _, obj := range objects { - if err := o.Add(obj); err != nil { - panic(err) - } - } - - fakePtr := core.Fake{} - fakePtr.AddReactor("*", "*", core.ObjectReaction(o, api.RESTMapper)) - - fakePtr.AddWatchReactor("*", core.DefaultWatchReactor(watch.NewFake(), nil)) - - return &Clientset{fakePtr} -} - -// Clientset implements clientset.Interface. Meant to be embedded into a -// struct to get a default implementation. This makes faking out just the method -// you want to test easier. -type Clientset struct { - core.Fake -} - -func (c *Clientset) Discovery() unversioned.DiscoveryInterface { - return &FakeDiscovery{&c.Fake} -} - -var _ clientset.Interface = &Clientset{} - -// Core retrieves the CoreClient -func (c *Clientset) Core() unversionedcore.CoreInterface { - return &fakeunversionedcore.FakeCore{&c.Fake} -} - -// Extensions retrieves the ExtensionsClient -func (c *Clientset) Extensions() unversionedextensions.ExtensionsInterface { - return &fakeunversionedextensions.FakeExtensions{&c.Fake} -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/discovery.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/discovery.go deleted file mode 100644 index 655fa41e0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/discovery.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -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. -*/ - -// TODO: the fake discovery client should live in pkg/client/discovery/, rather -// than being copied in every fake clientset. -package fake - -import ( - "github.com/emicklei/go-restful/swagger" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/client/testing/core" - "k8s.io/kubernetes/pkg/version" -) - -type FakeDiscovery struct { - *core.Fake -} - -func (c *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*unversioned.APIResourceList, error) { - action := core.ActionImpl{ - Verb: "get", - Resource: "resource", - } - c.Invokes(action, nil) - return c.Resources[groupVersion], nil -} - -func (c *FakeDiscovery) ServerResources() (map[string]*unversioned.APIResourceList, error) { - action := core.ActionImpl{ - Verb: "get", - Resource: "resource", - } - c.Invokes(action, nil) - return c.Resources, nil -} - -func (c *FakeDiscovery) ServerGroups() (*unversioned.APIGroupList, error) { - return nil, nil -} - -func (c *FakeDiscovery) ServerVersion() (*version.Info, error) { - action := core.ActionImpl{} - action.Verb = "get" - action.Resource = "version" - - c.Invokes(action, nil) - versionInfo := version.Get() - return &versionInfo, nil -} - -func (c *FakeDiscovery) SwaggerSchema(version unversioned.GroupVersion) (*swagger.ApiDeclaration, error) { - action := core.ActionImpl{} - action.Verb = "get" - if version == v1.SchemeGroupVersion { - action.Resource = "/swaggerapi/api/" + version.Version - } else { - action.Resource = "/swaggerapi/apis/" + version.Group + "/" + version.Version - } - - c.Invokes(action, nil) - return &swagger.ApiDeclaration{}, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/event.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/event.go index 221a8cc34..a47868247 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/event.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/event.go @@ -24,7 +24,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" utilruntime "k8s.io/kubernetes/pkg/util/runtime" @@ -182,7 +182,7 @@ func recordEvent(sink EventSink, event *api.Event, patch []byte, updateExistingE // If we can't contact the server, then hold everything while we keep trying. // Otherwise, something about the event is malformed and we should abandon it. switch err.(type) { - case *client.RequestConstructionError: + case *restclient.RequestConstructionError: // We will construct the request the same next time, so don't keep trying. glog.Errorf("Unable to construct event '%#v': '%v' (will not retry!)", event, err) return true diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/event_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/event_test.go deleted file mode 100644 index 61597e0d5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/event_test.go +++ /dev/null @@ -1,885 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package record - -import ( - "encoding/json" - "fmt" - "math/rand" - "strconv" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - client "k8s.io/kubernetes/pkg/client/unversioned" - k8sruntime "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/strategicpatch" -) - -func init() { - // Don't bother sleeping between retries. - sleepDuration = 0 -} - -type testEventSink struct { - OnCreate func(e *api.Event) (*api.Event, error) - OnUpdate func(e *api.Event) (*api.Event, error) - OnPatch func(e *api.Event, p []byte) (*api.Event, error) -} - -// CreateEvent records the event for testing. -func (t *testEventSink) Create(e *api.Event) (*api.Event, error) { - if t.OnCreate != nil { - return t.OnCreate(e) - } - return e, nil -} - -// UpdateEvent records the event for testing. -func (t *testEventSink) Update(e *api.Event) (*api.Event, error) { - if t.OnUpdate != nil { - return t.OnUpdate(e) - } - return e, nil -} - -// PatchEvent records the event for testing. -func (t *testEventSink) Patch(e *api.Event, p []byte) (*api.Event, error) { - if t.OnPatch != nil { - return t.OnPatch(e, p) - } - return e, nil -} - -type OnCreateFunc func(*api.Event) (*api.Event, error) - -func OnCreateFactory(testCache map[string]*api.Event, createEvent chan<- *api.Event) OnCreateFunc { - return func(event *api.Event) (*api.Event, error) { - testCache[getEventKey(event)] = event - createEvent <- event - return event, nil - } -} - -type OnPatchFunc func(*api.Event, []byte) (*api.Event, error) - -func OnPatchFactory(testCache map[string]*api.Event, patchEvent chan<- *api.Event) OnPatchFunc { - return func(event *api.Event, patch []byte) (*api.Event, error) { - cachedEvent, found := testCache[getEventKey(event)] - if !found { - return nil, fmt.Errorf("unexpected error: couldn't find Event in testCache.") - } - originalData, err := json.Marshal(cachedEvent) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - patched, err := strategicpatch.StrategicMergePatch(originalData, patch, event) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - patchedObj := &api.Event{} - err = json.Unmarshal(patched, patchedObj) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - patchEvent <- patchedObj - return patchedObj, nil - } -} - -func TestEventf(t *testing.T) { - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "bar", - }, - } - testPod2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - }, - } - testRef, err := api.GetPartialReference(testPod, "spec.containers[2]") - testRef2, err := api.GetPartialReference(testPod2, "spec.containers[3]") - if err != nil { - t.Fatal(err) - } - table := []struct { - obj k8sruntime.Object - eventtype string - reason string - messageFmt string - elements []interface{} - expect *api.Event - expectLog string - expectUpdate bool - }{ - { - obj: testRef, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testPod, - eventtype: api.EventTypeNormal, - reason: "Killed", - messageFmt: "some other verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - }, - Reason: "Killed", - Message: "some other verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 2, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 3, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: api.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef2, - eventtype: api.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 2, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: true, - }, - } - - testCache := map[string]*api.Event{} - logCalled := make(chan struct{}) - createEvent := make(chan *api.Event) - updateEvent := make(chan *api.Event) - patchEvent := make(chan *api.Event) - testEvents := testEventSink{ - OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *api.Event) (*api.Event, error) { - updateEvent <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache, patchEvent), - } - eventBroadcaster := NewBroadcaster() - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - - clock := util.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(api.EventSource{Component: "eventTest"}, eventBroadcaster, clock) - for index, item := range table { - clock.Step(1 * time.Second) - logWatcher1 := eventBroadcaster.StartLogging(t.Logf) // Prove that it is useful - logWatcher2 := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { - if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - logCalled <- struct{}{} - }) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - <-logCalled - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent - validateEvent(string(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent - validateEvent(string(index), actualEvent, item.expect, t) - } - logWatcher1.Stop() - logWatcher2.Stop() - } - sinkWatcher.Stop() -} - -func recorderWithFakeClock(eventSource api.EventSource, eventBroadcaster EventBroadcaster, clock util.Clock) EventRecorder { - return &recorderImpl{eventSource, eventBroadcaster.(*eventBroadcasterImpl).Broadcaster, clock} -} - -func TestWriteEventError(t *testing.T) { - type entry struct { - timesToSendError int - attemptsWanted int - err error - } - table := map[string]*entry{ - "giveUp1": { - timesToSendError: 1000, - attemptsWanted: 1, - err: &client.RequestConstructionError{}, - }, - "giveUp2": { - timesToSendError: 1000, - attemptsWanted: 1, - err: &errors.StatusError{}, - }, - "retry1": { - timesToSendError: 1000, - attemptsWanted: 12, - err: &errors.UnexpectedObjectError{}, - }, - "retry2": { - timesToSendError: 1000, - attemptsWanted: 12, - err: fmt.Errorf("A weird error"), - }, - "succeedEventually": { - timesToSendError: 2, - attemptsWanted: 2, - err: fmt.Errorf("A weird error"), - }, - } - - eventCorrelator := NewEventCorrelator(util.RealClock{}) - randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - - for caseName, ent := range table { - attempts := 0 - sink := &testEventSink{ - OnCreate: func(event *api.Event) (*api.Event, error) { - attempts++ - if attempts < ent.timesToSendError { - return nil, ent.err - } - return event, nil - }, - } - ev := &api.Event{} - recordToSink(sink, ev, eventCorrelator, randGen) - if attempts != ent.attemptsWanted { - t.Errorf("case %v: wanted %d, got %d attempts", caseName, ent.attemptsWanted, attempts) - } - } -} - -func TestLotsOfEvents(t *testing.T) { - recorderCalled := make(chan struct{}) - loggerCalled := make(chan struct{}) - - // Fail each event a few times to ensure there's some load on the tested code. - var counts [1000]int - testEvents := testEventSink{ - OnCreate: func(event *api.Event) (*api.Event, error) { - num, err := strconv.Atoi(event.Message) - if err != nil { - t.Error(err) - return event, nil - } - counts[num]++ - if counts[num] < 5 { - return nil, fmt.Errorf("fake error") - } - recorderCalled <- struct{}{} - return event, nil - }, - } - - eventBroadcaster := NewBroadcaster() - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { - loggerCalled <- struct{}{} - }) - recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "eventTest"}) - ref := &api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - } - for i := 0; i < maxQueuedEvents; i++ { - // we need to vary the reason to prevent aggregation - go recorder.Eventf(ref, api.EventTypeNormal, "Reason-"+string(i), strconv.Itoa(i)) - } - // Make sure no events were dropped by either of the listeners. - for i := 0; i < maxQueuedEvents; i++ { - <-recorderCalled - <-loggerCalled - } - // Make sure that every event was attempted 5 times - for i := 0; i < maxQueuedEvents; i++ { - if counts[i] < 5 { - t.Errorf("Only attempted to record event '%d' %d times.", i, counts[i]) - } - } - sinkWatcher.Stop() - logWatcher.Stop() -} - -func TestEventfNoNamespace(t *testing.T) { - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - UID: "bar", - }, - } - testRef, err := api.GetPartialReference(testPod, "spec.containers[2]") - if err != nil { - t.Fatal(err) - } - table := []struct { - obj k8sruntime.Object - eventtype string - reason string - messageFmt string - elements []interface{} - expect *api.Event - expectLog string - expectUpdate bool - }{ - { - obj: testRef, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "default", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - } - - testCache := map[string]*api.Event{} - logCalled := make(chan struct{}) - createEvent := make(chan *api.Event) - updateEvent := make(chan *api.Event) - patchEvent := make(chan *api.Event) - testEvents := testEventSink{ - OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *api.Event) (*api.Event, error) { - updateEvent <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache, patchEvent), - } - eventBroadcaster := NewBroadcaster() - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - - clock := util.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(api.EventSource{Component: "eventTest"}, eventBroadcaster, clock) - - for index, item := range table { - clock.Step(1 * time.Second) - logWatcher1 := eventBroadcaster.StartLogging(t.Logf) // Prove that it is useful - logWatcher2 := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { - if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - logCalled <- struct{}{} - }) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - <-logCalled - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent - validateEvent(string(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent - validateEvent(string(index), actualEvent, item.expect, t) - } - - logWatcher1.Stop() - logWatcher2.Stop() - } - sinkWatcher.Stop() -} - -func TestMultiSinkCache(t *testing.T) { - testPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "bar", - }, - } - testPod2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - }, - } - testRef, err := api.GetPartialReference(testPod, "spec.containers[2]") - testRef2, err := api.GetPartialReference(testPod2, "spec.containers[3]") - if err != nil { - t.Fatal(err) - } - table := []struct { - obj k8sruntime.Object - eventtype string - reason string - messageFmt string - elements []interface{} - expect *api.Event - expectLog string - expectUpdate bool - }{ - { - obj: testRef, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testPod, - eventtype: api.EventTypeNormal, - reason: "Killed", - messageFmt: "some other verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - }, - Reason: "Killed", - Message: "some other verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 2, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: api.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 3, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: api.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 1, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef2, - eventtype: api.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &api.Event{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: api.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: api.EventSource{Component: "eventTest"}, - Count: 2, - Type: api.EventTypeNormal, - }, - expectLog: `Event(api.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: true, - }, - } - - testCache := map[string]*api.Event{} - createEvent := make(chan *api.Event) - updateEvent := make(chan *api.Event) - patchEvent := make(chan *api.Event) - testEvents := testEventSink{ - OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *api.Event) (*api.Event, error) { - updateEvent <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache, patchEvent), - } - - testCache2 := map[string]*api.Event{} - createEvent2 := make(chan *api.Event) - updateEvent2 := make(chan *api.Event) - patchEvent2 := make(chan *api.Event) - testEvents2 := testEventSink{ - OnCreate: OnCreateFactory(testCache2, createEvent2), - OnUpdate: func(event *api.Event) (*api.Event, error) { - updateEvent2 <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache2, patchEvent2), - } - - eventBroadcaster := NewBroadcaster() - clock := util.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(api.EventSource{Component: "eventTest"}, eventBroadcaster, clock) - - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - for index, item := range table { - clock.Step(1 * time.Second) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent - validateEvent(string(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent - validateEvent(string(index), actualEvent, item.expect, t) - } - } - - // Another StartRecordingToSink call should start to record events with new clean cache. - sinkWatcher2 := eventBroadcaster.StartRecordingToSink(&testEvents2) - for index, item := range table { - clock.Step(1 * time.Second) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent2 - validateEvent(string(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent2 - validateEvent(string(index), actualEvent, item.expect, t) - } - } - - sinkWatcher.Stop() - sinkWatcher2.Stop() -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/events_cache_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/events_cache_test.go deleted file mode 100644 index 08699d9a6..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/record/events_cache_test.go +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package record - -import ( - "reflect" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/util" -) - -func makeObjectReference(kind, name, namespace string) api.ObjectReference { - return api.ObjectReference{ - Kind: kind, - Name: name, - Namespace: namespace, - UID: "C934D34AFB20242", - APIVersion: "version", - } -} - -func makeEvent(reason, message string, involvedObject api.ObjectReference) api.Event { - eventTime := unversioned.Now() - event := api.Event{ - Reason: reason, - Message: message, - InvolvedObject: involvedObject, - Source: api.EventSource{ - Component: "kubelet", - Host: "kublet.node1", - }, - Count: 1, - FirstTimestamp: eventTime, - LastTimestamp: eventTime, - Type: api.EventTypeNormal, - } - return event -} - -func makeEvents(num int, template api.Event) []api.Event { - events := []api.Event{} - for i := 0; i < num; i++ { - events = append(events, template) - } - return events -} - -func makeUniqueEvents(num int) []api.Event { - events := []api.Event{} - kind := "Pod" - for i := 0; i < num; i++ { - reason := strings.Join([]string{"reason", string(i)}, "-") - message := strings.Join([]string{"message", string(i)}, "-") - name := strings.Join([]string{"pod", string(i)}, "-") - namespace := strings.Join([]string{"ns", string(i)}, "-") - involvedObject := makeObjectReference(kind, name, namespace) - events = append(events, makeEvent(reason, message, involvedObject)) - } - return events -} - -func makeSimilarEvents(num int, template api.Event, messagePrefix string) []api.Event { - events := makeEvents(num, template) - for i := range events { - events[i].Message = strings.Join([]string{messagePrefix, string(i), events[i].Message}, "-") - } - return events -} - -func setCount(event api.Event, count int) api.Event { - event.Count = count - return event -} - -func validateEvent(messagePrefix string, actualEvent *api.Event, expectedEvent *api.Event, t *testing.T) (*api.Event, error) { - recvEvent := *actualEvent - expectCompression := expectedEvent.Count > 1 - t.Logf("%v - expectedEvent.Count is %d\n", messagePrefix, expectedEvent.Count) - // Just check that the timestamp was set. - if recvEvent.FirstTimestamp.IsZero() || recvEvent.LastTimestamp.IsZero() { - t.Errorf("%v - timestamp wasn't set: %#v", messagePrefix, recvEvent) - } - actualFirstTimestamp := recvEvent.FirstTimestamp - actualLastTimestamp := recvEvent.LastTimestamp - if actualFirstTimestamp.Equal(actualLastTimestamp) { - if expectCompression { - t.Errorf("%v - FirstTimestamp (%q) and LastTimestamp (%q) must be different to indicate event compression happened, but were the same. Actual Event: %#v", messagePrefix, actualFirstTimestamp, actualLastTimestamp, recvEvent) - } - } else { - if expectedEvent.Count == 1 { - t.Errorf("%v - FirstTimestamp (%q) and LastTimestamp (%q) must be equal to indicate only one occurrence of the event, but were different. Actual Event: %#v", messagePrefix, actualFirstTimestamp, actualLastTimestamp, recvEvent) - } - } - // Temp clear time stamps for comparison because actual values don't matter for comparison - recvEvent.FirstTimestamp = expectedEvent.FirstTimestamp - recvEvent.LastTimestamp = expectedEvent.LastTimestamp - // Check that name has the right prefix. - if n, en := recvEvent.Name, expectedEvent.Name; !strings.HasPrefix(n, en) { - t.Errorf("%v - Name '%v' does not contain prefix '%v'", messagePrefix, n, en) - } - recvEvent.Name = expectedEvent.Name - if e, a := expectedEvent, &recvEvent; !reflect.DeepEqual(e, a) { - t.Errorf("%v - diff: %s", messagePrefix, util.ObjectGoPrintDiff(e, a)) - } - recvEvent.FirstTimestamp = actualFirstTimestamp - recvEvent.LastTimestamp = actualLastTimestamp - return actualEvent, nil -} - -// TestDefaultEventFilterFunc ensures that no events are filtered -func TestDefaultEventFilterFunc(t *testing.T) { - event := makeEvent("end-of-world", "it was fun", makeObjectReference("Pod", "pod1", "other")) - if DefaultEventFilterFunc(&event) { - t.Fatalf("DefaultEventFilterFunc should always return false") - } -} - -// TestEventAggregatorByReasonFunc ensures that two events are aggregated if they vary only by event.message -func TestEventAggregatorByReasonFunc(t *testing.T) { - event1 := makeEvent("end-of-world", "it was fun", makeObjectReference("Pod", "pod1", "other")) - event2 := makeEvent("end-of-world", "it was awful", makeObjectReference("Pod", "pod1", "other")) - event3 := makeEvent("nevermind", "it was a bug", makeObjectReference("Pod", "pod1", "other")) - - aggKey1, localKey1 := EventAggregatorByReasonFunc(&event1) - aggKey2, localKey2 := EventAggregatorByReasonFunc(&event2) - aggKey3, _ := EventAggregatorByReasonFunc(&event3) - - if aggKey1 != aggKey2 { - t.Errorf("Expected %v equal %v", aggKey1, aggKey2) - } - if localKey1 == localKey2 { - t.Errorf("Expected %v to not equal %v", aggKey1, aggKey3) - } - if aggKey1 == aggKey3 { - t.Errorf("Expected %v to not equal %v", aggKey1, aggKey3) - } -} - -// TestEventAggregatorByReasonMessageFunc validates the proper output for an aggregate message -func TestEventAggregatorByReasonMessageFunc(t *testing.T) { - expected := "(events with common reason combined)" - event1 := makeEvent("end-of-world", "it was fun", makeObjectReference("Pod", "pod1", "other")) - if actual := EventAggregatorByReasonMessageFunc(&event1); expected != actual { - t.Errorf("Expected %v got %v", expected, actual) - } -} - -// TestEventCorrelator validates proper counting, aggregation of events -func TestEventCorrelator(t *testing.T) { - firstEvent := makeEvent("first", "i am first", makeObjectReference("Pod", "my-pod", "my-ns")) - duplicateEvent := makeEvent("duplicate", "me again", makeObjectReference("Pod", "my-pod", "my-ns")) - uniqueEvent := makeEvent("unique", "snowflake", makeObjectReference("Pod", "my-pod", "my-ns")) - similarEvent := makeEvent("similar", "similar message", makeObjectReference("Pod", "my-pod", "my-ns")) - aggregateEvent := makeEvent(similarEvent.Reason, EventAggregatorByReasonMessageFunc(&similarEvent), similarEvent.InvolvedObject) - scenario := map[string]struct { - previousEvents []api.Event - newEvent api.Event - expectedEvent api.Event - intervalSeconds int - }{ - "create-a-single-event": { - previousEvents: []api.Event{}, - newEvent: firstEvent, - expectedEvent: setCount(firstEvent, 1), - intervalSeconds: 5, - }, - "the-same-event-should-just-count": { - previousEvents: makeEvents(1, duplicateEvent), - newEvent: duplicateEvent, - expectedEvent: setCount(duplicateEvent, 2), - intervalSeconds: 5, - }, - "the-same-event-should-just-count-even-if-more-than-aggregate": { - previousEvents: makeEvents(defaultAggregateMaxEvents, duplicateEvent), - newEvent: duplicateEvent, - expectedEvent: setCount(duplicateEvent, defaultAggregateMaxEvents+1), - intervalSeconds: 5, - }, - "create-many-unique-events": { - previousEvents: makeUniqueEvents(30), - newEvent: uniqueEvent, - expectedEvent: setCount(uniqueEvent, 1), - intervalSeconds: 5, - }, - "similar-events-should-aggregate-event": { - previousEvents: makeSimilarEvents(defaultAggregateMaxEvents-1, similarEvent, similarEvent.Message), - newEvent: similarEvent, - expectedEvent: setCount(aggregateEvent, 1), - intervalSeconds: 5, - }, - "similar-events-many-times-should-count-the-aggregate": { - previousEvents: makeSimilarEvents(defaultAggregateMaxEvents, similarEvent, similarEvent.Message), - newEvent: similarEvent, - expectedEvent: setCount(aggregateEvent, 2), - intervalSeconds: 5, - }, - "similar-events-whose-interval-is-greater-than-aggregate-interval-do-not-aggregate": { - previousEvents: makeSimilarEvents(defaultAggregateMaxEvents-1, similarEvent, similarEvent.Message), - newEvent: similarEvent, - expectedEvent: setCount(similarEvent, 1), - intervalSeconds: defaultAggregateIntervalInSeconds, - }, - } - - for testScenario, testInput := range scenario { - eventInterval := time.Duration(testInput.intervalSeconds) * time.Second - clock := util.IntervalClock{Time: time.Now(), Duration: eventInterval} - correlator := NewEventCorrelator(&clock) - for i := range testInput.previousEvents { - event := testInput.previousEvents[i] - now := unversioned.NewTime(clock.Now()) - event.FirstTimestamp = now - event.LastTimestamp = now - result, err := correlator.EventCorrelate(&event) - if err != nil { - t.Errorf("scenario %v: unexpected error playing back prevEvents %v", testScenario, err) - } - correlator.UpdateState(result.Event) - } - - // update the input to current clock value - now := unversioned.NewTime(clock.Now()) - testInput.newEvent.FirstTimestamp = now - testInput.newEvent.LastTimestamp = now - result, err := correlator.EventCorrelate(&testInput.newEvent) - if err != nil { - t.Errorf("scenario %v: unexpected error correlating input event %v", testScenario, err) - } - - _, err = validateEvent(testScenario, result.Event, &testInput.expectedEvent, t) - if err != nil { - t.Errorf("scenario %v: unexpected error validating result %v", testScenario, err) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/restclient.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/client.go similarity index 99% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/restclient.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/client.go index 3946754f3..2e378a922 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/restclient.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/client.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package unversioned +package restclient import ( "net/http" diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/config.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/config.go new file mode 100644 index 000000000..b084a8eb2 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/config.go @@ -0,0 +1,309 @@ +/* +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. +*/ + +package restclient + +import ( + "fmt" + "io/ioutil" + "net" + "net/http" + "os" + "path" + gruntime "runtime" + "strings" + + "github.com/golang/glog" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/version" +) + +// Config holds the common attributes that can be passed to a Kubernetes client on +// initialization. +type Config struct { + // Host must be a host string, a host:port pair, or a URL to the base of the apiserver. + // If a URL is given then the (optional) Path of that URL represents a prefix that must + // be appended to all request URIs used to access the apiserver. This allows a frontend + // proxy to easily relocate all of the apiserver endpoints. + Host string + // APIPath is a sub-path that points to an API root. + APIPath string + // Prefix is the sub path of the server. If not specified, the client will set + // a default value. Use "/" to indicate the server root should be used + Prefix string + + // ContentConfig contains settings that affect how objects are transformed when + // sent to the server. + ContentConfig + + // Server requires Basic authentication + Username string + Password string + + // Server requires Bearer authentication. This client will not attempt to use + // refresh tokens for an OAuth2 flow. + // TODO: demonstrate an OAuth2 compatible client. + BearerToken string + + // TLSClientConfig contains settings to enable transport layer security + TLSClientConfig + + // Server should be accessed without verifying the TLS + // certificate. For testing only. + Insecure bool + + // UserAgent is an optional field that specifies the caller of this request. + UserAgent string + + // Transport may be used for custom HTTP behavior. This attribute may not + // be specified with the TLS client certificate options. Use WrapTransport + // for most client level operations. + Transport http.RoundTripper + // WrapTransport will be invoked for custom HTTP behavior after the underlying + // transport is initialized (either the transport created from TLSClientConfig, + // Transport, or http.DefaultTransport). The config may layer other RoundTrippers + // 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 float32 + + // Maximum burst for throttle + Burst int +} + +// TLSClientConfig contains settings to enable transport layer security +type TLSClientConfig struct { + // Server requires TLS client certificate authentication + CertFile string + // Server requires TLS client certificate authentication + KeyFile string + // Trusted root certificates for server + CAFile string + + // CertData holds PEM-encoded bytes (typically read from a client certificate file). + // CertData takes precedence over CertFile + CertData []byte + // KeyData holds PEM-encoded bytes (typically read from a client certificate key file). + // KeyData takes precedence over KeyFile + KeyData []byte + // CAData holds PEM-encoded bytes (typically read from a root certificates bundle). + // CAData takes precedence over CAFile + CAData []byte +} + +type ContentConfig struct { + // 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, + // "application/json" is used. + ContentType string + // GroupVersion is the API version to talk to. Must be provided when initializing + // a RESTClient directly. When initializing a Client, will be set with the default + // code version. + GroupVersion *unversioned.GroupVersion + // 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. + Codec runtime.Codec +} + +// RESTClientFor returns a RESTClient that satisfies the requested attributes on a client Config +// object. Note that a RESTClient may require fields that are optional when initializing a Client. +// A RESTClient created by this method is generic - it expects to operate on an API that follows +// the Kubernetes conventions, but may not be the Kubernetes API. +func RESTClientFor(config *Config) (*RESTClient, error) { + if config.GroupVersion == nil { + return nil, fmt.Errorf("GroupVersion is required when initializing a RESTClient") + } + if config.Codec == nil { + return nil, fmt.Errorf("Codec is required when initializing a RESTClient") + } + + baseURL, versionedAPIPath, err := defaultServerUrlFor(config) + if err != nil { + return nil, err + } + + transport, err := TransportFor(config) + if err != nil { + return nil, err + } + + var httpClient *http.Client + if transport != http.DefaultTransport { + httpClient = &http.Client{Transport: transport} + } + + client := NewRESTClient(baseURL, versionedAPIPath, config.ContentConfig, config.QPS, config.Burst, httpClient) + + return client, nil +} + +// UnversionedRESTClientFor is the same as RESTClientFor, except that it allows +// the config.Version to be empty. +func UnversionedRESTClientFor(config *Config) (*RESTClient, error) { + if config.Codec == nil { + return nil, fmt.Errorf("Codec is required when initializing a RESTClient") + } + + baseURL, versionedAPIPath, err := defaultServerUrlFor(config) + if err != nil { + return nil, err + } + + transport, err := TransportFor(config) + if err != nil { + return nil, err + } + + var httpClient *http.Client + if transport != http.DefaultTransport { + httpClient = &http.Client{Transport: transport} + } + + versionConfig := config.ContentConfig + if versionConfig.GroupVersion == nil { + v := unversioned.SchemeGroupVersion + versionConfig.GroupVersion = &v + } + + client := NewRESTClient(baseURL, versionedAPIPath, versionConfig, config.QPS, config.Burst, httpClient) + return client, nil +} + +// SetKubernetesDefaults sets default values on the provided client config for accessing the +// Kubernetes API or returns an error if any of the defaults are impossible or invalid. +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 +} + +// DefaultKubernetesUserAgent returns the default user agent that clients can use. +func DefaultKubernetesUserAgent() string { + commit := version.Get().GitCommit + if len(commit) > 7 { + commit = commit[:7] + } + if len(commit) == 0 { + commit = "unknown" + } + version := version.Get().GitVersion + seg := strings.SplitN(version, "-", 2) + version = seg[0] + return fmt.Sprintf("%s/%s (%s/%s) kubernetes/%s", path.Base(os.Args[0]), version, gruntime.GOOS, gruntime.GOARCH, commit) +} + +// 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 +// 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") + if len(host) == 0 || len(port) == 0 { + return nil, fmt.Errorf("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined") + } + + token, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/" + api.ServiceAccountTokenKey) + if err != nil { + return nil, err + } + tlsClientConfig := TLSClientConfig{} + rootCAFile := "/var/run/secrets/kubernetes.io/serviceaccount/" + api.ServiceAccountRootCAKey + if _, err := util.CertPoolFromFile(rootCAFile); err != nil { + glog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err) + } else { + tlsClientConfig.CAFile = rootCAFile + } + + return &Config{ + // TODO: switch to using cluster DNS. + Host: "https://" + net.JoinHostPort(host, port), + BearerToken: string(token), + TLSClientConfig: tlsClientConfig, + }, nil +} + +// IsConfigTransportTLS returns true if and only if the provided +// config will result in a protected connection to the server when it +// is passed to restclient.RESTClientFor(). Use to determine when to +// send credentials over the wire. +// +// Note: the Insecure flag is ignored when testing for this value, so MITM attacks are +// still possible. +func IsConfigTransportTLS(config Config) bool { + baseURL, _, err := defaultServerUrlFor(&config) + if err != nil { + return false + } + return baseURL.Scheme == "https" +} + +// LoadTLSFiles copies the data from the CertFile, KeyFile, and CAFile fields into the CertData, +// KeyData, and CAFile fields, or returns an error. If no error is returned, all three fields are +// either populated or were empty to start. +func LoadTLSFiles(c *Config) error { + var err error + c.CAData, err = dataFromSliceOrFile(c.CAData, c.CAFile) + if err != nil { + return err + } + + c.CertData, err = dataFromSliceOrFile(c.CertData, c.CertFile) + if err != nil { + return err + } + + c.KeyData, err = dataFromSliceOrFile(c.KeyData, c.KeyFile) + if err != nil { + return err + } + return nil +} + +// dataFromSliceOrFile returns data from the slice (if non-empty), or from the file, +// or an error if an error occurred reading the file +func dataFromSliceOrFile(data []byte, file string) ([]byte, error) { + if len(data) > 0 { + return data, nil + } + if len(file) > 0 { + fileData, err := ioutil.ReadFile(file) + if err != nil { + return []byte{}, err + } + return fileData, nil + } + return nil, nil +} + +func AddUserAgent(config *Config, userAgent string) *Config { + fullUserAgent := DefaultKubernetesUserAgent() + "/" + userAgent + config.UserAgent = fullUserAgent + return config +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/request.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/request.go similarity index 94% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/request.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/request.go index 24c4bd195..0c9a10b7d 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/request.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/request.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package unversioned +package restclient import ( "bytes" @@ -292,22 +292,22 @@ func (r *Request) RequestURI(uri string) *Request { const ( // A constant that clients can use to refer in a field selector to the object name field. // Will be automatically emitted as the correct name for the API version. - NodeUnschedulable = "spec.unschedulable" - ObjectNameField = "metadata.name" - PodHost = "spec.nodeName" - PodStatus = "status.phase" - SecretType = "type" + nodeUnschedulable = "spec.unschedulable" + objectNameField = "metadata.name" + podHost = "spec.nodeName" + podStatus = "status.phase" + secretType = "type" - EventReason = "reason" - EventSource = "source" - EventType = "type" - EventInvolvedKind = "involvedObject.kind" - EventInvolvedNamespace = "involvedObject.namespace" - EventInvolvedName = "involvedObject.name" - EventInvolvedUID = "involvedObject.uid" - EventInvolvedAPIVersion = "involvedObject.apiVersion" - EventInvolvedResourceVersion = "involvedObject.resourceVersion" - EventInvolvedFieldPath = "involvedObject.fieldPath" + eventReason = "reason" + eventSource = "source" + eventType = "type" + eventInvolvedKind = "involvedObject.kind" + eventInvolvedNamespace = "involvedObject.namespace" + eventInvolvedName = "involvedObject.name" + eventInvolvedUID = "involvedObject.uid" + eventInvolvedAPIVersion = "involvedObject.apiVersion" + eventInvolvedResourceVersion = "involvedObject.resourceVersion" + eventInvolvedFieldPath = "involvedObject.fieldPath" ) type clientFieldNameToAPIVersionFieldName map[string]string @@ -350,34 +350,34 @@ func (v versionToResourceToFieldMapping) filterField(groupVersion *unversioned.G var fieldMappings = versionToResourceToFieldMapping{ v1.SchemeGroupVersion: resourceTypeToFieldMapping{ "nodes": clientFieldNameToAPIVersionFieldName{ - ObjectNameField: ObjectNameField, - NodeUnschedulable: NodeUnschedulable, + objectNameField: objectNameField, + nodeUnschedulable: nodeUnschedulable, }, "pods": clientFieldNameToAPIVersionFieldName{ - PodHost: PodHost, - PodStatus: PodStatus, + podHost: podHost, + podStatus: podStatus, }, "secrets": clientFieldNameToAPIVersionFieldName{ - SecretType: SecretType, + secretType: secretType, }, "serviceAccounts": clientFieldNameToAPIVersionFieldName{ - ObjectNameField: ObjectNameField, + objectNameField: objectNameField, }, "endpoints": clientFieldNameToAPIVersionFieldName{ - ObjectNameField: ObjectNameField, + objectNameField: objectNameField, }, "events": clientFieldNameToAPIVersionFieldName{ - ObjectNameField: ObjectNameField, - EventReason: EventReason, - EventSource: EventSource, - EventType: EventType, - EventInvolvedKind: EventInvolvedKind, - EventInvolvedNamespace: EventInvolvedNamespace, - EventInvolvedName: EventInvolvedName, - EventInvolvedUID: EventInvolvedUID, - EventInvolvedAPIVersion: EventInvolvedAPIVersion, - EventInvolvedResourceVersion: EventInvolvedResourceVersion, - EventInvolvedFieldPath: EventInvolvedFieldPath, + objectNameField: objectNameField, + eventReason: eventReason, + eventSource: eventSource, + eventType: eventType, + eventInvolvedKind: eventInvolvedKind, + eventInvolvedNamespace: eventInvolvedNamespace, + eventInvolvedName: eventInvolvedName, + eventInvolvedUID: eventInvolvedUID, + eventInvolvedAPIVersion: eventInvolvedAPIVersion, + eventInvolvedResourceVersion: eventInvolvedResourceVersion, + eventInvolvedFieldPath: eventInvolvedFieldPath, }, }, } @@ -624,7 +624,7 @@ func (r *Request) tryThrottle() { r.throttle.Accept() } if latency := time.Since(now); latency > longThrottleLatency { - glog.Warningf("Throttling request took %v, request: %s", latency, r.URL().String()) + glog.Warningf("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String()) } } @@ -645,7 +645,7 @@ func (r *Request) Watch() (watch.Interface, error) { if client == nil { client = http.DefaultClient } - time.Sleep(r.backoffMgr.CalculateBackoff(r.URL())) + r.backoffMgr.Sleep(r.backoffMgr.CalculateBackoff(r.URL())) resp, err := client.Do(req) updateURLMetrics(r, resp, err) if r.baseURL != nil { @@ -710,7 +710,7 @@ func (r *Request) Stream() (io.ReadCloser, error) { if client == nil { client = http.DefaultClient } - time.Sleep(r.backoffMgr.CalculateBackoff(r.URL())) + r.backoffMgr.Sleep(r.backoffMgr.CalculateBackoff(r.URL())) resp, err := client.Do(req) updateURLMetrics(r, resp, err) if r.baseURL != nil { @@ -792,7 +792,7 @@ func (r *Request) request(fn func(*http.Request, *http.Response)) error { } req.Header = r.headers - time.Sleep(r.backoffMgr.CalculateBackoff(r.URL())) + r.backoffMgr.Sleep(r.backoffMgr.CalculateBackoff(r.URL())) resp, err := client.Do(req) updateURLMetrics(r, resp, err) if err != nil { @@ -812,7 +812,7 @@ func (r *Request) request(fn func(*http.Request, *http.Response)) error { retries++ if seconds, wait := checkWait(resp); wait && retries < maxRetries { glog.V(4).Infof("Got a Retry-After %s response for attempt %d to %v", seconds, retries, url) - time.Sleep(time.Duration(seconds) * time.Second) + r.backoffMgr.Sleep(time.Duration(seconds) * time.Second) return false } fn(req, resp) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/transport.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/transport.go similarity index 99% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/transport.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/transport.go index 74469cae0..7d4b497c3 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/transport.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/transport.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package unversioned +package restclient import ( "crypto/tls" diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/url_utils.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/url_utils.go new file mode 100644 index 000000000..9a83d7874 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/url_utils.go @@ -0,0 +1,93 @@ +/* +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. +*/ + +package restclient + +import ( + "fmt" + "net/url" + "path" + + "k8s.io/kubernetes/pkg/api/unversioned" +) + +// DefaultServerURL converts a host, host:port, or URL string to the default base server API path +// to use with a Client at a given API version following the standard conventions for a +// Kubernetes API. +func DefaultServerURL(host, apiPath string, groupVersion unversioned.GroupVersion, defaultTLS bool) (*url.URL, string, error) { + if host == "" { + return nil, "", fmt.Errorf("host must be a URL or a host:port pair") + } + base := host + hostURL, err := url.Parse(base) + if err != nil { + return nil, "", err + } + if hostURL.Scheme == "" { + scheme := "http://" + if defaultTLS { + scheme = "https://" + } + hostURL, err = url.Parse(scheme + base) + if err != nil { + return nil, "", err + } + if hostURL.Path != "" && hostURL.Path != "/" { + return nil, "", fmt.Errorf("host must be a URL or a host:port pair: %q", base) + } + } + + // hostURL.Path is optional; a non-empty Path is treated as a prefix that is to be applied to + // all URIs used to access the host. this is useful when there's a proxy in front of the + // apiserver that has relocated the apiserver endpoints, forwarding all requests from, for + // example, /a/b/c to the apiserver. in this case the Path should be /a/b/c. + // + // if running without a frontend proxy (that changes the location of the apiserver), then + // hostURL.Path should be blank. + // + // versionedAPIPath, a path relative to baseURL.Path, points to a versioned API base + versionedAPIPath := path.Join("/", apiPath) + + // Add the version to the end of the path + if len(groupVersion.Group) > 0 { + versionedAPIPath = path.Join(versionedAPIPath, groupVersion.Group, groupVersion.Version) + + } else { + versionedAPIPath = path.Join(versionedAPIPath, groupVersion.Version) + + } + + return hostURL, versionedAPIPath, nil +} + +// defaultServerUrlFor is shared between IsConfigTransportTLS and RESTClientFor. It +// requires Host and Version to be set prior to being called. +func defaultServerUrlFor(config *Config) (*url.URL, string, error) { + // TODO: move the default to secure when the apiserver supports TLS by default + // config.Insecure is taken to mean "I want HTTPS but don't bother checking the certs against a CA." + hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0 + hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0 + defaultTLS := hasCA || hasCert || config.Insecure + host := config.Host + if host == "" { + host = "localhost" + } + + if config.GroupVersion != nil { + return DefaultServerURL(host, config.APIPath, *config.GroupVersion, defaultTLS) + } + return DefaultServerURL(host, config.APIPath, unversioned.GroupVersion{}, defaultTLS) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/urlbackoff.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/urlbackoff.go similarity index 93% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/urlbackoff.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/urlbackoff.go index 331079bd7..7baba5c1f 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/urlbackoff.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/urlbackoff.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package unversioned +package restclient import ( "net/url" @@ -35,6 +35,7 @@ var maxResponseCode = 499 type BackoffManager interface { UpdateBackoff(actualUrl *url.URL, err error, responseCode int) CalculateBackoff(actualUrl *url.URL) time.Duration + Sleep(d time.Duration) } // URLBackoff struct implements the semantics on top of Backoff which @@ -54,6 +55,9 @@ func (n *NoBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode in func (n *NoBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration { return 0 * time.Second } +func (n *NoBackoff) Sleep(d time.Duration) { + return +} // Disable makes the backoff trivial, i.e., sets it to zero. This might be used // by tests which want to run 1000s of mock requests without slowing down. @@ -80,7 +84,7 @@ func (b *URLBackoff) baseUrlKey(rawurl *url.URL) string { func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) { // range for retry counts that we store is [0,13] if responseCode > maxResponseCode || serverIsOverloadedSet.Has(responseCode) { - b.Backoff.Next(b.baseUrlKey(actualUrl), time.Now()) + b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now()) return } else if responseCode >= 300 || err != nil { glog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) @@ -95,3 +99,7 @@ func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode i func (b *URLBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration { return b.Backoff.Get(b.baseUrlKey(actualUrl)) } + +func (b *URLBackoff) Sleep(d time.Duration) { + b.Backoff.Clock.Sleep(d) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/versions.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/versions.go new file mode 100644 index 000000000..e12c05c10 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/restclient/versions.go @@ -0,0 +1,88 @@ +/* +Copyright 2014 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. +*/ + +package restclient + +import ( + "encoding/json" + "fmt" + "net/http" + "path" + + "k8s.io/kubernetes/pkg/api/unversioned" +) + +const ( + legacyAPIPath = "/api" + defaultAPIPath = "/apis" +) + +// TODO: Is this obsoleted by the discovery client? + +// ServerAPIVersions returns the GroupVersions supported by the API server. +// It creates a RESTClient based on the passed in config, but it doesn't rely +// on the Version and Codec of the config, because it uses AbsPath and +// takes the raw response. +func ServerAPIVersions(c *Config) (groupVersions []string, err error) { + transport, err := TransportFor(c) + if err != nil { + return nil, err + } + client := http.Client{Transport: transport} + + configCopy := *c + configCopy.GroupVersion = nil + configCopy.APIPath = "" + baseURL, _, err := defaultServerUrlFor(&configCopy) + if err != nil { + return nil, err + } + // Get the groupVersions exposed at /api + originalPath := baseURL.Path + baseURL.Path = path.Join(originalPath, legacyAPIPath) + resp, err := client.Get(baseURL.String()) + if err != nil { + return nil, err + } + var v unversioned.APIVersions + defer resp.Body.Close() + err = json.NewDecoder(resp.Body).Decode(&v) + if err != nil { + return nil, fmt.Errorf("unexpected error: %v", err) + } + + groupVersions = append(groupVersions, v.Versions...) + // Get the groupVersions exposed at /apis + baseURL.Path = path.Join(originalPath, defaultAPIPath) + resp2, err := client.Get(baseURL.String()) + if err != nil { + return nil, err + } + var apiGroupList unversioned.APIGroupList + defer resp2.Body.Close() + err = json.NewDecoder(resp2.Body).Decode(&apiGroupList) + if err != nil { + return nil, fmt.Errorf("unexpected error: %v", err) + } + + for _, g := range apiGroupList.Groups { + for _, gv := range g.Versions { + groupVersions = append(groupVersions, gv.GroupVersion) + } + } + + return groupVersions, nil +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/cache_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/cache_test.go deleted file mode 100644 index 8a602c147..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/cache_test.go +++ /dev/null @@ -1,114 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package transport - -import ( - "net/http" - "testing" -) - -func TestTLSConfigKey(t *testing.T) { - // Make sure config fields that don't affect the tls config don't affect the cache key - identicalConfigurations := map[string]*Config{ - "empty": {}, - "basic": {Username: "bob", Password: "password"}, - "bearer": {BearerToken: "token"}, - "user agent": {UserAgent: "useragent"}, - "transport": {Transport: http.DefaultTransport}, - "wrap transport": {WrapTransport: func(http.RoundTripper) http.RoundTripper { return nil }}, - } - for nameA, valueA := range identicalConfigurations { - for nameB, valueB := range identicalConfigurations { - keyA, err := tlsConfigKey(valueA) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameA, err) - continue - } - keyB, err := tlsConfigKey(valueB) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameB, err) - continue - } - if keyA != keyB { - t.Errorf("Expected identical cache keys for %q and %q, got:\n\t%s\n\t%s", nameA, nameB, keyA, keyB) - continue - } - } - } - - // Make sure config fields that affect the tls config affect the cache key - uniqueConfigurations := map[string]*Config{ - "no tls": {}, - "insecure": {TLS: TLSConfig{Insecure: true}}, - "cadata 1": {TLS: TLSConfig{CAData: []byte{1}}}, - "cadata 2": {TLS: TLSConfig{CAData: []byte{2}}}, - "cert 1, key 1": { - TLS: TLSConfig{ - CertData: []byte{1}, - KeyData: []byte{1}, - }, - }, - "cert 1, key 2": { - TLS: TLSConfig{ - CertData: []byte{1}, - KeyData: []byte{2}, - }, - }, - "cert 2, key 1": { - TLS: TLSConfig{ - CertData: []byte{2}, - KeyData: []byte{1}, - }, - }, - "cert 2, key 2": { - TLS: TLSConfig{ - CertData: []byte{2}, - KeyData: []byte{2}, - }, - }, - "cadata 1, cert 1, key 1": { - TLS: TLSConfig{ - CAData: []byte{1}, - CertData: []byte{1}, - KeyData: []byte{1}, - }, - }, - } - for nameA, valueA := range uniqueConfigurations { - for nameB, valueB := range uniqueConfigurations { - // Don't compare to ourselves - if nameA == nameB { - continue - } - - keyA, err := tlsConfigKey(valueA) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameA, err) - continue - } - keyB, err := tlsConfigKey(valueB) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameB, err) - continue - } - if keyA == keyB { - t.Errorf("Expected unique cache keys for %q and %q, got:\n\t%s\n\t%s", nameA, nameB, keyA, keyB) - continue - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/round_trippers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/round_trippers_test.go deleted file mode 100644 index 6e8e52f7d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/round_trippers_test.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package transport - -import ( - "net/http" - "testing" -) - -type testRoundTripper struct { - Request *http.Request - Response *http.Response - Err error -} - -func (rt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - rt.Request = req - return rt.Response, rt.Err -} - -func TestBearerAuthRoundTripper(t *testing.T) { - rt := &testRoundTripper{} - req := &http.Request{} - NewBearerAuthRoundTripper("test", rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("unexpected nil request: %v", rt) - } - if rt.Request == req { - t.Fatalf("round tripper should have copied request object: %#v", rt.Request) - } - if rt.Request.Header.Get("Authorization") != "Bearer test" { - t.Errorf("unexpected authorization header: %#v", rt.Request) - } -} - -func TestBasicAuthRoundTripper(t *testing.T) { - for n, tc := range map[string]struct { - user string - pass string - }{ - "basic": {user: "user", pass: "pass"}, - "no pass": {user: "user"}, - } { - rt := &testRoundTripper{} - req := &http.Request{} - NewBasicAuthRoundTripper(tc.user, tc.pass, rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("%s: unexpected nil request: %v", n, rt) - } - if rt.Request == req { - t.Fatalf("%s: round tripper should have copied request object: %#v", n, rt.Request) - } - if user, pass, found := rt.Request.BasicAuth(); !found || user != tc.user || pass != tc.pass { - t.Errorf("%s: unexpected authorization header: %#v", n, rt.Request) - } - } -} - -func TestUserAgentRoundTripper(t *testing.T) { - rt := &testRoundTripper{} - req := &http.Request{ - Header: make(http.Header), - } - req.Header.Set("User-Agent", "other") - NewUserAgentRoundTripper("test", rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("unexpected nil request: %v", rt) - } - if rt.Request != req { - t.Fatalf("round tripper should not have copied request object: %#v", rt.Request) - } - if rt.Request.Header.Get("User-Agent") != "other" { - t.Errorf("unexpected user agent header: %#v", rt.Request) - } - - req = &http.Request{} - NewUserAgentRoundTripper("test", rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("unexpected nil request: %v", rt) - } - if rt.Request == req { - t.Fatalf("round tripper should have copied request object: %#v", rt.Request) - } - if rt.Request.Header.Get("User-Agent") != "test" { - t.Errorf("unexpected user agent header: %#v", rt.Request) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/transport_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/transport_test.go deleted file mode 100644 index ca04172d2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/transport/transport_test.go +++ /dev/null @@ -1,204 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package transport - -import ( - "net/http" - "testing" -) - -const ( - rootCACert = `-----BEGIN CERTIFICATE----- -MIIC4DCCAcqgAwIBAgIBATALBgkqhkiG9w0BAQswIzEhMB8GA1UEAwwYMTAuMTMu -MTI5LjEwNkAxNDIxMzU5MDU4MB4XDTE1MDExNTIxNTczN1oXDTE2MDExNTIxNTcz -OFowIzEhMB8GA1UEAwwYMTAuMTMuMTI5LjEwNkAxNDIxMzU5MDU4MIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAunDRXGwsiYWGFDlWH6kjGun+PshDGeZX -xtx9lUnL8pIRWH3wX6f13PO9sktaOWW0T0mlo6k2bMlSLlSZgG9H6og0W6gLS3vq -s4VavZ6DbXIwemZG2vbRwsvR+t4G6Nbwelm6F8RFnA1Fwt428pavmNQ/wgYzo+T1 -1eS+HiN4ACnSoDSx3QRWcgBkB1g6VReofVjx63i0J+w8Q/41L9GUuLqquFxu6ZnH -60vTB55lHgFiDLjA1FkEz2dGvGh/wtnFlRvjaPC54JH2K1mPYAUXTreoeJtLJKX0 -ycoiyB24+zGCniUmgIsmQWRPaOPircexCp1BOeze82BT1LCZNTVaxQIDAQABoyMw -ITAOBgNVHQ8BAf8EBAMCAKQwDwYDVR0TAQH/BAUwAwEB/zALBgkqhkiG9w0BAQsD -ggEBADMxsUuAFlsYDpF4fRCzXXwrhbtj4oQwcHpbu+rnOPHCZupiafzZpDu+rw4x -YGPnCb594bRTQn4pAu3Ac18NbLD5pV3uioAkv8oPkgr8aUhXqiv7KdDiaWm6sbAL -EHiXVBBAFvQws10HMqMoKtO8f1XDNAUkWduakR/U6yMgvOPwS7xl0eUTqyRB6zGb -K55q2dejiFWaFqB/y78txzvz6UlOZKE44g2JAVoJVM6kGaxh33q8/FmrL4kuN3ut -W+MmJCVDvd4eEqPwbp7146ZWTqpIJ8lvA6wuChtqV8lhAPka2hD/LMqY8iXNmfXD -uml0obOEy+ON91k+SWTJ3ggmF/U= ------END CERTIFICATE-----` - - certData = `-----BEGIN CERTIFICATE----- -MIIC6jCCAdSgAwIBAgIBCzALBgkqhkiG9w0BAQswIzEhMB8GA1UEAwwYMTAuMTMu -MTI5LjEwNkAxNDIxMzU5MDU4MB4XDTE1MDExNTIyMDEzMVoXDTE2MDExNTIyMDEz -MlowGzEZMBcGA1UEAxMQb3BlbnNoaWZ0LWNsaWVudDCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBAKtdhz0+uCLXw5cSYns9rU/XifFSpb/x24WDdrm72S/v -b9BPYsAStiP148buylr1SOuNi8sTAZmlVDDIpIVwMLff+o2rKYDicn9fjbrTxTOj -lI4pHJBH+JU3AJ0tbajupioh70jwFS0oYpwtneg2zcnE2Z4l6mhrj2okrc5Q1/X2 -I2HChtIU4JYTisObtin10QKJX01CLfYXJLa8upWzKZ4/GOcHG+eAV3jXWoXidtjb -1Usw70amoTZ6mIVCkiu1QwCoa8+ycojGfZhvqMsAp1536ZcCul+Na+AbCv4zKS7F -kQQaImVrXdUiFansIoofGlw/JNuoKK6ssVpS5Ic3pgcCAwEAAaM1MDMwDgYDVR0P -AQH/BAQDAgCgMBMGA1UdJQQMMAoGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwCwYJ -KoZIhvcNAQELA4IBAQCKLREH7bXtXtZ+8vI6cjD7W3QikiArGqbl36bAhhWsJLp/ -p/ndKz39iFNaiZ3GlwIURWOOKx3y3GA0x9m8FR+Llthf0EQ8sUjnwaknWs0Y6DQ3 -jjPFZOpV3KPCFrdMJ3++E3MgwFC/Ih/N2ebFX9EcV9Vcc6oVWMdwT0fsrhu683rq -6GSR/3iVX1G/pmOiuaR0fNUaCyCfYrnI4zHBDgSfnlm3vIvN2lrsR/DQBakNL8DJ -HBgKxMGeUPoneBv+c8DMXIL0EhaFXRlBv9QW45/GiAIOuyFJ0i6hCtGZpJjq4OpQ -BRjCI+izPzFTjsxD4aORE+WOkyWFCGPWKfNejfw0 ------END CERTIFICATE-----` - - keyData = `-----BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAq12HPT64ItfDlxJiez2tT9eJ8VKlv/HbhYN2ubvZL+9v0E9i -wBK2I/Xjxu7KWvVI642LyxMBmaVUMMikhXAwt9/6jaspgOJyf1+NutPFM6OUjikc -kEf4lTcAnS1tqO6mKiHvSPAVLShinC2d6DbNycTZniXqaGuPaiStzlDX9fYjYcKG -0hTglhOKw5u2KfXRAolfTUIt9hcktry6lbMpnj8Y5wcb54BXeNdaheJ22NvVSzDv -RqahNnqYhUKSK7VDAKhrz7JyiMZ9mG+oywCnXnfplwK6X41r4BsK/jMpLsWRBBoi -ZWtd1SIVqewiih8aXD8k26gorqyxWlLkhzemBwIDAQABAoIBAD2XYRs3JrGHQUpU -FkdbVKZkvrSY0vAZOqBTLuH0zUv4UATb8487anGkWBjRDLQCgxH+jucPTrztekQK -aW94clo0S3aNtV4YhbSYIHWs1a0It0UdK6ID7CmdWkAj6s0T8W8lQT7C46mWYVLm -5mFnCTHi6aB42jZrqmEpC7sivWwuU0xqj3Ml8kkxQCGmyc9JjmCB4OrFFC8NNt6M -ObvQkUI6Z3nO4phTbpxkE1/9dT0MmPIF7GhHVzJMS+EyyRYUDllZ0wvVSOM3qZT0 -JMUaBerkNwm9foKJ1+dv2nMKZZbJajv7suUDCfU44mVeaEO+4kmTKSGCGjjTBGkr -7L1ySDECgYEA5ElIMhpdBzIivCuBIH8LlUeuzd93pqssO1G2Xg0jHtfM4tz7fyeI -cr90dc8gpli24dkSxzLeg3Tn3wIj/Bu64m2TpZPZEIlukYvgdgArmRIPQVxerYey -OkrfTNkxU1HXsYjLCdGcGXs5lmb+K/kuTcFxaMOs7jZi7La+jEONwf8CgYEAwCs/ -rUOOA0klDsWWisbivOiNPII79c9McZCNBqncCBfMUoiGe8uWDEO4TFHN60vFuVk9 -8PkwpCfvaBUX+ajvbafIfHxsnfk1M04WLGCeqQ/ym5Q4sQoQOcC1b1y9qc/xEWfg -nIUuia0ukYRpl7qQa3tNg+BNFyjypW8zukUAC/kCgYB1/Kojuxx5q5/oQVPrx73k -2bevD+B3c+DYh9MJqSCNwFtUpYIWpggPxoQan4LwdsmO0PKzocb/ilyNFj4i/vII -NToqSc/WjDFpaDIKyuu9oWfhECye45NqLWhb/6VOuu4QA/Nsj7luMhIBehnEAHW+ -GkzTKM8oD1PxpEG3nPKXYQKBgQC6AuMPRt3XBl1NkCrpSBy/uObFlFaP2Enpf39S -3OZ0Gv0XQrnSaL1kP8TMcz68rMrGX8DaWYsgytstR4W+jyy7WvZwsUu+GjTJ5aMG -77uEcEBpIi9CBzivfn7hPccE8ZgqPf+n4i6q66yxBJflW5xhvafJqDtW2LcPNbW/ -bvzdmQKBgExALRUXpq+5dbmkdXBHtvXdRDZ6rVmrnjy4nI5bPw+1GqQqk6uAR6B/ -F6NmLCQOO4PDG/cuatNHIr2FrwTmGdEL6ObLUGWn9Oer9gJhHVqqsY5I4sEPo4XX -stR0Yiw0buV6DL/moUO0HIM9Bjh96HJp+LxiIS6UCdIhMPp5HoQa ------END RSA PRIVATE KEY-----` -) - -func TestNew(t *testing.T) { - testCases := map[string]struct { - Config *Config - Err bool - TLS bool - Default bool - }{ - "default transport": { - Default: true, - Config: &Config{}, - }, - - "ca transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - }, - }, - }, - "bad ca file transport": { - Err: true, - Config: &Config{ - TLS: TLSConfig{ - CAFile: "invalid file", - }, - }, - }, - "ca data overriding bad ca file transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CAFile: "invalid file", - }, - }, - }, - - "cert transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyData: []byte(keyData), - }, - }, - }, - "bad cert data transport": { - Err: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyData: []byte("bad key data"), - }, - }, - }, - "bad file cert transport": { - Err: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyFile: "invalid file", - }, - }, - }, - "key data overriding bad file cert transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyData: []byte(keyData), - KeyFile: "invalid file", - }, - }, - }, - } - for k, testCase := range testCases { - transport, err := New(testCase.Config) - switch { - case testCase.Err && err == nil: - t.Errorf("%s: unexpected non-error", k) - continue - case !testCase.Err && err != nil: - t.Errorf("%s: unexpected error: %v", k, err) - continue - } - - switch { - case testCase.Default && transport != http.DefaultTransport: - t.Errorf("%s: expected the default transport, got %#v", k, transport) - continue - case !testCase.Default && transport == http.DefaultTransport: - t.Errorf("%s: expected non-default transport, got %#v", k, transport) - continue - } - - // We only know how to check TLSConfig on http.Transports - if transport, ok := transport.(*http.Transport); ok { - switch { - case testCase.TLS && transport.TLSClientConfig == nil: - t.Errorf("%s: expected TLSClientConfig, got %#v", k, transport) - continue - case !testCase.TLS && transport.TLSClientConfig != nil: - t.Errorf("%s: expected no TLSClientConfig, got %#v", k, transport) - continue - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/discovery_client.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/discovery/discovery_client.go similarity index 90% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/discovery_client.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/discovery/discovery_client.go index f43d728fb..fa4d94a34 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/discovery_client.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/discovery/discovery_client.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package unversioned +package discovery import ( "encoding/json" @@ -27,6 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/version" ) @@ -70,7 +71,7 @@ type SwaggerSchemaInterface interface { // DiscoveryClient implements the functions that discover server-supported API groups, // versions and resources. type DiscoveryClient struct { - *RESTClient + *restclient.RESTClient } // Convert unversioned.APIVersions to unversioned.APIGroup. APIVersions is used by legacy v1, so @@ -147,7 +148,7 @@ func (d *DiscoveryClient) ServerResources() (map[string]*unversioned.APIResource if err != nil { return nil, err } - groupVersions := ExtractGroupVersions(apiGroups) + groupVersions := unversioned.ExtractGroupVersions(apiGroups) result := map[string]*unversioned.APIResourceList{} for _, groupVersion := range groupVersions { resources, err := d.ServerResourcesForGroupVersion(groupVersion) @@ -183,7 +184,7 @@ func (d *DiscoveryClient) SwaggerSchema(version unversioned.GroupVersion) (*swag if err != nil { return nil, err } - groupVersions := ExtractGroupVersions(groupList) + groupVersions := unversioned.ExtractGroupVersions(groupList) // This check also takes care the case that kubectl is newer than the running endpoint if stringDoesntExistIn(version.String(), groupVersions) { return nil, fmt.Errorf("API version: %v is not supported by the server. Use one of: %v", version, groupVersions) @@ -207,27 +208,30 @@ func (d *DiscoveryClient) SwaggerSchema(version unversioned.GroupVersion) (*swag return &schema, nil } -func setDiscoveryDefaults(config *Config) error { +func setDiscoveryDefaults(config *restclient.Config) error { config.APIPath = "" config.GroupVersion = nil config.Codec = runtime.NoopEncoder{api.Codecs.UniversalDecoder()} + if len(config.UserAgent) == 0 { + config.UserAgent = restclient.DefaultKubernetesUserAgent() + } return nil } // NewDiscoveryClientForConfig creates a new DiscoveryClient for the given config. This client // can be used to discover supported resources in the API server. -func NewDiscoveryClientForConfig(c *Config) (*DiscoveryClient, error) { +func NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error) { config := *c if err := setDiscoveryDefaults(&config); err != nil { return nil, err } - client, err := UnversionedRESTClientFor(&config) + client, err := restclient.UnversionedRESTClientFor(&config) return &DiscoveryClient{client}, err } // NewDiscoveryClientForConfig creates a new DiscoveryClient for the given config. If // there is an error, it panics. -func NewDiscoveryClientForConfigOrDie(c *Config) *DiscoveryClient { +func NewDiscoveryClientForConfigOrDie(c *restclient.Config) *DiscoveryClient { client, err := NewDiscoveryClientForConfig(c) if err != nil { panic(err) @@ -237,6 +241,15 @@ func NewDiscoveryClientForConfigOrDie(c *Config) *DiscoveryClient { } // New creates a new DiscoveryClient for the given RESTClient. -func NewDiscoveryClient(c *RESTClient) *DiscoveryClient { +func NewDiscoveryClient(c *restclient.RESTClient) *DiscoveryClient { return &DiscoveryClient{c} } + +func stringDoesntExistIn(str string, slice []string) bool { + for _, s := range slice { + if s == str { + return false + } + } + return true +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/core_client.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/core_client.go index c8119031e..dc3561c0b 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/core_client.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/core_client.go @@ -19,7 +19,7 @@ package unversioned import ( api "k8s.io/kubernetes/pkg/api" registered "k8s.io/kubernetes/pkg/apimachinery/registered" - unversioned "k8s.io/kubernetes/pkg/client/unversioned" + restclient "k8s.io/kubernetes/pkg/client/restclient" ) type CoreInterface interface { @@ -43,7 +43,7 @@ type CoreInterface interface { // CoreClient is used to interact with features provided by the Core group. type CoreClient struct { - *unversioned.RESTClient + *restclient.RESTClient } func (c *CoreClient) ComponentStatuses() ComponentStatusInterface { @@ -111,12 +111,12 @@ func (c *CoreClient) ServiceAccounts(namespace string) ServiceAccountInterface { } // NewForConfig creates a new CoreClient for the given config. -func NewForConfig(c *unversioned.Config) (*CoreClient, error) { +func NewForConfig(c *restclient.Config) (*CoreClient, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } - client, err := unversioned.RESTClientFor(&config) + client, err := restclient.RESTClientFor(&config) if err != nil { return nil, err } @@ -125,7 +125,7 @@ func NewForConfig(c *unversioned.Config) (*CoreClient, error) { // NewForConfigOrDie creates a new CoreClient for the given config and // panics if there is an error in the config. -func NewForConfigOrDie(c *unversioned.Config) *CoreClient { +func NewForConfigOrDie(c *restclient.Config) *CoreClient { client, err := NewForConfig(c) if err != nil { panic(err) @@ -134,11 +134,11 @@ func NewForConfigOrDie(c *unversioned.Config) *CoreClient { } // New creates a new CoreClient for the given RESTClient. -func New(c *unversioned.RESTClient) *CoreClient { +func New(c *restclient.RESTClient) *CoreClient { return &CoreClient{c} } -func setConfigDefaults(config *unversioned.Config) error { +func setConfigDefaults(config *restclient.Config) error { // if core group is not registered, return an error g, err := registered.Group("") if err != nil { @@ -146,7 +146,7 @@ func setConfigDefaults(config *unversioned.Config) error { } config.APIPath = "/api" if config.UserAgent == "" { - config.UserAgent = unversioned.DefaultKubernetesUserAgent() + config.UserAgent = restclient.DefaultKubernetesUserAgent() } // TODO: Unconditionally set the config.Version, until we fix the config. //if config.Version == "" { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/doc.go deleted file mode 100644 index dd6d4da71..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -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. -*/ - -// Package fake has the automatically generated clients. -package fake diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_componentstatus.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_componentstatus.go deleted file mode 100644 index 478dd9dbf..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_componentstatus.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeComponentStatuses implements ComponentStatusInterface -type FakeComponentStatuses struct { - Fake *FakeCore -} - -func (c *FakeComponentStatuses) Create(componentStatus *api.ComponentStatus) (result *api.ComponentStatus, err error) { - obj, err := c.Fake. - Invokes(core.NewRootCreateAction("componentstatuses", componentStatus), &api.ComponentStatus{}) - if obj == nil { - return nil, err - } - return obj.(*api.ComponentStatus), err -} - -func (c *FakeComponentStatuses) Update(componentStatus *api.ComponentStatus) (result *api.ComponentStatus, err error) { - obj, err := c.Fake. - Invokes(core.NewRootUpdateAction("componentstatuses", componentStatus), &api.ComponentStatus{}) - if obj == nil { - return nil, err - } - return obj.(*api.ComponentStatus), err -} - -func (c *FakeComponentStatuses) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewRootDeleteAction("componentstatuses", name), &api.ComponentStatus{}) - return err -} - -func (c *FakeComponentStatuses) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewRootDeleteCollectionAction("componentstatuses", listOptions) - - _, err := c.Fake.Invokes(action, &api.ComponentStatusList{}) - return err -} - -func (c *FakeComponentStatuses) Get(name string) (result *api.ComponentStatus, err error) { - obj, err := c.Fake. - Invokes(core.NewRootGetAction("componentstatuses", name), &api.ComponentStatus{}) - if obj == nil { - return nil, err - } - return obj.(*api.ComponentStatus), err -} - -func (c *FakeComponentStatuses) List(opts api.ListOptions) (result *api.ComponentStatusList, err error) { - obj, err := c.Fake. - Invokes(core.NewRootListAction("componentstatuses", opts), &api.ComponentStatusList{}) - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.ComponentStatusList{} - for _, item := range obj.(*api.ComponentStatusList).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 componentStatuses. -func (c *FakeComponentStatuses) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewRootWatchAction("componentstatuses", opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_configmap.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_configmap.go deleted file mode 100644 index 34fa0b229..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_configmap.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeConfigMaps implements ConfigMapInterface -type FakeConfigMaps struct { - Fake *FakeCore - ns string -} - -func (c *FakeConfigMaps) Create(configMap *api.ConfigMap) (result *api.ConfigMap, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("configmaps", c.ns, configMap), &api.ConfigMap{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ConfigMap), err -} - -func (c *FakeConfigMaps) Update(configMap *api.ConfigMap) (result *api.ConfigMap, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("configmaps", c.ns, configMap), &api.ConfigMap{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ConfigMap), err -} - -func (c *FakeConfigMaps) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("configmaps", c.ns, name), &api.ConfigMap{}) - - return err -} - -func (c *FakeConfigMaps) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("configmaps", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.ConfigMapList{}) - return err -} - -func (c *FakeConfigMaps) Get(name string) (result *api.ConfigMap, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("configmaps", c.ns, name), &api.ConfigMap{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ConfigMap), err -} - -func (c *FakeConfigMaps) List(opts api.ListOptions) (result *api.ConfigMapList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("configmaps", c.ns, opts), &api.ConfigMapList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.ConfigMapList{} - for _, item := range obj.(*api.ConfigMapList).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 configMaps. -func (c *FakeConfigMaps) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("configmaps", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_core_client.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_core_client.go deleted file mode 100644 index afc6cf6f9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_core_client.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - core "k8s.io/kubernetes/pkg/client/testing/core" - unversioned "k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned" -) - -type FakeCore struct { - *core.Fake -} - -func (c *FakeCore) ComponentStatuses() unversioned.ComponentStatusInterface { - return &FakeComponentStatuses{c} -} - -func (c *FakeCore) ConfigMaps(namespace string) unversioned.ConfigMapInterface { - return &FakeConfigMaps{c, namespace} -} - -func (c *FakeCore) Endpoints(namespace string) unversioned.EndpointsInterface { - return &FakeEndpoints{c, namespace} -} - -func (c *FakeCore) Events(namespace string) unversioned.EventInterface { - return &FakeEvents{c, namespace} -} - -func (c *FakeCore) LimitRanges(namespace string) unversioned.LimitRangeInterface { - return &FakeLimitRanges{c, namespace} -} - -func (c *FakeCore) Namespaces() unversioned.NamespaceInterface { - return &FakeNamespaces{c} -} - -func (c *FakeCore) Nodes() unversioned.NodeInterface { - return &FakeNodes{c} -} - -func (c *FakeCore) PersistentVolumes() unversioned.PersistentVolumeInterface { - return &FakePersistentVolumes{c} -} - -func (c *FakeCore) PersistentVolumeClaims(namespace string) unversioned.PersistentVolumeClaimInterface { - return &FakePersistentVolumeClaims{c, namespace} -} - -func (c *FakeCore) Pods(namespace string) unversioned.PodInterface { - return &FakePods{c, namespace} -} - -func (c *FakeCore) PodTemplates(namespace string) unversioned.PodTemplateInterface { - return &FakePodTemplates{c, namespace} -} - -func (c *FakeCore) ReplicationControllers(namespace string) unversioned.ReplicationControllerInterface { - return &FakeReplicationControllers{c, namespace} -} - -func (c *FakeCore) ResourceQuotas(namespace string) unversioned.ResourceQuotaInterface { - return &FakeResourceQuotas{c, namespace} -} - -func (c *FakeCore) Secrets(namespace string) unversioned.SecretInterface { - return &FakeSecrets{c, namespace} -} - -func (c *FakeCore) Services(namespace string) unversioned.ServiceInterface { - return &FakeServices{c, namespace} -} - -func (c *FakeCore) ServiceAccounts(namespace string) unversioned.ServiceAccountInterface { - return &FakeServiceAccounts{c, namespace} -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_endpoints.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_endpoints.go deleted file mode 100644 index cc25b6e06..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_endpoints.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeEndpoints implements EndpointsInterface -type FakeEndpoints struct { - Fake *FakeCore - ns string -} - -func (c *FakeEndpoints) Create(endpoints *api.Endpoints) (result *api.Endpoints, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("endpoints", c.ns, endpoints), &api.Endpoints{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Endpoints), err -} - -func (c *FakeEndpoints) Update(endpoints *api.Endpoints) (result *api.Endpoints, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("endpoints", c.ns, endpoints), &api.Endpoints{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Endpoints), err -} - -func (c *FakeEndpoints) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("endpoints", c.ns, name), &api.Endpoints{}) - - return err -} - -func (c *FakeEndpoints) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("endpoints", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.EndpointsList{}) - return err -} - -func (c *FakeEndpoints) Get(name string) (result *api.Endpoints, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("endpoints", c.ns, name), &api.Endpoints{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Endpoints), err -} - -func (c *FakeEndpoints) List(opts api.ListOptions) (result *api.EndpointsList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("endpoints", c.ns, opts), &api.EndpointsList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.EndpointsList{} - for _, item := range obj.(*api.EndpointsList).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 endpoints. -func (c *FakeEndpoints) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("endpoints", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_event.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_event.go deleted file mode 100644 index a9f88153b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_event.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeEvents implements EventInterface -type FakeEvents struct { - Fake *FakeCore - ns string -} - -func (c *FakeEvents) Create(event *api.Event) (result *api.Event, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("events", c.ns, event), &api.Event{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Event), err -} - -func (c *FakeEvents) Update(event *api.Event) (result *api.Event, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("events", c.ns, event), &api.Event{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Event), err -} - -func (c *FakeEvents) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("events", c.ns, name), &api.Event{}) - - return err -} - -func (c *FakeEvents) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("events", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.EventList{}) - return err -} - -func (c *FakeEvents) Get(name string) (result *api.Event, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("events", c.ns, name), &api.Event{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Event), err -} - -func (c *FakeEvents) List(opts api.ListOptions) (result *api.EventList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("events", c.ns, opts), &api.EventList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.EventList{} - for _, item := range obj.(*api.EventList).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 events. -func (c *FakeEvents) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("events", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_event_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_event_expansion.go deleted file mode 100644 index bc514d505..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_event_expansion.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package fake - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/testing/core" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/runtime" -) - -func (c *FakeEvents) CreateWithEventNamespace(event *api.Event) (*api.Event, error) { - action := core.NewRootCreateAction("events", event) - if c.ns != "" { - action = core.NewCreateAction("events", c.ns, event) - } - obj, err := c.Fake.Invokes(action, event) - if obj == nil { - return nil, err - } - - return obj.(*api.Event), err -} - -// Update replaces an existing event. Returns the copy of the event the server returns, or an error. -func (c *FakeEvents) UpdateWithEventNamespace(event *api.Event) (*api.Event, error) { - action := core.NewRootUpdateAction("events", event) - if c.ns != "" { - action = core.NewUpdateAction("events", c.ns, event) - } - obj, err := c.Fake.Invokes(action, event) - if obj == nil { - return nil, 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("events", event) - if c.ns != "" { - action = core.NewPatchAction("events", c.ns, event) - } - obj, err := c.Fake.Invokes(action, event) - if obj == nil { - return nil, err - } - - return obj.(*api.Event), err -} - -// Search returns a list of events matching the specified object. -func (c *FakeEvents) Search(objOrRef runtime.Object) (*api.EventList, error) { - action := core.NewRootListAction("events", api.ListOptions{}) - if c.ns != "" { - action = core.NewListAction("events", c.ns, api.ListOptions{}) - } - obj, err := c.Fake.Invokes(action, &api.EventList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.EventList), err -} - -func (c *FakeEvents) GetFieldSelector(involvedObjectName, involvedObjectNamespace, involvedObjectKind, involvedObjectUID *string) fields.Selector { - action := core.GenericActionImpl{} - action.Verb = "get-field-selector" - action.Resource = "events" - - c.Fake.Invokes(action, nil) - return fields.Everything() -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_limitrange.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_limitrange.go deleted file mode 100644 index cab44ce4e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_limitrange.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeLimitRanges implements LimitRangeInterface -type FakeLimitRanges struct { - Fake *FakeCore - ns string -} - -func (c *FakeLimitRanges) Create(limitRange *api.LimitRange) (result *api.LimitRange, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("limitranges", c.ns, limitRange), &api.LimitRange{}) - - if obj == nil { - return nil, err - } - return obj.(*api.LimitRange), err -} - -func (c *FakeLimitRanges) Update(limitRange *api.LimitRange) (result *api.LimitRange, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("limitranges", c.ns, limitRange), &api.LimitRange{}) - - if obj == nil { - return nil, err - } - return obj.(*api.LimitRange), err -} - -func (c *FakeLimitRanges) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("limitranges", c.ns, name), &api.LimitRange{}) - - return err -} - -func (c *FakeLimitRanges) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("limitranges", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.LimitRangeList{}) - return err -} - -func (c *FakeLimitRanges) Get(name string) (result *api.LimitRange, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("limitranges", c.ns, name), &api.LimitRange{}) - - if obj == nil { - return nil, err - } - return obj.(*api.LimitRange), err -} - -func (c *FakeLimitRanges) List(opts api.ListOptions) (result *api.LimitRangeList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("limitranges", c.ns, opts), &api.LimitRangeList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.LimitRangeList{} - for _, item := range obj.(*api.LimitRangeList).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 limitRanges. -func (c *FakeLimitRanges) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("limitranges", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_namespace.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_namespace.go deleted file mode 100644 index 78933814f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_namespace.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeNamespaces implements NamespaceInterface -type FakeNamespaces struct { - Fake *FakeCore -} - -func (c *FakeNamespaces) Create(namespace *api.Namespace) (result *api.Namespace, err error) { - obj, err := c.Fake. - Invokes(core.NewRootCreateAction("namespaces", namespace), &api.Namespace{}) - if obj == nil { - return nil, err - } - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) Update(namespace *api.Namespace) (result *api.Namespace, err error) { - obj, err := c.Fake. - Invokes(core.NewRootUpdateAction("namespaces", namespace), &api.Namespace{}) - if obj == nil { - return nil, err - } - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) UpdateStatus(namespace *api.Namespace) (*api.Namespace, error) { - obj, err := c.Fake. - Invokes(core.NewRootUpdateSubresourceAction("namespaces", "status", namespace), &api.Namespace{}) - if obj == nil { - return nil, err - } - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewRootDeleteAction("namespaces", name), &api.Namespace{}) - return err -} - -func (c *FakeNamespaces) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewRootDeleteCollectionAction("namespaces", listOptions) - - _, err := c.Fake.Invokes(action, &api.NamespaceList{}) - return err -} - -func (c *FakeNamespaces) Get(name string) (result *api.Namespace, err error) { - obj, err := c.Fake. - Invokes(core.NewRootGetAction("namespaces", name), &api.Namespace{}) - if obj == nil { - return nil, err - } - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) List(opts api.ListOptions) (result *api.NamespaceList, err error) { - obj, err := c.Fake. - Invokes(core.NewRootListAction("namespaces", opts), &api.NamespaceList{}) - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.NamespaceList{} - for _, item := range obj.(*api.NamespaceList).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 namespaces. -func (c *FakeNamespaces) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewRootWatchAction("namespaces", opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_namespace_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_namespace_expansion.go deleted file mode 100644 index 8bb49ff2b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_namespace_expansion.go +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package fake - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/testing/core" -) - -func (c *FakeNamespaces) Finalize(namespace *api.Namespace) (*api.Namespace, error) { - action := core.CreateActionImpl{} - action.Verb = "create" - action.Resource = "namespaces" - action.Subresource = "finalize" - action.Object = namespace - - obj, err := c.Fake.Invokes(action, namespace) - if obj == nil { - return nil, err - } - - return obj.(*api.Namespace), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_node.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_node.go deleted file mode 100644 index 8761c8772..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_node.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeNodes implements NodeInterface -type FakeNodes struct { - Fake *FakeCore -} - -func (c *FakeNodes) Create(node *api.Node) (result *api.Node, err error) { - obj, err := c.Fake. - Invokes(core.NewRootCreateAction("nodes", node), &api.Node{}) - if obj == nil { - return nil, err - } - return obj.(*api.Node), err -} - -func (c *FakeNodes) Update(node *api.Node) (result *api.Node, err error) { - obj, err := c.Fake. - Invokes(core.NewRootUpdateAction("nodes", node), &api.Node{}) - if obj == nil { - return nil, err - } - return obj.(*api.Node), err -} - -func (c *FakeNodes) UpdateStatus(node *api.Node) (*api.Node, error) { - obj, err := c.Fake. - Invokes(core.NewRootUpdateSubresourceAction("nodes", "status", node), &api.Node{}) - if obj == nil { - return nil, err - } - return obj.(*api.Node), err -} - -func (c *FakeNodes) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewRootDeleteAction("nodes", name), &api.Node{}) - return err -} - -func (c *FakeNodes) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewRootDeleteCollectionAction("nodes", listOptions) - - _, err := c.Fake.Invokes(action, &api.NodeList{}) - return err -} - -func (c *FakeNodes) Get(name string) (result *api.Node, err error) { - obj, err := c.Fake. - Invokes(core.NewRootGetAction("nodes", name), &api.Node{}) - if obj == nil { - return nil, err - } - return obj.(*api.Node), err -} - -func (c *FakeNodes) List(opts api.ListOptions) (result *api.NodeList, err error) { - obj, err := c.Fake. - Invokes(core.NewRootListAction("nodes", opts), &api.NodeList{}) - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.NodeList{} - for _, item := range obj.(*api.NodeList).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 nodes. -func (c *FakeNodes) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewRootWatchAction("nodes", opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_persistentvolume.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_persistentvolume.go deleted file mode 100644 index d3d8c79f5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_persistentvolume.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakePersistentVolumes implements PersistentVolumeInterface -type FakePersistentVolumes struct { - Fake *FakeCore -} - -func (c *FakePersistentVolumes) Create(persistentVolume *api.PersistentVolume) (result *api.PersistentVolume, err error) { - obj, err := c.Fake. - Invokes(core.NewRootCreateAction("persistentvolumes", persistentVolume), &api.PersistentVolume{}) - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolume), err -} - -func (c *FakePersistentVolumes) Update(persistentVolume *api.PersistentVolume) (result *api.PersistentVolume, err error) { - obj, err := c.Fake. - Invokes(core.NewRootUpdateAction("persistentvolumes", persistentVolume), &api.PersistentVolume{}) - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolume), err -} - -func (c *FakePersistentVolumes) UpdateStatus(persistentVolume *api.PersistentVolume) (*api.PersistentVolume, error) { - obj, err := c.Fake. - Invokes(core.NewRootUpdateSubresourceAction("persistentvolumes", "status", persistentVolume), &api.PersistentVolume{}) - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolume), err -} - -func (c *FakePersistentVolumes) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewRootDeleteAction("persistentvolumes", name), &api.PersistentVolume{}) - return err -} - -func (c *FakePersistentVolumes) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewRootDeleteCollectionAction("persistentvolumes", listOptions) - - _, err := c.Fake.Invokes(action, &api.PersistentVolumeList{}) - return err -} - -func (c *FakePersistentVolumes) Get(name string) (result *api.PersistentVolume, err error) { - obj, err := c.Fake. - Invokes(core.NewRootGetAction("persistentvolumes", name), &api.PersistentVolume{}) - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolume), err -} - -func (c *FakePersistentVolumes) List(opts api.ListOptions) (result *api.PersistentVolumeList, err error) { - obj, err := c.Fake. - Invokes(core.NewRootListAction("persistentvolumes", opts), &api.PersistentVolumeList{}) - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.PersistentVolumeList{} - for _, item := range obj.(*api.PersistentVolumeList).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 persistentVolumes. -func (c *FakePersistentVolumes) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewRootWatchAction("persistentvolumes", opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_persistentvolumeclaim.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_persistentvolumeclaim.go deleted file mode 100644 index ba674f269..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_persistentvolumeclaim.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakePersistentVolumeClaims implements PersistentVolumeClaimInterface -type FakePersistentVolumeClaims struct { - Fake *FakeCore - ns string -} - -func (c *FakePersistentVolumeClaims) Create(persistentVolumeClaim *api.PersistentVolumeClaim) (result *api.PersistentVolumeClaim, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("persistentvolumeclaims", c.ns, persistentVolumeClaim), &api.PersistentVolumeClaim{}) - - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolumeClaim), err -} - -func (c *FakePersistentVolumeClaims) Update(persistentVolumeClaim *api.PersistentVolumeClaim) (result *api.PersistentVolumeClaim, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("persistentvolumeclaims", c.ns, persistentVolumeClaim), &api.PersistentVolumeClaim{}) - - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolumeClaim), err -} - -func (c *FakePersistentVolumeClaims) UpdateStatus(persistentVolumeClaim *api.PersistentVolumeClaim) (*api.PersistentVolumeClaim, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("persistentvolumeclaims", "status", c.ns, persistentVolumeClaim), &api.PersistentVolumeClaim{}) - - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolumeClaim), err -} - -func (c *FakePersistentVolumeClaims) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("persistentvolumeclaims", c.ns, name), &api.PersistentVolumeClaim{}) - - return err -} - -func (c *FakePersistentVolumeClaims) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("persistentvolumeclaims", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.PersistentVolumeClaimList{}) - return err -} - -func (c *FakePersistentVolumeClaims) Get(name string) (result *api.PersistentVolumeClaim, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("persistentvolumeclaims", c.ns, name), &api.PersistentVolumeClaim{}) - - if obj == nil { - return nil, err - } - return obj.(*api.PersistentVolumeClaim), err -} - -func (c *FakePersistentVolumeClaims) List(opts api.ListOptions) (result *api.PersistentVolumeClaimList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("persistentvolumeclaims", c.ns, opts), &api.PersistentVolumeClaimList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.PersistentVolumeClaimList{} - for _, item := range obj.(*api.PersistentVolumeClaimList).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 persistentVolumeClaims. -func (c *FakePersistentVolumeClaims) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("persistentvolumeclaims", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_pod.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_pod.go deleted file mode 100644 index 6488c021d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_pod.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakePods implements PodInterface -type FakePods struct { - Fake *FakeCore - ns string -} - -func (c *FakePods) Create(pod *api.Pod) (result *api.Pod, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("pods", c.ns, pod), &api.Pod{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Pod), err -} - -func (c *FakePods) Update(pod *api.Pod) (result *api.Pod, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("pods", c.ns, pod), &api.Pod{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Pod), err -} - -func (c *FakePods) UpdateStatus(pod *api.Pod) (*api.Pod, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("pods", "status", c.ns, pod), &api.Pod{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Pod), err -} - -func (c *FakePods) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("pods", c.ns, name), &api.Pod{}) - - return err -} - -func (c *FakePods) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("pods", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.PodList{}) - return err -} - -func (c *FakePods) Get(name string) (result *api.Pod, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("pods", c.ns, name), &api.Pod{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Pod), err -} - -func (c *FakePods) List(opts api.ListOptions) (result *api.PodList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("pods", c.ns, opts), &api.PodList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.PodList{} - for _, item := range obj.(*api.PodList).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 pods. -func (c *FakePods) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("pods", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_pod_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_pod_expansion.go deleted file mode 100644 index 034ecf2b2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_pod_expansion.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package fake - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/testing/core" - client "k8s.io/kubernetes/pkg/client/unversioned" -) - -func (c *FakePods) Bind(binding *api.Binding) error { - action := core.CreateActionImpl{} - action.Verb = "create" - action.Resource = "pods" - action.Subresource = "bindings" - action.Object = binding - - _, err := c.Fake.Invokes(action, binding) - return err -} - -func (c *FakePods) GetLogs(name string, opts *api.PodLogOptions) *client.Request { - action := core.GenericActionImpl{} - action.Verb = "get" - action.Namespace = c.ns - action.Resource = "pod" - action.Subresource = "logs" - action.Value = opts - - _, _ = c.Fake.Invokes(action, &api.Pod{}) - return &client.Request{} -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_podtemplate.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_podtemplate.go deleted file mode 100644 index b900a113c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_podtemplate.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakePodTemplates implements PodTemplateInterface -type FakePodTemplates struct { - Fake *FakeCore - ns string -} - -func (c *FakePodTemplates) Create(podTemplate *api.PodTemplate) (result *api.PodTemplate, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("podtemplates", c.ns, podTemplate), &api.PodTemplate{}) - - if obj == nil { - return nil, err - } - return obj.(*api.PodTemplate), err -} - -func (c *FakePodTemplates) Update(podTemplate *api.PodTemplate) (result *api.PodTemplate, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("podtemplates", c.ns, podTemplate), &api.PodTemplate{}) - - if obj == nil { - return nil, err - } - return obj.(*api.PodTemplate), err -} - -func (c *FakePodTemplates) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("podtemplates", c.ns, name), &api.PodTemplate{}) - - return err -} - -func (c *FakePodTemplates) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("podtemplates", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.PodTemplateList{}) - return err -} - -func (c *FakePodTemplates) Get(name string) (result *api.PodTemplate, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("podtemplates", c.ns, name), &api.PodTemplate{}) - - if obj == nil { - return nil, err - } - return obj.(*api.PodTemplate), err -} - -func (c *FakePodTemplates) List(opts api.ListOptions) (result *api.PodTemplateList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("podtemplates", c.ns, opts), &api.PodTemplateList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.PodTemplateList{} - for _, item := range obj.(*api.PodTemplateList).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 podTemplates. -func (c *FakePodTemplates) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("podtemplates", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_replicationcontroller.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_replicationcontroller.go deleted file mode 100644 index 205f09456..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_replicationcontroller.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeReplicationControllers implements ReplicationControllerInterface -type FakeReplicationControllers struct { - Fake *FakeCore - ns string -} - -func (c *FakeReplicationControllers) Create(replicationController *api.ReplicationController) (result *api.ReplicationController, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("replicationcontrollers", c.ns, replicationController), &api.ReplicationController{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) Update(replicationController *api.ReplicationController) (result *api.ReplicationController, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("replicationcontrollers", c.ns, replicationController), &api.ReplicationController{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) UpdateStatus(replicationController *api.ReplicationController) (*api.ReplicationController, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("replicationcontrollers", "status", c.ns, replicationController), &api.ReplicationController{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("replicationcontrollers", c.ns, name), &api.ReplicationController{}) - - return err -} - -func (c *FakeReplicationControllers) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("replicationcontrollers", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.ReplicationControllerList{}) - return err -} - -func (c *FakeReplicationControllers) Get(name string) (result *api.ReplicationController, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("replicationcontrollers", c.ns, name), &api.ReplicationController{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) List(opts api.ListOptions) (result *api.ReplicationControllerList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("replicationcontrollers", c.ns, opts), &api.ReplicationControllerList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.ReplicationControllerList{} - for _, item := range obj.(*api.ReplicationControllerList).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 replicationControllers. -func (c *FakeReplicationControllers) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("replicationcontrollers", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_resourcequota.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_resourcequota.go deleted file mode 100644 index 056e61ed5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_resourcequota.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeResourceQuotas implements ResourceQuotaInterface -type FakeResourceQuotas struct { - Fake *FakeCore - ns string -} - -func (c *FakeResourceQuotas) Create(resourceQuota *api.ResourceQuota) (result *api.ResourceQuota, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("resourcequotas", c.ns, resourceQuota), &api.ResourceQuota{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ResourceQuota), err -} - -func (c *FakeResourceQuotas) Update(resourceQuota *api.ResourceQuota) (result *api.ResourceQuota, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("resourcequotas", c.ns, resourceQuota), &api.ResourceQuota{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ResourceQuota), err -} - -func (c *FakeResourceQuotas) UpdateStatus(resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("resourcequotas", "status", c.ns, resourceQuota), &api.ResourceQuota{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ResourceQuota), err -} - -func (c *FakeResourceQuotas) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("resourcequotas", c.ns, name), &api.ResourceQuota{}) - - return err -} - -func (c *FakeResourceQuotas) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("resourcequotas", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.ResourceQuotaList{}) - return err -} - -func (c *FakeResourceQuotas) Get(name string) (result *api.ResourceQuota, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("resourcequotas", c.ns, name), &api.ResourceQuota{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ResourceQuota), err -} - -func (c *FakeResourceQuotas) List(opts api.ListOptions) (result *api.ResourceQuotaList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("resourcequotas", c.ns, opts), &api.ResourceQuotaList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.ResourceQuotaList{} - for _, item := range obj.(*api.ResourceQuotaList).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 resourceQuotas. -func (c *FakeResourceQuotas) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("resourcequotas", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_secret.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_secret.go deleted file mode 100644 index 2f09be6e5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_secret.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeSecrets implements SecretInterface -type FakeSecrets struct { - Fake *FakeCore - ns string -} - -func (c *FakeSecrets) Create(secret *api.Secret) (result *api.Secret, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("secrets", c.ns, secret), &api.Secret{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Secret), err -} - -func (c *FakeSecrets) Update(secret *api.Secret) (result *api.Secret, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("secrets", c.ns, secret), &api.Secret{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Secret), err -} - -func (c *FakeSecrets) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("secrets", c.ns, name), &api.Secret{}) - - return err -} - -func (c *FakeSecrets) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("secrets", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.SecretList{}) - return err -} - -func (c *FakeSecrets) Get(name string) (result *api.Secret, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("secrets", c.ns, name), &api.Secret{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Secret), err -} - -func (c *FakeSecrets) List(opts api.ListOptions) (result *api.SecretList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("secrets", c.ns, opts), &api.SecretList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.SecretList{} - for _, item := range obj.(*api.SecretList).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 secrets. -func (c *FakeSecrets) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("secrets", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_service.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_service.go deleted file mode 100644 index 2cf38901c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_service.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeServices implements ServiceInterface -type FakeServices struct { - Fake *FakeCore - ns string -} - -func (c *FakeServices) Create(service *api.Service) (result *api.Service, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("services", c.ns, service), &api.Service{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Service), err -} - -func (c *FakeServices) Update(service *api.Service) (result *api.Service, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("services", c.ns, service), &api.Service{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Service), err -} - -func (c *FakeServices) UpdateStatus(service *api.Service) (*api.Service, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("services", "status", c.ns, service), &api.Service{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Service), err -} - -func (c *FakeServices) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("services", c.ns, name), &api.Service{}) - - return err -} - -func (c *FakeServices) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("services", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.ServiceList{}) - return err -} - -func (c *FakeServices) Get(name string) (result *api.Service, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("services", c.ns, name), &api.Service{}) - - if obj == nil { - return nil, err - } - return obj.(*api.Service), err -} - -func (c *FakeServices) List(opts api.ListOptions) (result *api.ServiceList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("services", c.ns, opts), &api.ServiceList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.ServiceList{} - for _, item := range obj.(*api.ServiceList).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 services. -func (c *FakeServices) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("services", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_service_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_service_expansion.go deleted file mode 100644 index 7d72d1dfe..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_service_expansion.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package fake - -import ( - "k8s.io/kubernetes/pkg/client/testing/core" - client "k8s.io/kubernetes/pkg/client/unversioned" -) - -func (c *FakeServices) ProxyGet(scheme, name, port, path string, params map[string]string) client.ResponseWrapper { - return c.Fake.InvokesProxy(core.NewProxyGetAction("services", c.ns, scheme, name, port, path, params)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_serviceaccount.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_serviceaccount.go deleted file mode 100644 index 61d7a04f5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/fake/fake_serviceaccount.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - core "k8s.io/kubernetes/pkg/client/testing/core" - labels "k8s.io/kubernetes/pkg/labels" - watch "k8s.io/kubernetes/pkg/watch" -) - -// FakeServiceAccounts implements ServiceAccountInterface -type FakeServiceAccounts struct { - Fake *FakeCore - ns string -} - -func (c *FakeServiceAccounts) Create(serviceAccount *api.ServiceAccount) (result *api.ServiceAccount, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("serviceaccounts", c.ns, serviceAccount), &api.ServiceAccount{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ServiceAccount), err -} - -func (c *FakeServiceAccounts) Update(serviceAccount *api.ServiceAccount) (result *api.ServiceAccount, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("serviceaccounts", c.ns, serviceAccount), &api.ServiceAccount{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ServiceAccount), err -} - -func (c *FakeServiceAccounts) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("serviceaccounts", c.ns, name), &api.ServiceAccount{}) - - return err -} - -func (c *FakeServiceAccounts) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("serviceaccounts", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &api.ServiceAccountList{}) - return err -} - -func (c *FakeServiceAccounts) Get(name string) (result *api.ServiceAccount, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("serviceaccounts", c.ns, name), &api.ServiceAccount{}) - - if obj == nil { - return nil, err - } - return obj.(*api.ServiceAccount), err -} - -func (c *FakeServiceAccounts) List(opts api.ListOptions) (result *api.ServiceAccountList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("serviceaccounts", c.ns, opts), &api.ServiceAccountList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.ServiceAccountList{} - for _, item := range obj.(*api.ServiceAccountList).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 serviceAccounts. -func (c *FakeServiceAccounts) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("serviceaccounts", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/pod_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/pod_expansion.go index 0a46431d5..8ebd29d30 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/pod_expansion.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/pod_expansion.go @@ -18,13 +18,13 @@ package unversioned import ( "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" ) // The PodExpansion interface allows manually adding extra methods to the PodInterface. type PodExpansion interface { Bind(binding *api.Binding) error - GetLogs(name string, opts *api.PodLogOptions) *unversioned.Request + GetLogs(name string, opts *api.PodLogOptions) *restclient.Request } // Bind applies the provided binding to the named pod in the current namespace (binding.Namespace is ignored). @@ -33,6 +33,6 @@ func (c *pods) Bind(binding *api.Binding) error { } // Get constructs a request for getting the logs for a pod -func (c *pods) GetLogs(name string, opts *api.PodLogOptions) *unversioned.Request { +func (c *pods) GetLogs(name string, opts *api.PodLogOptions) *restclient.Request { return c.client.Get().Namespace(c.ns).Name(name).Resource("pods").SubResource("log").VersionedParams(opts, api.ParameterCodec) } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/service_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/service_expansion.go index b9fb6af86..89266e6cd 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/service_expansion.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned/service_expansion.go @@ -17,17 +17,17 @@ limitations under the License. package unversioned import ( - "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/util/net" ) // The ServiceExpansion interface allows manually adding extra methods to the ServiceInterface. type ServiceExpansion interface { - ProxyGet(scheme, name, port, path string, params map[string]string) unversioned.ResponseWrapper + ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper } // ProxyGet returns a response of the service by calling it through the proxy. -func (c *services) ProxyGet(scheme, name, port, path string, params map[string]string) unversioned.ResponseWrapper { +func (c *services) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper { request := c.client.Get(). Prefix("proxy"). Namespace(c.ns). diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/extensions_client.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/extensions_client.go index 6780a5c03..220dd69b5 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/extensions_client.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/extensions_client.go @@ -19,7 +19,7 @@ package unversioned import ( api "k8s.io/kubernetes/pkg/api" registered "k8s.io/kubernetes/pkg/apimachinery/registered" - unversioned "k8s.io/kubernetes/pkg/client/unversioned" + restclient "k8s.io/kubernetes/pkg/client/restclient" ) type ExtensionsInterface interface { @@ -35,7 +35,7 @@ type ExtensionsInterface interface { // ExtensionsClient is used to interact with features provided by the Extensions group. type ExtensionsClient struct { - *unversioned.RESTClient + *restclient.RESTClient } func (c *ExtensionsClient) DaemonSets(namespace string) DaemonSetInterface { @@ -71,12 +71,12 @@ func (c *ExtensionsClient) ThirdPartyResources(namespace string) ThirdPartyResou } // NewForConfig creates a new ExtensionsClient for the given config. -func NewForConfig(c *unversioned.Config) (*ExtensionsClient, error) { +func NewForConfig(c *restclient.Config) (*ExtensionsClient, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } - client, err := unversioned.RESTClientFor(&config) + client, err := restclient.RESTClientFor(&config) if err != nil { return nil, err } @@ -85,7 +85,7 @@ func NewForConfig(c *unversioned.Config) (*ExtensionsClient, error) { // NewForConfigOrDie creates a new ExtensionsClient for the given config and // panics if there is an error in the config. -func NewForConfigOrDie(c *unversioned.Config) *ExtensionsClient { +func NewForConfigOrDie(c *restclient.Config) *ExtensionsClient { client, err := NewForConfig(c) if err != nil { panic(err) @@ -94,11 +94,11 @@ func NewForConfigOrDie(c *unversioned.Config) *ExtensionsClient { } // New creates a new ExtensionsClient for the given RESTClient. -func New(c *unversioned.RESTClient) *ExtensionsClient { +func New(c *restclient.RESTClient) *ExtensionsClient { return &ExtensionsClient{c} } -func setConfigDefaults(config *unversioned.Config) error { +func setConfigDefaults(config *restclient.Config) error { // if extensions group is not registered, return an error g, err := registered.Group("extensions") if err != nil { @@ -106,7 +106,7 @@ func setConfigDefaults(config *unversioned.Config) error { } config.APIPath = "/apis" if config.UserAgent == "" { - config.UserAgent = unversioned.DefaultKubernetesUserAgent() + config.UserAgent = restclient.DefaultKubernetesUserAgent() } // TODO: Unconditionally set the config.Version, until we fix the config. //if config.Version == "" { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/doc.go deleted file mode 100644 index dd6d4da71..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -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. -*/ - -// Package fake has the automatically generated clients. -package fake diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_daemonset.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_daemonset.go deleted file mode 100644 index 7de9f927f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_daemonset.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - 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" -) - -// FakeDaemonSets implements DaemonSetInterface -type FakeDaemonSets struct { - Fake *FakeExtensions - ns string -} - -func (c *FakeDaemonSets) Create(daemonSet *extensions.DaemonSet) (result *extensions.DaemonSet, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("daemonsets", c.ns, daemonSet), &extensions.DaemonSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) Update(daemonSet *extensions.DaemonSet) (result *extensions.DaemonSet, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("daemonsets", c.ns, daemonSet), &extensions.DaemonSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) UpdateStatus(daemonSet *extensions.DaemonSet) (*extensions.DaemonSet, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("daemonsets", "status", c.ns, daemonSet), &extensions.DaemonSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("daemonsets", c.ns, name), &extensions.DaemonSet{}) - - return err -} - -func (c *FakeDaemonSets) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("daemonsets", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &extensions.DaemonSetList{}) - return err -} - -func (c *FakeDaemonSets) Get(name string) (result *extensions.DaemonSet, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("daemonsets", c.ns, name), &extensions.DaemonSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) List(opts api.ListOptions) (result *extensions.DaemonSetList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("daemonsets", c.ns, opts), &extensions.DaemonSetList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.DaemonSetList{} - for _, item := range obj.(*extensions.DaemonSetList).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 daemonSets. -func (c *FakeDaemonSets) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("daemonsets", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_deployment.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_deployment.go deleted file mode 100644 index 748968a9d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_deployment.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - 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" -) - -// FakeDeployments implements DeploymentInterface -type FakeDeployments struct { - Fake *FakeExtensions - ns string -} - -func (c *FakeDeployments) Create(deployment *extensions.Deployment) (result *extensions.Deployment, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("deployments", c.ns, deployment), &extensions.Deployment{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) Update(deployment *extensions.Deployment) (result *extensions.Deployment, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("deployments", c.ns, deployment), &extensions.Deployment{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) UpdateStatus(deployment *extensions.Deployment) (*extensions.Deployment, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("deployments", "status", c.ns, deployment), &extensions.Deployment{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("deployments", c.ns, name), &extensions.Deployment{}) - - return err -} - -func (c *FakeDeployments) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("deployments", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &extensions.DeploymentList{}) - return err -} - -func (c *FakeDeployments) Get(name string) (result *extensions.Deployment, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("deployments", c.ns, name), &extensions.Deployment{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) List(opts api.ListOptions) (result *extensions.DeploymentList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("deployments", c.ns, opts), &extensions.DeploymentList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.DeploymentList{} - for _, item := range obj.(*extensions.DeploymentList).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 deployments. -func (c *FakeDeployments) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("deployments", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_deployment_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_deployment_expansion.go deleted file mode 100644 index 3edc64c01..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_deployment_expansion.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package fake - -import ( - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/testing/core" -) - -func (c *FakeDeployments) Rollback(deploymentRollback *extensions.DeploymentRollback) error { - action := core.CreateActionImpl{} - action.Verb = "create" - action.Resource = "deployments" - action.Subresource = "rollback" - action.Object = deploymentRollback - - _, err := c.Fake.Invokes(action, deploymentRollback) - return err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_extensions_client.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_extensions_client.go deleted file mode 100644 index 2f7fb0423..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_extensions_client.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - core "k8s.io/kubernetes/pkg/client/testing/core" - unversioned "k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned" -) - -type FakeExtensions struct { - *core.Fake -} - -func (c *FakeExtensions) DaemonSets(namespace string) unversioned.DaemonSetInterface { - return &FakeDaemonSets{c, namespace} -} - -func (c *FakeExtensions) Deployments(namespace string) unversioned.DeploymentInterface { - return &FakeDeployments{c, namespace} -} - -func (c *FakeExtensions) HorizontalPodAutoscalers(namespace string) unversioned.HorizontalPodAutoscalerInterface { - return &FakeHorizontalPodAutoscalers{c, namespace} -} - -func (c *FakeExtensions) Ingresses(namespace string) unversioned.IngressInterface { - return &FakeIngresses{c, namespace} -} - -func (c *FakeExtensions) Jobs(namespace string) unversioned.JobInterface { - return &FakeJobs{c, namespace} -} - -func (c *FakeExtensions) ReplicaSets(namespace string) unversioned.ReplicaSetInterface { - return &FakeReplicaSets{c, namespace} -} - -func (c *FakeExtensions) Scales(namespace string) unversioned.ScaleInterface { - return &FakeScales{c, namespace} -} - -func (c *FakeExtensions) ThirdPartyResources(namespace string) unversioned.ThirdPartyResourceInterface { - return &FakeThirdPartyResources{c, namespace} -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_horizontalpodautoscaler.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_horizontalpodautoscaler.go deleted file mode 100644 index 71b5cf322..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_horizontalpodautoscaler.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - 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" -) - -// FakeHorizontalPodAutoscalers implements HorizontalPodAutoscalerInterface -type FakeHorizontalPodAutoscalers struct { - Fake *FakeExtensions - ns string -} - -func (c *FakeHorizontalPodAutoscalers) Create(horizontalPodAutoscaler *extensions.HorizontalPodAutoscaler) (result *extensions.HorizontalPodAutoscaler, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("horizontalpodautoscalers", c.ns, horizontalPodAutoscaler), &extensions.HorizontalPodAutoscaler{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) Update(horizontalPodAutoscaler *extensions.HorizontalPodAutoscaler) (result *extensions.HorizontalPodAutoscaler, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("horizontalpodautoscalers", c.ns, horizontalPodAutoscaler), &extensions.HorizontalPodAutoscaler{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) UpdateStatus(horizontalPodAutoscaler *extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("horizontalpodautoscalers", "status", c.ns, horizontalPodAutoscaler), &extensions.HorizontalPodAutoscaler{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("horizontalpodautoscalers", c.ns, name), &extensions.HorizontalPodAutoscaler{}) - - return err -} - -func (c *FakeHorizontalPodAutoscalers) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("horizontalpodautoscalers", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &extensions.HorizontalPodAutoscalerList{}) - return err -} - -func (c *FakeHorizontalPodAutoscalers) Get(name string) (result *extensions.HorizontalPodAutoscaler, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("horizontalpodautoscalers", c.ns, name), &extensions.HorizontalPodAutoscaler{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) List(opts api.ListOptions) (result *extensions.HorizontalPodAutoscalerList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("horizontalpodautoscalers", c.ns, opts), &extensions.HorizontalPodAutoscalerList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.HorizontalPodAutoscalerList{} - for _, item := range obj.(*extensions.HorizontalPodAutoscalerList).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 horizontalPodAutoscalers. -func (c *FakeHorizontalPodAutoscalers) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("horizontalpodautoscalers", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_ingress.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_ingress.go deleted file mode 100644 index a331644e4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_ingress.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - 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" -) - -// FakeIngresses implements IngressInterface -type FakeIngresses struct { - Fake *FakeExtensions - ns string -} - -func (c *FakeIngresses) Create(ingress *extensions.Ingress) (result *extensions.Ingress, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("ingresses", c.ns, ingress), &extensions.Ingress{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Ingress), err -} - -func (c *FakeIngresses) Update(ingress *extensions.Ingress) (result *extensions.Ingress, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("ingresses", c.ns, ingress), &extensions.Ingress{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Ingress), err -} - -func (c *FakeIngresses) UpdateStatus(ingress *extensions.Ingress) (*extensions.Ingress, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("ingresses", "status", c.ns, ingress), &extensions.Ingress{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Ingress), err -} - -func (c *FakeIngresses) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("ingresses", c.ns, name), &extensions.Ingress{}) - - return err -} - -func (c *FakeIngresses) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("ingresses", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &extensions.IngressList{}) - return err -} - -func (c *FakeIngresses) Get(name string) (result *extensions.Ingress, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("ingresses", c.ns, name), &extensions.Ingress{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Ingress), err -} - -func (c *FakeIngresses) List(opts api.ListOptions) (result *extensions.IngressList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("ingresses", c.ns, opts), &extensions.IngressList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.IngressList{} - for _, item := range obj.(*extensions.IngressList).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 ingresses. -func (c *FakeIngresses) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("ingresses", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_job.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_job.go deleted file mode 100644 index c1875c006..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_job.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - 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" -) - -// FakeJobs implements JobInterface -type FakeJobs struct { - Fake *FakeExtensions - ns string -} - -func (c *FakeJobs) Create(job *extensions.Job) (result *extensions.Job, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("jobs", c.ns, job), &extensions.Job{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Job), err -} - -func (c *FakeJobs) Update(job *extensions.Job) (result *extensions.Job, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("jobs", c.ns, job), &extensions.Job{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Job), err -} - -func (c *FakeJobs) UpdateStatus(job *extensions.Job) (*extensions.Job, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("jobs", "status", c.ns, job), &extensions.Job{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Job), err -} - -func (c *FakeJobs) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("jobs", c.ns, name), &extensions.Job{}) - - return err -} - -func (c *FakeJobs) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("jobs", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &extensions.JobList{}) - return err -} - -func (c *FakeJobs) Get(name string) (result *extensions.Job, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("jobs", c.ns, name), &extensions.Job{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.Job), err -} - -func (c *FakeJobs) List(opts api.ListOptions) (result *extensions.JobList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("jobs", c.ns, opts), &extensions.JobList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.JobList{} - for _, item := range obj.(*extensions.JobList).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 jobs. -func (c *FakeJobs) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("jobs", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_replicaset.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_replicaset.go deleted file mode 100644 index d861326b7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_replicaset.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - 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" -) - -// FakeReplicaSets implements ReplicaSetInterface -type FakeReplicaSets struct { - Fake *FakeExtensions - ns string -} - -func (c *FakeReplicaSets) Create(replicaSet *extensions.ReplicaSet) (result *extensions.ReplicaSet, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("replicasets", c.ns, replicaSet), &extensions.ReplicaSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.ReplicaSet), err -} - -func (c *FakeReplicaSets) Update(replicaSet *extensions.ReplicaSet) (result *extensions.ReplicaSet, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("replicasets", c.ns, replicaSet), &extensions.ReplicaSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.ReplicaSet), err -} - -func (c *FakeReplicaSets) UpdateStatus(replicaSet *extensions.ReplicaSet) (*extensions.ReplicaSet, error) { - obj, err := c.Fake. - Invokes(core.NewUpdateSubresourceAction("replicasets", "status", c.ns, replicaSet), &extensions.ReplicaSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.ReplicaSet), err -} - -func (c *FakeReplicaSets) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("replicasets", c.ns, name), &extensions.ReplicaSet{}) - - return err -} - -func (c *FakeReplicaSets) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("replicasets", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &extensions.ReplicaSetList{}) - return err -} - -func (c *FakeReplicaSets) Get(name string) (result *extensions.ReplicaSet, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("replicasets", c.ns, name), &extensions.ReplicaSet{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.ReplicaSet), err -} - -func (c *FakeReplicaSets) List(opts api.ListOptions) (result *extensions.ReplicaSetList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("replicasets", c.ns, opts), &extensions.ReplicaSetList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.ReplicaSetList{} - for _, item := range obj.(*extensions.ReplicaSetList).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 replicaSets. -func (c *FakeReplicaSets) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("replicasets", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_scale_expansion.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_scale_expansion.go deleted file mode 100644 index 8c52e409b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_scale_expansion.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package fake - -import ( - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/testing/core" -) - -func (c *FakeScales) Get(kind string, name string) (result *extensions.Scale, err error) { - action := core.GetActionImpl{} - action.Verb = "get" - action.Namespace = c.ns - action.Resource = kind - action.Subresource = "scale" - action.Name = name - obj, err := c.Fake.Invokes(action, &extensions.Scale{}) - result = obj.(*extensions.Scale) - return -} - -func (c *FakeScales) Update(kind string, scale *extensions.Scale) (result *extensions.Scale, err error) { - action := core.UpdateActionImpl{} - action.Verb = "update" - action.Namespace = c.ns - action.Resource = kind - action.Subresource = "scale" - action.Object = scale - obj, err := c.Fake.Invokes(action, scale) - result = obj.(*extensions.Scale) - return -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_thirdpartyresource.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_thirdpartyresource.go deleted file mode 100644 index 9a005d570..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_thirdpartyresource.go +++ /dev/null @@ -1,103 +0,0 @@ -/* -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. -*/ - -package fake - -import ( - api "k8s.io/kubernetes/pkg/api" - 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" -) - -// FakeThirdPartyResources implements ThirdPartyResourceInterface -type FakeThirdPartyResources struct { - Fake *FakeExtensions - ns string -} - -func (c *FakeThirdPartyResources) Create(thirdPartyResource *extensions.ThirdPartyResource) (result *extensions.ThirdPartyResource, err error) { - obj, err := c.Fake. - Invokes(core.NewCreateAction("thirdpartyresources", c.ns, thirdPartyResource), &extensions.ThirdPartyResource{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResource), err -} - -func (c *FakeThirdPartyResources) Update(thirdPartyResource *extensions.ThirdPartyResource) (result *extensions.ThirdPartyResource, err error) { - obj, err := c.Fake. - Invokes(core.NewUpdateAction("thirdpartyresources", c.ns, thirdPartyResource), &extensions.ThirdPartyResource{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResource), err -} - -func (c *FakeThirdPartyResources) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake. - Invokes(core.NewDeleteAction("thirdpartyresources", c.ns, name), &extensions.ThirdPartyResource{}) - - return err -} - -func (c *FakeThirdPartyResources) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := core.NewDeleteCollectionAction("thirdpartyresources", c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &extensions.ThirdPartyResourceList{}) - return err -} - -func (c *FakeThirdPartyResources) Get(name string) (result *extensions.ThirdPartyResource, err error) { - obj, err := c.Fake. - Invokes(core.NewGetAction("thirdpartyresources", c.ns, name), &extensions.ThirdPartyResource{}) - - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResource), err -} - -func (c *FakeThirdPartyResources) List(opts api.ListOptions) (result *extensions.ThirdPartyResourceList, err error) { - obj, err := c.Fake. - Invokes(core.NewListAction("thirdpartyresources", c.ns, opts), &extensions.ThirdPartyResourceList{}) - - if obj == nil { - return nil, err - } - - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.ThirdPartyResourceList{} - for _, item := range obj.(*extensions.ThirdPartyResourceList).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 thirdPartyResources. -func (c *FakeThirdPartyResources) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(core.NewWatchAction("thirdpartyresources", c.ns, opts)) - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go index 16acc00ce..64b3ef6be 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go @@ -68,7 +68,7 @@ import ( "io/ioutil" "os" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" ) // Info holds Kubernetes API authorization config. It is intended @@ -104,8 +104,8 @@ func LoadFromFile(path string) (*Info, error) { // MergeWithConfig returns a copy of a client.Config with values from the Info. // The fields of client.Config with a corresponding field in the Info are set // with the value from the Info. -func (info Info) MergeWithConfig(c client.Config) (client.Config, error) { - var config client.Config = c +func (info Info) MergeWithConfig(c restclient.Config) (restclient.Config, error) { + var config restclient.Config = c config.Username = info.User config.Password = info.Password config.CAFile = info.CAFile diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth_test.go deleted file mode 100644 index a99c5d94a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package auth_test - -import ( - "io/ioutil" - "os" - "reflect" - "testing" - - clientauth "k8s.io/kubernetes/pkg/client/unversioned/auth" -) - -func TestLoadFromFile(t *testing.T) { - loadAuthInfoTests := []struct { - authData string - authInfo *clientauth.Info - expectErr bool - }{ - { - `{"user": "user", "password": "pass"}`, - &clientauth.Info{User: "user", Password: "pass"}, - false, - }, - { - "", nil, true, - }, - } - for _, loadAuthInfoTest := range loadAuthInfoTests { - tt := loadAuthInfoTest - aifile, err := ioutil.TempFile("", "testAuthInfo") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if tt.authData != "missing" { - defer os.Remove(aifile.Name()) - defer aifile.Close() - _, err = aifile.WriteString(tt.authData) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - } else { - aifile.Close() - os.Remove(aifile.Name()) - } - authInfo, err := clientauth.LoadFromFile(aifile.Name()) - gotErr := err != nil - if gotErr != tt.expectErr { - t.Errorf("expected errorness: %v, actual errorness: %v", tt.expectErr, gotErr) - } - if !reflect.DeepEqual(authInfo, tt.authInfo) { - t.Errorf("Expected %v, got %v", tt.authInfo, authInfo) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go index 9445c0c6c..c3ec19810 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go @@ -20,6 +20,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/autoscaling" + "k8s.io/kubernetes/pkg/client/restclient" ) type AutoscalingInterface interface { @@ -28,26 +29,26 @@ type AutoscalingInterface interface { // AutoscalingClient is used to interact with Kubernetes autoscaling features. type AutoscalingClient struct { - *RESTClient + *restclient.RESTClient } func (c *AutoscalingClient) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface { return newHorizontalPodAutoscalersV1(c, namespace) } -func NewAutoscaling(c *Config) (*AutoscalingClient, error) { +func NewAutoscaling(c *restclient.Config) (*AutoscalingClient, error) { config := *c if err := setAutoscalingDefaults(&config); err != nil { return nil, err } - client, err := RESTClientFor(&config) + client, err := restclient.RESTClientFor(&config) if err != nil { return nil, err } return &AutoscalingClient{client}, nil } -func NewAutoscalingOrDie(c *Config) *AutoscalingClient { +func NewAutoscalingOrDie(c *restclient.Config) *AutoscalingClient { client, err := NewAutoscaling(c) if err != nil { panic(err) @@ -55,7 +56,7 @@ func NewAutoscalingOrDie(c *Config) *AutoscalingClient { return client } -func setAutoscalingDefaults(config *Config) error { +func setAutoscalingDefaults(config *restclient.Config) error { // if autoscaling group is not registered, return an error g, err := registered.Group(autoscaling.GroupName) if err != nil { @@ -63,7 +64,7 @@ func setAutoscalingDefaults(config *Config) error { } config.APIPath = defaultAPIPath if config.UserAgent == "" { - config.UserAgent = DefaultKubernetesUserAgent() + config.UserAgent = restclient.DefaultKubernetesUserAgent() } // TODO: Unconditionally set the config.Version, until we fix the config. //if config.Version == "" { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/batch.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/batch.go new file mode 100644 index 000000000..a432e4c78 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/batch.go @@ -0,0 +1,83 @@ +/* +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. +*/ + +package unversioned + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apimachinery/registered" + "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/client/restclient" +) + +type BatchInterface interface { + JobsNamespacer +} + +// BatchClient is used to interact with Kubernetes batch features. +type BatchClient struct { + *restclient.RESTClient +} + +func (c *BatchClient) Jobs(namespace string) JobInterface { + return newJobsV1(c, namespace) +} + +func NewBatch(c *restclient.Config) (*BatchClient, error) { + config := *c + if err := setBatchDefaults(&config); err != nil { + return nil, err + } + client, err := restclient.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &BatchClient{client}, nil +} + +func NewBatchOrDie(c *restclient.Config) *BatchClient { + client, err := NewBatch(c) + if err != nil { + panic(err) + } + return client +} + +func setBatchDefaults(config *restclient.Config) error { + // if batch group is not registered, return an error + g, err := registered.Group(batch.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.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) + if config.QPS == 0 { + config.QPS = 5 + } + if config.Burst == 0 { + config.Burst = 10 + } + return nil +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/client.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/client.go index 8a891c44a..b897bc230 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/client.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/client.go @@ -20,6 +20,9 @@ import ( "net" "net/url" "strings" + + "k8s.io/kubernetes/pkg/client/restclient" + "k8s.io/kubernetes/pkg/client/typed/discovery" ) // Interface holds the methods for clients of Kubernetes, @@ -42,8 +45,9 @@ type Interface interface { ComponentStatusesInterface ConfigMapsNamespacer Autoscaling() AutoscalingInterface + Batch() BatchInterface Extensions() ExtensionsInterface - Discovery() DiscoveryInterface + Discovery() discovery.DiscoveryInterface } func (c *Client) ReplicationControllers(namespace string) ReplicationControllerInterface { @@ -111,19 +115,11 @@ func (c *Client) ConfigMaps(namespace string) ConfigMapsInterface { // Client is the implementation of a Kubernetes client. type Client struct { - *RESTClient + *restclient.RESTClient *AutoscalingClient + *BatchClient *ExtensionsClient - *DiscoveryClient -} - -func stringDoesntExistIn(str string, slice []string) bool { - for _, s := range slice { - if s == str { - return false - } - } - return true + *discovery.DiscoveryClient } // IsTimeout tests if this is a timeout error in the underlying transport. @@ -152,10 +148,14 @@ func (c *Client) Autoscaling() AutoscalingInterface { return c.AutoscalingClient } +func (c *Client) Batch() BatchInterface { + return c.BatchClient +} + func (c *Client) Extensions() ExtensionsInterface { return c.ExtensionsClient } -func (c *Client) Discovery() DiscoveryInterface { +func (c *Client) Discovery() discovery.DiscoveryInterface { return c.DiscoveryClient } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/client_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/client_test.go deleted file mode 100644 index 487591c5d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/client_test.go +++ /dev/null @@ -1,308 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "reflect" - "testing" - - "github.com/emicklei/go-restful/swagger" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/version" -) - -func TestGetServerVersion(t *testing.T) { - expect := version.Info{ - Major: "foo", - Minor: "bar", - GitCommit: "baz", - } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - output, err := json.Marshal(expect) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - client := NewOrDie(&Config{Host: server.URL}) - - got, err := client.Discovery().ServerVersion() - if err != nil { - t.Fatalf("unexpected encoding error: %v", err) - } - if e, a := expect, *got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestGetServerGroupsWithV1Server(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var obj interface{} - switch req.URL.Path { - case "/api": - obj = &unversioned.APIVersions{ - Versions: []string{ - "v1", - }, - } - default: - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(obj) - if err != nil { - t.Fatalf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - client := NewOrDie(&Config{Host: server.URL}) - // ServerGroups should not return an error even if server returns error at /api and /apis - apiGroupList, err := client.Discovery().ServerGroups() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - groupVersions := ExtractGroupVersions(apiGroupList) - if !reflect.DeepEqual(groupVersions, []string{"v1"}) { - t.Errorf("expected: %q, got: %q", []string{"v1"}, groupVersions) - } -} - -func TestGetServerResourcesWithV1Server(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var obj interface{} - switch req.URL.Path { - case "/api": - obj = &unversioned.APIVersions{ - Versions: []string{ - "v1", - }, - } - default: - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(obj) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - client := NewOrDie(&Config{Host: server.URL}) - // ServerResources should not return an error even if server returns error at /api/v1. - resourceMap, err := client.Discovery().ServerResources() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if _, found := resourceMap["v1"]; !found { - t.Errorf("missing v1 in resource map") - } - -} - -func TestGetServerResources(t *testing.T) { - stable := unversioned.APIResourceList{ - GroupVersion: "v1", - APIResources: []unversioned.APIResource{ - {"pods", true, "Pod"}, - {"services", true, "Service"}, - {"namespaces", false, "Namespace"}, - }, - } - beta := unversioned.APIResourceList{ - GroupVersion: "extensions/v1", - APIResources: []unversioned.APIResource{ - {"deployments", true, "Deployment"}, - {"ingresses", true, "Ingress"}, - {"jobs", true, "Job"}, - }, - } - tests := []struct { - resourcesList *unversioned.APIResourceList - path string - request string - expectErr bool - }{ - { - resourcesList: &stable, - path: "/api/v1", - request: "v1", - expectErr: false, - }, - { - resourcesList: &beta, - path: "/apis/extensions/v1beta1", - request: "extensions/v1beta1", - expectErr: false, - }, - { - resourcesList: &stable, - path: "/api/v1", - request: "foobar", - expectErr: true, - }, - } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/api/v1": - list = &stable - case "/apis/extensions/v1beta1": - list = &beta - case "/api": - list = &unversioned.APIVersions{ - Versions: []string{ - "v1", - }, - } - case "/apis": - list = &unversioned.APIGroupList{ - Groups: []unversioned.APIGroup{ - { - Versions: []unversioned.GroupVersionForDiscovery{ - {GroupVersion: "extensions/v1beta1"}, - }, - }, - }, - } - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - client := NewOrDie(&Config{Host: server.URL}) - for _, test := range tests { - got, err := client.Discovery().ServerResourcesForGroupVersion(test.request) - if test.expectErr { - if err == nil { - t.Error("unexpected non-error") - } - continue - } - if err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - if !reflect.DeepEqual(got, test.resourcesList) { - t.Errorf("expected:\n%v\ngot:\n%v\n", test.resourcesList, got) - } - } - - resourceMap, err := client.Discovery().ServerResources() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - for _, api := range []string{"v1", "extensions/v1beta1"} { - if _, found := resourceMap[api]; !found { - t.Errorf("missing expected api: %s", api) - } - } -} - -func swaggerSchemaFakeServer() (*httptest.Server, error) { - request := 1 - var sErr error - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var resp interface{} - if request == 1 { - resp = unversioned.APIVersions{Versions: []string{"v1", "v2", "v3"}} - request++ - } else { - resp = swagger.ApiDeclaration{} - } - output, err := json.Marshal(resp) - if err != nil { - sErr = err - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - return server, sErr -} - -func TestGetSwaggerSchema(t *testing.T) { - expect := swagger.ApiDeclaration{} - - server, err := swaggerSchemaFakeServer() - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - } - // TODO: Uncomment when fix #19254 - // defer server.Close() - - client := NewOrDie(&Config{Host: server.URL}) - got, err := client.Discovery().SwaggerSchema(v1.SchemeGroupVersion) - if err != nil { - t.Fatalf("unexpected encoding error: %v", err) - } - if e, a := expect, *got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestGetSwaggerSchemaFail(t *testing.T) { - expErr := "API version: api.group/v4 is not supported by the server. Use one of: [v1 v2 v3]" - - server, err := swaggerSchemaFakeServer() - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - } - // TODO: Uncomment when fix #19254 - // defer server.Close() - - client := NewOrDie(&Config{Host: server.URL}) - got, err := client.Discovery().SwaggerSchema(unversioned.GroupVersion{Group: "api.group", Version: "v4"}) - if got != nil { - t.Fatalf("unexpected response: %v", got) - } - if err.Error() != expErr { - t.Errorf("expected an error, got %v", err) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/helpers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/helpers_test.go deleted file mode 100644 index ca970f3b4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/helpers_test.go +++ /dev/null @@ -1,301 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package api - -import ( - "fmt" - "io/ioutil" - "os" - "reflect" - "testing" - - "github.com/ghodss/yaml" -) - -func newMergedConfig(certFile, certContent, keyFile, keyContent, caFile, caContent string, t *testing.T) Config { - if err := ioutil.WriteFile(certFile, []byte(certContent), 0644); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := ioutil.WriteFile(keyFile, []byte(keyContent), 0600); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := ioutil.WriteFile(caFile, []byte(caContent), 0644); err != nil { - t.Errorf("unexpected error: %v", err) - } - - return Config{ - AuthInfos: map[string]*AuthInfo{ - "red-user": {Token: "red-token", ClientCertificateData: []byte(certContent), ClientKeyData: []byte(keyContent)}, - "blue-user": {Token: "blue-token", ClientCertificate: certFile, ClientKey: keyFile}}, - Clusters: map[string]*Cluster{ - "cow-cluster": {Server: "http://cow.org:8080", CertificateAuthorityData: []byte(caContent)}, - "chicken-cluster": {Server: "http://chicken.org:8080", CertificateAuthority: caFile}}, - Contexts: map[string]*Context{ - "federal-context": {AuthInfo: "red-user", Cluster: "cow-cluster"}, - "shaker-context": {AuthInfo: "blue-user", Cluster: "chicken-cluster"}}, - CurrentContext: "federal-context", - } -} - -func TestMinifySuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - - if err := MinifyConfig(&mutatingConfig); err != nil { - t.Errorf("unexpected error: %v", err) - } - - if len(mutatingConfig.Contexts) > 1 { - t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts) - } - if _, exists := mutatingConfig.Contexts["federal-context"]; !exists { - t.Errorf("missing context") - } - - if len(mutatingConfig.Clusters) > 1 { - t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters) - } - if _, exists := mutatingConfig.Clusters["cow-cluster"]; !exists { - t.Errorf("missing cluster") - } - - if len(mutatingConfig.AuthInfos) > 1 { - t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos) - } - if _, exists := mutatingConfig.AuthInfos["red-user"]; !exists { - t.Errorf("missing user") - } -} - -func TestMinifyMissingContext(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - mutatingConfig.CurrentContext = "missing" - - errMsg := "cannot locate context missing" - - if err := MinifyConfig(&mutatingConfig); err == nil || err.Error() != errMsg { - t.Errorf("expected %v, got %v", errMsg, err) - } -} - -func TestMinifyMissingCluster(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - delete(mutatingConfig.Clusters, mutatingConfig.Contexts[mutatingConfig.CurrentContext].Cluster) - - errMsg := "cannot locate cluster cow-cluster" - - if err := MinifyConfig(&mutatingConfig); err == nil || err.Error() != errMsg { - t.Errorf("expected %v, got %v", errMsg, err) - } -} - -func TestMinifyMissingAuthInfo(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - delete(mutatingConfig.AuthInfos, mutatingConfig.Contexts[mutatingConfig.CurrentContext].AuthInfo) - - errMsg := "cannot locate user red-user" - - if err := MinifyConfig(&mutatingConfig); err == nil || err.Error() != errMsg { - t.Errorf("expected %v, got %v", errMsg, err) - } -} - -func TestFlattenSuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - certData := "cert" - keyData := "key" - caData := "ca" - - unchangingCluster := "cow-cluster" - unchangingAuthInfo := "red-user" - changingCluster := "chicken-cluster" - changingAuthInfo := "blue-user" - - startingConfig := newMergedConfig(certFile.Name(), certData, keyFile.Name(), keyData, caFile.Name(), caData, t) - mutatingConfig := startingConfig - - if err := FlattenConfig(&mutatingConfig); err != nil { - t.Errorf("unexpected error: %v", err) - } - - if len(mutatingConfig.Contexts) != 2 { - t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts) - } - if !reflect.DeepEqual(startingConfig.Contexts, mutatingConfig.Contexts) { - t.Errorf("expected %v, got %v", startingConfig.Contexts, mutatingConfig.Contexts) - } - - if len(mutatingConfig.Clusters) != 2 { - t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters) - } - if !reflect.DeepEqual(startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) { - t.Errorf("expected %v, got %v", startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) - } - if len(mutatingConfig.Clusters[changingCluster].CertificateAuthority) != 0 { - t.Errorf("unexpected caFile") - } - if string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData) != caData { - t.Errorf("expected %v, got %v", caData, string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData)) - } - - if len(mutatingConfig.AuthInfos) != 2 { - t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos) - } - if !reflect.DeepEqual(startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) { - t.Errorf("expected %v, got %v", startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) - } - if len(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificate) != 0 { - t.Errorf("unexpected caFile") - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData) != certData { - t.Errorf("expected %v, got %v", certData, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData)) - } - if len(mutatingConfig.AuthInfos[changingAuthInfo].ClientKey) != 0 { - t.Errorf("unexpected caFile") - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData) != keyData { - t.Errorf("expected %v, got %v", keyData, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData)) - } - -} - -func ExampleMinifyAndShorten() { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - certData := "cert" - keyData := "key" - caData := "ca" - - config := newMergedConfig(certFile.Name(), certData, keyFile.Name(), keyData, caFile.Name(), caData, nil) - - MinifyConfig(&config) - ShortenConfig(&config) - - output, _ := yaml.Marshal(config) - fmt.Printf("%s", string(output)) - // Output: - // clusters: - // cow-cluster: - // LocationOfOrigin: "" - // certificate-authority-data: REDACTED - // server: http://cow.org:8080 - // contexts: - // federal-context: - // LocationOfOrigin: "" - // cluster: cow-cluster - // user: red-user - // current-context: federal-context - // preferences: {} - // users: - // red-user: - // LocationOfOrigin: "" - // client-certificate-data: REDACTED - // client-key-data: REDACTED - // token: red-token -} - -func TestShortenSuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - certData := "cert" - keyData := "key" - caData := "ca" - - unchangingCluster := "chicken-cluster" - unchangingAuthInfo := "blue-user" - changingCluster := "cow-cluster" - changingAuthInfo := "red-user" - - startingConfig := newMergedConfig(certFile.Name(), certData, keyFile.Name(), keyData, caFile.Name(), caData, t) - mutatingConfig := startingConfig - - ShortenConfig(&mutatingConfig) - - if len(mutatingConfig.Contexts) != 2 { - t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts) - } - if !reflect.DeepEqual(startingConfig.Contexts, mutatingConfig.Contexts) { - t.Errorf("expected %v, got %v", startingConfig.Contexts, mutatingConfig.Contexts) - } - - redacted := string(redactedBytes) - if len(mutatingConfig.Clusters) != 2 { - t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters) - } - if !reflect.DeepEqual(startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) { - t.Errorf("expected %v, got %v", startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) - } - if string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData) != redacted { - t.Errorf("expected %v, got %v", redacted, string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData)) - } - - if len(mutatingConfig.AuthInfos) != 2 { - t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos) - } - if !reflect.DeepEqual(startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) { - t.Errorf("expected %v, got %v", startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData) != redacted { - t.Errorf("expected %v, got %v", redacted, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData)) - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData) != redacted { - t.Errorf("expected %v, got %v", redacted, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData)) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go index 4a1dc364f..7e2bfcfa8 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go @@ -29,7 +29,11 @@ type Config struct { // Legacy field from pkg/api/types.go TypeMeta. // TODO(jlowdermilk): remove this after eliminating downstream dependencies. Kind string `json:"kind,omitempty"` - // Version of the schema for this config object. + // DEPRECATED: APIVersion is the preferred api version for communicating with the kubernetes cluster (v1, v2, etc). + // Because a cluster can run multiple API groups and potentially multiple versions of each, it no longer makes sense to specify + // a single value for the cluster version. + // This field isnt really needed anyway, so we are deprecating it without replacement. + // It will be ignored if it is present. APIVersion string `json:"apiVersion,omitempty"` // Preferences holds general information to be use for cli interactions Preferences Preferences `json:"preferences"` diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types_test.go deleted file mode 100644 index 8059fe21f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types_test.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package api - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func ExampleEmptyConfig() { - defaultConfig := NewConfig() - - output, err := yaml.Marshal(defaultConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // clusters: {} - // contexts: {} - // current-context: "" - // preferences: {} - // users: {} -} - -func ExampleOfOptionsConfig() { - defaultConfig := NewConfig() - defaultConfig.Preferences.Colors = true - defaultConfig.Clusters["alfa"] = &Cluster{ - Server: "https://alfa.org:8080", - APIVersion: "v1", - InsecureSkipTLSVerify: true, - CertificateAuthority: "path/to/my/cert-ca-filename", - } - defaultConfig.Clusters["bravo"] = &Cluster{ - Server: "https://bravo.org:8080", - APIVersion: "v1", - InsecureSkipTLSVerify: false, - } - defaultConfig.AuthInfos["white-mage-via-cert"] = &AuthInfo{ - ClientCertificate: "path/to/my/client-cert-filename", - ClientKey: "path/to/my/client-key-filename", - } - defaultConfig.AuthInfos["red-mage-via-token"] = &AuthInfo{ - Token: "my-secret-token", - } - defaultConfig.Contexts["bravo-as-black-mage"] = &Context{ - Cluster: "bravo", - AuthInfo: "black-mage-via-file", - Namespace: "yankee", - } - defaultConfig.Contexts["alfa-as-black-mage"] = &Context{ - Cluster: "alfa", - AuthInfo: "black-mage-via-file", - Namespace: "zulu", - } - defaultConfig.Contexts["alfa-as-white-mage"] = &Context{ - Cluster: "alfa", - AuthInfo: "white-mage-via-cert", - } - defaultConfig.CurrentContext = "alfa-as-white-mage" - - output, err := yaml.Marshal(defaultConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // clusters: - // alfa: - // LocationOfOrigin: "" - // api-version: v1 - // certificate-authority: path/to/my/cert-ca-filename - // insecure-skip-tls-verify: true - // server: https://alfa.org:8080 - // bravo: - // LocationOfOrigin: "" - // api-version: v1 - // server: https://bravo.org:8080 - // contexts: - // alfa-as-black-mage: - // LocationOfOrigin: "" - // cluster: alfa - // namespace: zulu - // user: black-mage-via-file - // alfa-as-white-mage: - // LocationOfOrigin: "" - // cluster: alfa - // user: white-mage-via-cert - // bravo-as-black-mage: - // LocationOfOrigin: "" - // cluster: bravo - // namespace: yankee - // user: black-mage-via-file - // current-context: alfa-as-white-mage - // preferences: - // colors: true - // users: - // red-mage-via-token: - // LocationOfOrigin: "" - // token: my-secret-token - // white-mage-via-cert: - // LocationOfOrigin: "" - // client-certificate: path/to/my/client-cert-filename - // client-key: path/to/my/client-key-filename -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go index e04f1311e..c9b4ab56b 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go @@ -28,7 +28,11 @@ type Config struct { // Legacy field from pkg/api/types.go TypeMeta. // TODO(jlowdermilk): remove this after eliminating downstream dependencies. Kind string `json:"kind,omitempty"` - // Version of the schema for this config object. + // DEPRECATED: APIVersion is the preferred api version for communicating with the kubernetes cluster (v1, v2, etc). + // Because a cluster can run multiple API groups and potentially multiple versions of each, it no longer makes sense to specify + // a single value for the cluster version. + // This field isnt really needed anyway, so we are deprecating it without replacement. + // It will be ignored if it is present. APIVersion string `json:"apiVersion,omitempty"` // Preferences holds general information to be use for cli interactions Preferences Preferences `json:"preferences"` diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go index e5af51b32..9ff259edf 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go @@ -28,8 +28,7 @@ import ( "github.com/imdario/mergo" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" clientauth "k8s.io/kubernetes/pkg/client/unversioned/auth" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" ) @@ -50,7 +49,7 @@ type ClientConfig interface { // RawConfig returns the merged result of all overrides RawConfig() (clientcmdapi.Config, error) // ClientConfig returns a complete client config - ClientConfig() (*client.Config, error) + ClientConfig() (*restclient.Config, error) // Namespace returns the namespace resulting from the merged // result of all overrides and a boolean indicating if it was // overridden @@ -85,7 +84,7 @@ func (config *DirectClientConfig) RawConfig() (clientcmdapi.Config, error) { } // ClientConfig implements ClientConfig -func (config *DirectClientConfig) ClientConfig() (*client.Config, error) { +func (config *DirectClientConfig) ClientConfig() (*restclient.Config, error) { if err := config.ConfirmUsable(); err != nil { return nil, err } @@ -93,26 +92,21 @@ func (config *DirectClientConfig) ClientConfig() (*client.Config, error) { configAuthInfo := config.getAuthInfo() configClusterInfo := config.getCluster() - clientConfig := &client.Config{} + clientConfig := &restclient.Config{} clientConfig.Host = configClusterInfo.Server if u, err := url.ParseRequestURI(clientConfig.Host); err == nil && u.Opaque == "" && len(u.Path) > 1 { u.RawQuery = "" u.Fragment = "" clientConfig.Host = u.String() } - if len(configClusterInfo.APIVersion) != 0 { - gv, err := unversioned.ParseGroupVersion(configClusterInfo.APIVersion) - if err != nil { - return nil, err - } - clientConfig.GroupVersion = &gv - } // only try to read the auth information if we are secure - if client.IsConfigTransportTLS(*clientConfig) { + if restclient.IsConfigTransportTLS(*clientConfig) { var err error // mergo is a first write wins for map value and a last writing wins for interface values + // NOTE: This behavior changed with https://github.com/imdario/mergo/commit/d304790b2ed594794496464fadd89d2bb266600a. + // Our mergo.Merge version is older than this change. userAuthPartialConfig, err := getUserIdentificationPartialConfig(configAuthInfo, config.fallbackReader) if err != nil { return nil, err @@ -135,11 +129,11 @@ func (config *DirectClientConfig) ClientConfig() (*client.Config, error) { // 1. configClusterInfo (the final result of command line flags and merged .kubeconfig files) // 2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority) // 3. load the ~/.kubernetes_auth file as a default -func getServerIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, configClusterInfo clientcmdapi.Cluster) (*client.Config, error) { - mergedConfig := &client.Config{} +func getServerIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) { + mergedConfig := &restclient.Config{} // configClusterInfo holds the information identify the server provided by .kubeconfig - configClientConfig := &client.Config{} + configClientConfig := &restclient.Config{} configClientConfig.CAFile = configClusterInfo.CertificateAuthority configClientConfig.CAData = configClusterInfo.CertificateAuthorityData configClientConfig.Insecure = configClusterInfo.InsecureSkipTLSVerify @@ -155,8 +149,8 @@ func getServerIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, // 2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority) // 3. if there is not enough information to idenfity the user, load try the ~/.kubernetes_auth file // 4. if there is not enough information to identify the user, prompt if possible -func getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader) (*client.Config, error) { - mergedConfig := &client.Config{} +func getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader) (*restclient.Config, error) { + mergedConfig := &restclient.Config{} // blindly overwrite existing values based on precedence if len(configAuthInfo.Token) > 0 { @@ -180,7 +174,7 @@ func getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fa promptedConfig := makeUserIdentificationConfig(*promptedAuthInfo) previouslyMergedConfig := mergedConfig - mergedConfig = &client.Config{} + mergedConfig = &restclient.Config{} mergo.Merge(mergedConfig, promptedConfig) mergo.Merge(mergedConfig, previouslyMergedConfig) } @@ -189,8 +183,8 @@ func getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fa } // makeUserIdentificationFieldsConfig returns a client.Config capable of being merged using mergo for only user identification information -func makeUserIdentificationConfig(info clientauth.Info) *client.Config { - config := &client.Config{} +func makeUserIdentificationConfig(info clientauth.Info) *restclient.Config { + config := &restclient.Config{} config.Username = info.User config.Password = info.Password config.CertFile = info.CertFile @@ -200,8 +194,8 @@ func makeUserIdentificationConfig(info clientauth.Info) *client.Config { } // makeUserIdentificationFieldsConfig returns a client.Config capable of being merged using mergo for only server identification information -func makeServerIdentificationConfig(info clientauth.Info) client.Config { - config := client.Config{} +func makeServerIdentificationConfig(info clientauth.Info) restclient.Config { + config := restclient.Config{} config.CAFile = info.CAFile if info.Insecure != nil { config.Insecure = *info.Insecure @@ -209,7 +203,7 @@ func makeServerIdentificationConfig(info clientauth.Info) client.Config { return config } -func canIdentifyUser(config client.Config) bool { +func canIdentifyUser(config restclient.Config) bool { return len(config.Username) > 0 || (len(config.CertFile) > 0 || len(config.CertData) > 0) || len(config.BearerToken) > 0 @@ -322,8 +316,8 @@ func (inClusterClientConfig) RawConfig() (clientcmdapi.Config, error) { return clientcmdapi.Config{}, fmt.Errorf("inCluster environment config doesn't support multiple clusters") } -func (inClusterClientConfig) ClientConfig() (*client.Config, error) { - return client.InClusterConfig() +func (inClusterClientConfig) ClientConfig() (*restclient.Config, error) { + return restclient.InClusterConfig() } func (inClusterClientConfig) Namespace() (string, error) { @@ -356,10 +350,10 @@ func (inClusterClientConfig) Possible() bool { // components. Warnings should reflect this usage. If neither masterUrl or kubeconfigPath // are passed in we fallback to inClusterConfig. If inClusterConfig fails, we fallback // to the default config. -func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*client.Config, error) { +func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error) { if kubeconfigPath == "" && masterUrl == "" { glog.Warningf("Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.") - kubeconfig, err := client.InClusterConfig() + kubeconfig, err := restclient.InClusterConfig() if err == nil { return kubeconfig, nil } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config_test.go deleted file mode 100644 index 834869677..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config_test.go +++ /dev/null @@ -1,252 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package clientcmd - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api/testapi" - client "k8s.io/kubernetes/pkg/client/unversioned" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" -) - -func createValidTestConfig() *clientcmdapi.Config { - const ( - server = "https://anything.com:8080" - token = "the-token" - ) - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: server, - APIVersion: testapi.Default.GroupVersion().String(), - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Token: token, - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - return config -} - -func TestMergeContext(t *testing.T) { - const namespace = "overriden-namespace" - - config := createValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}) - - _, overridden, err := clientBuilder.Namespace() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if overridden { - t.Error("Expected namespace to not be overridden") - } - - clientBuilder = NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{ - Context: clientcmdapi.Context{ - Namespace: namespace, - }, - }) - - actual, overridden, err := clientBuilder.Namespace() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if !overridden { - t.Error("Expected namespace to be overridden") - } - - matchStringArg(namespace, actual, t) -} - -func TestCertificateData(t *testing.T) { - caData := []byte("ca-data") - certData := []byte("cert-data") - keyData := []byte("key-data") - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "https://localhost:8443", - APIVersion: testapi.Default.GroupVersion().String(), - CertificateAuthorityData: caData, - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - ClientCertificateData: certData, - ClientKeyData: keyData, - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // Make sure cert data gets into config (will override file paths) - matchByteArg(caData, clientConfig.TLSClientConfig.CAData, t) - matchByteArg(certData, clientConfig.TLSClientConfig.CertData, t) - matchByteArg(keyData, clientConfig.TLSClientConfig.KeyData, t) -} - -func TestBasicAuthData(t *testing.T) { - username := "myuser" - password := "mypass" - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "https://localhost:8443", - APIVersion: testapi.Default.GroupVersion().String(), - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Username: username, - Password: password, - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // Make sure basic auth data gets into config - matchStringArg(username, clientConfig.Username, t) - matchStringArg(password, clientConfig.Password, t) -} - -func TestCreateClean(t *testing.T) { - config := createValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - matchStringArg(config.Clusters["clean"].Server, clientConfig.Host, t) - matchStringArg("", clientConfig.APIPath, t) - matchStringArg(config.Clusters["clean"].APIVersion, clientConfig.GroupVersion.String(), t) - matchBoolArg(config.Clusters["clean"].InsecureSkipTLSVerify, clientConfig.Insecure, t) - matchStringArg(config.AuthInfos["clean"].Token, clientConfig.BearerToken, t) -} - -func TestCreateCleanWithPrefix(t *testing.T) { - tt := []struct { - server string - host string - }{ - {"https://anything.com:8080/foo/bar", "https://anything.com:8080/foo/bar"}, - {"http://anything.com:8080/foo/bar", "http://anything.com:8080/foo/bar"}, - {"http://anything.com:8080/foo/bar/", "http://anything.com:8080/foo/bar/"}, - {"http://anything.com:8080/", "http://anything.com:8080/"}, - {"http://anything.com:8080//", "http://anything.com:8080//"}, - {"anything.com:8080/foo/bar", "anything.com:8080/foo/bar"}, - {"anything.com:8080", "anything.com:8080"}, - {"anything.com", "anything.com"}, - {"anything", "anything"}, - } - - // WARNING: EnvVarCluster.Server is set during package loading time and can not be overriden by os.Setenv inside this test - EnvVarCluster.Server = "" - tt = append(tt, struct{ server, host string }{"", "http://localhost:8080"}) - - for _, tc := range tt { - config := createValidTestConfig() - - cleanConfig := config.Clusters["clean"] - cleanConfig.Server = tc.server - config.Clusters["clean"] = cleanConfig - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - matchStringArg(tc.host, clientConfig.Host, t) - } -} - -func TestCreateCleanDefault(t *testing.T) { - config := createValidTestConfig() - clientBuilder := NewDefaultClientConfig(*config, &ConfigOverrides{}) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - matchStringArg(config.Clusters["clean"].Server, clientConfig.Host, t) - matchStringArg(config.Clusters["clean"].APIVersion, clientConfig.GroupVersion.String(), t) - matchBoolArg(config.Clusters["clean"].InsecureSkipTLSVerify, clientConfig.Insecure, t) - matchStringArg(config.AuthInfos["clean"].Token, clientConfig.BearerToken, t) -} - -func TestCreateMissingContext(t *testing.T) { - const expectedErrorContains = "Context was not found for specified context" - config := createValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "not-present", &ConfigOverrides{}) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - expectedConfig := &client.Config{Host: clientConfig.Host} - - if !reflect.DeepEqual(expectedConfig, clientConfig) { - t.Errorf("Expected %#v, got %#v", expectedConfig, clientConfig) - } - -} - -func matchBoolArg(expected, got bool, t *testing.T) { - if expected != got { - t.Errorf("Expected %v, got %v", expected, got) - } -} - -func matchStringArg(expected, got string, t *testing.T) { - if expected != got { - t.Errorf("Expected %q, got %q", expected, got) - } -} - -func matchByteArg(expected, got []byte, t *testing.T) { - if !reflect.DeepEqual(expected, got) { - t.Errorf("Expected %v, got %v", expected, got) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader_test.go deleted file mode 100644 index 0921f7043..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader_test.go +++ /dev/null @@ -1,562 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package clientcmd - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "reflect" - "strings" - "testing" - - "github.com/ghodss/yaml" - - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - clientcmdlatest "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest" - "k8s.io/kubernetes/pkg/runtime" -) - -var ( - testConfigAlfa = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "red-user": {Token: "red-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "cow-cluster": {Server: "http://cow.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "federal-context": {AuthInfo: "red-user", Cluster: "cow-cluster", Namespace: "hammer-ns"}}, - } - testConfigBravo = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "black-user": {Token: "black-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "pig-cluster": {Server: "http://pig.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "queen-anne-context": {AuthInfo: "black-user", Cluster: "pig-cluster", Namespace: "saw-ns"}}, - } - testConfigCharlie = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "green-user": {Token: "green-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "horse-cluster": {Server: "http://horse.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "shaker-context": {AuthInfo: "green-user", Cluster: "horse-cluster", Namespace: "chisel-ns"}}, - } - testConfigDelta = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "blue-user": {Token: "blue-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "chicken-cluster": {Server: "http://chicken.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "gothic-context": {AuthInfo: "blue-user", Cluster: "chicken-cluster", Namespace: "plane-ns"}}, - } - - testConfigConflictAlfa = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "red-user": {Token: "a-different-red-token"}, - "yellow-user": {Token: "yellow-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "cow-cluster": {Server: "http://a-different-cow.org:8080", InsecureSkipTLSVerify: true}, - "donkey-cluster": {Server: "http://donkey.org:8080", InsecureSkipTLSVerify: true}}, - CurrentContext: "federal-context", - } -) - -func TestNonExistentCommandLineFile(t *testing.T) { - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: "bogus_file", - } - - _, err := loadingRules.Load() - if err == nil { - t.Fatalf("Expected error for missing command-line file, got none") - } - if !strings.Contains(err.Error(), "bogus_file") { - t.Fatalf("Expected error about 'bogus_file', got %s", err.Error()) - } -} - -func TestToleratingMissingFiles(t *testing.T) { - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{"bogus1", "bogus2", "bogus3"}, - } - - _, err := loadingRules.Load() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestErrorReadingFile(t *testing.T) { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - - if err := ioutil.WriteFile(commandLineFile.Name(), []byte("bogus value"), 0644); err != nil { - t.Fatalf("Error creating tempfile: %v", err) - } - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: commandLineFile.Name(), - } - - _, err := loadingRules.Load() - if err == nil { - t.Fatalf("Expected error for unloadable file, got none") - } - if !strings.Contains(err.Error(), commandLineFile.Name()) { - t.Fatalf("Expected error about '%s', got %s", commandLineFile.Name(), err.Error()) - } -} - -func TestErrorReadingNonFile(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "") - if err != nil { - t.Fatalf("Couldn't create tmpdir") - } - defer os.Remove(tmpdir) - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: tmpdir, - } - - _, err = loadingRules.Load() - if err == nil { - t.Fatalf("Expected error for non-file, got none") - } - if !strings.Contains(err.Error(), tmpdir) { - t.Fatalf("Expected error about '%s', got %s", tmpdir, err.Error()) - } -} - -func TestConflictingCurrentContext(t *testing.T) { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - - mockCommandLineConfig := clientcmdapi.Config{ - CurrentContext: "any-context-value", - } - mockEnvVarConfig := clientcmdapi.Config{ - CurrentContext: "a-different-context", - } - - WriteToFile(mockCommandLineConfig, commandLineFile.Name()) - WriteToFile(mockEnvVarConfig, envVarFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: commandLineFile.Name(), - Precedence: []string{envVarFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if mergedConfig.CurrentContext != mockCommandLineConfig.CurrentContext { - t.Errorf("expected %v, got %v", mockCommandLineConfig.CurrentContext, mergedConfig.CurrentContext) - } -} - -func TestLoadingEmptyMaps(t *testing.T) { - configFile, _ := ioutil.TempFile("", "") - defer os.Remove(configFile.Name()) - - mockConfig := clientcmdapi.Config{ - CurrentContext: "any-context-value", - } - - WriteToFile(mockConfig, configFile.Name()) - - config, err := LoadFromFile(configFile.Name()) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if config.Clusters == nil { - t.Error("expected config.Clusters to be non-nil") - } - if config.AuthInfos == nil { - t.Error("expected config.AuthInfos to be non-nil") - } - if config.Contexts == nil { - t.Error("expected config.Contexts to be non-nil") - } -} - -func TestResolveRelativePaths(t *testing.T) { - pathResolutionConfig1 := clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "relative-user-1": {ClientCertificate: "relative/client/cert", ClientKey: "../relative/client/key"}, - "absolute-user-1": {ClientCertificate: "/absolute/client/cert", ClientKey: "/absolute/client/key"}, - }, - Clusters: map[string]*clientcmdapi.Cluster{ - "relative-server-1": {CertificateAuthority: "../relative/ca"}, - "absolute-server-1": {CertificateAuthority: "/absolute/ca"}, - }, - } - pathResolutionConfig2 := clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "relative-user-2": {ClientCertificate: "relative/client/cert2", ClientKey: "../relative/client/key2"}, - "absolute-user-2": {ClientCertificate: "/absolute/client/cert2", ClientKey: "/absolute/client/key2"}, - }, - Clusters: map[string]*clientcmdapi.Cluster{ - "relative-server-2": {CertificateAuthority: "../relative/ca2"}, - "absolute-server-2": {CertificateAuthority: "/absolute/ca2"}, - }, - } - - configDir1, _ := ioutil.TempDir("", "") - configFile1 := path.Join(configDir1, ".kubeconfig") - configDir1, _ = filepath.Abs(configDir1) - defer os.Remove(configFile1) - configDir2, _ := ioutil.TempDir("", "") - configDir2, _ = ioutil.TempDir(configDir2, "") - configFile2 := path.Join(configDir2, ".kubeconfig") - configDir2, _ = filepath.Abs(configDir2) - defer os.Remove(configFile2) - - WriteToFile(pathResolutionConfig1, configFile1) - WriteToFile(pathResolutionConfig2, configFile2) - - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{configFile1, configFile2}, - } - - mergedConfig, err := loadingRules.Load() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - foundClusterCount := 0 - for key, cluster := range mergedConfig.Clusters { - if key == "relative-server-1" { - foundClusterCount++ - matchStringArg(path.Join(configDir1, pathResolutionConfig1.Clusters["relative-server-1"].CertificateAuthority), cluster.CertificateAuthority, t) - } - if key == "relative-server-2" { - foundClusterCount++ - matchStringArg(path.Join(configDir2, pathResolutionConfig2.Clusters["relative-server-2"].CertificateAuthority), cluster.CertificateAuthority, t) - } - if key == "absolute-server-1" { - foundClusterCount++ - matchStringArg(pathResolutionConfig1.Clusters["absolute-server-1"].CertificateAuthority, cluster.CertificateAuthority, t) - } - if key == "absolute-server-2" { - foundClusterCount++ - matchStringArg(pathResolutionConfig2.Clusters["absolute-server-2"].CertificateAuthority, cluster.CertificateAuthority, t) - } - } - if foundClusterCount != 4 { - t.Errorf("Expected 4 clusters, found %v: %v", foundClusterCount, mergedConfig.Clusters) - } - - foundAuthInfoCount := 0 - for key, authInfo := range mergedConfig.AuthInfos { - if key == "relative-user-1" { - foundAuthInfoCount++ - matchStringArg(path.Join(configDir1, pathResolutionConfig1.AuthInfos["relative-user-1"].ClientCertificate), authInfo.ClientCertificate, t) - matchStringArg(path.Join(configDir1, pathResolutionConfig1.AuthInfos["relative-user-1"].ClientKey), authInfo.ClientKey, t) - } - if key == "relative-user-2" { - foundAuthInfoCount++ - matchStringArg(path.Join(configDir2, pathResolutionConfig2.AuthInfos["relative-user-2"].ClientCertificate), authInfo.ClientCertificate, t) - matchStringArg(path.Join(configDir2, pathResolutionConfig2.AuthInfos["relative-user-2"].ClientKey), authInfo.ClientKey, t) - } - if key == "absolute-user-1" { - foundAuthInfoCount++ - matchStringArg(pathResolutionConfig1.AuthInfos["absolute-user-1"].ClientCertificate, authInfo.ClientCertificate, t) - matchStringArg(pathResolutionConfig1.AuthInfos["absolute-user-1"].ClientKey, authInfo.ClientKey, t) - } - if key == "absolute-user-2" { - foundAuthInfoCount++ - matchStringArg(pathResolutionConfig2.AuthInfos["absolute-user-2"].ClientCertificate, authInfo.ClientCertificate, t) - matchStringArg(pathResolutionConfig2.AuthInfos["absolute-user-2"].ClientKey, authInfo.ClientKey, t) - } - } - if foundAuthInfoCount != 4 { - t.Errorf("Expected 4 users, found %v: %v", foundAuthInfoCount, mergedConfig.AuthInfos) - } - -} - -func TestMigratingFile(t *testing.T) { - sourceFile, _ := ioutil.TempFile("", "") - defer os.Remove(sourceFile.Name()) - destinationFile, _ := ioutil.TempFile("", "") - // delete the file so that we'll write to it - os.Remove(destinationFile.Name()) - - WriteToFile(testConfigAlfa, sourceFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - MigrationRules: map[string]string{destinationFile.Name(): sourceFile.Name()}, - } - - if _, err := loadingRules.Load(); err != nil { - t.Errorf("unexpected error %v", err) - } - - // the load should have recreated this file - defer os.Remove(destinationFile.Name()) - - sourceContent, err := ioutil.ReadFile(sourceFile.Name()) - if err != nil { - t.Errorf("unexpected error %v", err) - } - destinationContent, err := ioutil.ReadFile(destinationFile.Name()) - if err != nil { - t.Errorf("unexpected error %v", err) - } - - if !reflect.DeepEqual(sourceContent, destinationContent) { - t.Errorf("source and destination do not match") - } -} - -func TestMigratingFileLeaveExistingFileAlone(t *testing.T) { - sourceFile, _ := ioutil.TempFile("", "") - defer os.Remove(sourceFile.Name()) - destinationFile, _ := ioutil.TempFile("", "") - defer os.Remove(destinationFile.Name()) - - WriteToFile(testConfigAlfa, sourceFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - MigrationRules: map[string]string{destinationFile.Name(): sourceFile.Name()}, - } - - if _, err := loadingRules.Load(); err != nil { - t.Errorf("unexpected error %v", err) - } - - destinationContent, err := ioutil.ReadFile(destinationFile.Name()) - if err != nil { - t.Errorf("unexpected error %v", err) - } - - if len(destinationContent) > 0 { - t.Errorf("destination should not have been touched") - } -} - -func TestMigratingFileSourceMissingSkip(t *testing.T) { - sourceFilename := "some-missing-file" - destinationFile, _ := ioutil.TempFile("", "") - // delete the file so that we'll write to it - os.Remove(destinationFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - MigrationRules: map[string]string{destinationFile.Name(): sourceFilename}, - } - - if _, err := loadingRules.Load(); err != nil { - t.Errorf("unexpected error %v", err) - } - - if _, err := os.Stat(destinationFile.Name()); !os.IsNotExist(err) { - t.Errorf("destination should not exist") - } -} - -func ExampleNoMergingOnExplicitPaths() { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - - WriteToFile(testConfigAlfa, commandLineFile.Name()) - WriteToFile(testConfigConflictAlfa, envVarFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: commandLineFile.Name(), - Precedence: []string{envVarFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - - json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - output, err := yaml.JSONToYAML(json) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // apiVersion: v1 - // clusters: - // - cluster: - // server: http://cow.org:8080 - // name: cow-cluster - // contexts: - // - context: - // cluster: cow-cluster - // namespace: hammer-ns - // user: red-user - // name: federal-context - // current-context: "" - // kind: Config - // preferences: {} - // users: - // - name: red-user - // user: - // token: red-token -} - -func ExampleMergingSomeWithConflict() { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - - WriteToFile(testConfigAlfa, commandLineFile.Name()) - WriteToFile(testConfigConflictAlfa, envVarFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{commandLineFile.Name(), envVarFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - - json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - output, err := yaml.JSONToYAML(json) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // apiVersion: v1 - // clusters: - // - cluster: - // server: http://cow.org:8080 - // name: cow-cluster - // - cluster: - // insecure-skip-tls-verify: true - // server: http://donkey.org:8080 - // name: donkey-cluster - // contexts: - // - context: - // cluster: cow-cluster - // namespace: hammer-ns - // user: red-user - // name: federal-context - // current-context: federal-context - // kind: Config - // preferences: {} - // users: - // - name: red-user - // user: - // token: red-token - // - name: yellow-user - // user: - // token: yellow-token -} - -func ExampleMergingEverythingNoConflicts() { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - currentDirFile, _ := ioutil.TempFile("", "") - defer os.Remove(currentDirFile.Name()) - homeDirFile, _ := ioutil.TempFile("", "") - defer os.Remove(homeDirFile.Name()) - - WriteToFile(testConfigAlfa, commandLineFile.Name()) - WriteToFile(testConfigBravo, envVarFile.Name()) - WriteToFile(testConfigCharlie, currentDirFile.Name()) - WriteToFile(testConfigDelta, homeDirFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{commandLineFile.Name(), envVarFile.Name(), currentDirFile.Name(), homeDirFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - - json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - output, err := yaml.JSONToYAML(json) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // apiVersion: v1 - // clusters: - // - cluster: - // server: http://chicken.org:8080 - // name: chicken-cluster - // - cluster: - // server: http://cow.org:8080 - // name: cow-cluster - // - cluster: - // server: http://horse.org:8080 - // name: horse-cluster - // - cluster: - // server: http://pig.org:8080 - // name: pig-cluster - // contexts: - // - context: - // cluster: cow-cluster - // namespace: hammer-ns - // user: red-user - // name: federal-context - // - context: - // cluster: chicken-cluster - // namespace: plane-ns - // user: blue-user - // name: gothic-context - // - context: - // cluster: pig-cluster - // namespace: saw-ns - // user: black-user - // name: queen-anne-context - // - context: - // cluster: horse-cluster - // namespace: chisel-ns - // user: green-user - // name: shaker-context - // current-context: "" - // kind: Config - // preferences: {} - // users: - // - name: black-user - // user: - // token: black-token - // - name: blue-user - // user: - // token: blue-token - // - name: green-user - // user: - // token: green-token - // - name: red-user - // user: - // token: red-token -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go index 8fee4b9ec..321eae9e8 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go @@ -23,7 +23,7 @@ import ( "github.com/golang/glog" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" ) @@ -86,7 +86,7 @@ func (config *DeferredLoadingClientConfig) RawConfig() (clientcmdapi.Config, err } // ClientConfig implements ClientConfig -func (config *DeferredLoadingClientConfig) ClientConfig() (*client.Config, error) { +func (config *DeferredLoadingClientConfig) ClientConfig() (*restclient.Config, error) { mergedClientConfig, err := config.createClientConfig() if err != nil { return nil, err diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go index d6bc496a2..9996d2f44 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go @@ -134,7 +134,7 @@ func RecommendedAuthOverrideFlags(prefix string) AuthOverrideFlags { func RecommendedClusterOverrideFlags(prefix string) ClusterOverrideFlags { return ClusterOverrideFlags{ APIServer: FlagInfo{prefix + FlagAPIServer, "", "", "The address and port of the Kubernetes API server"}, - APIVersion: FlagInfo{prefix + FlagAPIVersion, "", "", "The API version to use when talking to the 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."}, } @@ -171,7 +171,9 @@ func BindAuthInfoFlags(authInfo *clientcmdapi.AuthInfo, flags *pflag.FlagSet, fl // BindClusterFlags is a convenience method to bind the specified flags to their associated variables func BindClusterFlags(clusterInfo *clientcmdapi.Cluster, flags *pflag.FlagSet, flagNames ClusterOverrideFlags) { flagNames.APIServer.BindStringFlag(flags, &clusterInfo.Server) + // TODO: remove --api-version flag in 1.3. flagNames.APIVersion.BindStringFlag(flags, &clusterInfo.APIVersion) + flags.MarkDeprecated(FlagAPIVersion, "flag is no longer respected and will be deleted in the next release") flagNames.CertificateAuthority.BindStringFlag(flags, &clusterInfo.CertificateAuthority) flagNames.InsecureSkipTLSVerify.BindBoolFlag(flags, &clusterInfo.InsecureSkipTLSVerify) } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/validation_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/validation_test.go deleted file mode 100644 index ca4843a87..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/validation_test.go +++ /dev/null @@ -1,432 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package clientcmd - -import ( - "io/ioutil" - "os" - "strings" - "testing" - - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - utilerrors "k8s.io/kubernetes/pkg/util/errors" -) - -func TestConfirmUsableBadInfoButOkConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["missing ca"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: "missing", - } - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - Username: "anything", - Token: "here", - } - config.Contexts["dirty"] = &clientcmdapi.Context{ - Cluster: "missing ca", - AuthInfo: "error", - } - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "anything", - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Token: "here", - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - - badValidation := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read certificate-authority"}, - } - okTest := configValidationTest{ - config: config, - } - - okTest.testConfirmUsable("clean", t) - badValidation.testConfig(t) -} -func TestConfirmUsableBadInfoConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["missing ca"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: "missing", - } - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - Username: "anything", - Token: "here", - } - config.Contexts["first"] = &clientcmdapi.Context{ - Cluster: "missing ca", - AuthInfo: "error", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read certificate-authority"}, - } - - test.testConfirmUsable("first", t) -} -func TestConfirmUsableEmptyConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"invalid configuration: no configuration has been provided"}, - } - - test.testConfirmUsable("", t) -} -func TestConfirmUsableMissingConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"invalid configuration: no configuration has been provided"}, - } - - test.testConfirmUsable("not-here", t) -} -func TestValidateEmptyConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"invalid configuration: no configuration has been provided"}, - } - - test.testConfig(t) -} -func TestValidateMissingCurrentContextConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"context was not found for specified "}, - } - - test.testConfig(t) -} -func TestIsContextNotFound(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - - err := Validate(*config) - if !IsContextNotFound(err) { - t.Errorf("Expected context not found, but got %v", err) - } - if !IsConfigurationInvalid(err) { - t.Errorf("Expected configuration invalid, but got %v", err) - } -} - -func TestIsEmptyConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - - err := Validate(*config) - if !IsEmptyConfig(err) { - t.Errorf("Expected context not found, but got %v", err) - } - if !IsConfigurationInvalid(err) { - t.Errorf("Expected configuration invalid, but got %v", err) - } -} - -func TestIsConfigurationInvalid(t *testing.T) { - if newErrConfigurationInvalid([]error{}) != nil { - t.Errorf("unexpected error") - } - if newErrConfigurationInvalid([]error{ErrNoContext}) == ErrNoContext { - t.Errorf("unexpected error") - } - if newErrConfigurationInvalid([]error{ErrNoContext, ErrNoContext}) == nil { - t.Errorf("unexpected error") - } - if !IsConfigurationInvalid(newErrConfigurationInvalid([]error{ErrNoContext, ErrNoContext})) { - t.Errorf("unexpected error") - } -} - -func TestValidateMissingReferencesConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - config.Contexts["anything"] = &clientcmdapi.Context{Cluster: "missing", AuthInfo: "missing"} - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"user \"missing\" was not found for context \"anything\"", "cluster \"missing\" was not found for context \"anything\""}, - } - - test.testContext("anything", t) - test.testConfig(t) -} -func TestValidateEmptyContext(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - config.Contexts["anything"] = &clientcmdapi.Context{} - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"user was not specified for context \"anything\"", "cluster was not specified for context \"anything\""}, - } - - test.testContext("anything", t) - test.testConfig(t) -} - -func TestValidateEmptyClusterInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["empty"] = &clientcmdapi.Cluster{} - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"cluster has no server defined"}, - } - - test.testCluster("empty", t) - test.testConfig(t) -} -func TestValidateMissingCAFileClusterInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["missing ca"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: "missing", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read certificate-authority"}, - } - - test.testCluster("missing ca", t) - test.testConfig(t) -} -func TestValidateCleanClusterInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "anything", - } - test := configValidationTest{ - config: config, - } - - test.testCluster("clean", t) - test.testConfig(t) -} -func TestValidateCleanWithCAClusterInfo(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") - defer os.Remove(tempFile.Name()) - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: tempFile.Name(), - } - test := configValidationTest{ - config: config, - } - - test.testCluster("clean", t) - test.testConfig(t) -} - -func TestValidateEmptyAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{} - test := configValidationTest{ - config: config, - } - - test.testAuthInfo("error", t) - test.testConfig(t) -} -func TestValidateCertFilesNotFoundAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - ClientCertificate: "missing", - ClientKey: "missing", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read client-cert", "unable to read client-key"}, - } - - test.testAuthInfo("error", t) - test.testConfig(t) -} -func TestValidateCertDataOverridesFiles(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") - defer os.Remove(tempFile.Name()) - - config := clientcmdapi.NewConfig() - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - ClientCertificate: tempFile.Name(), - ClientCertificateData: []byte("certdata"), - ClientKey: tempFile.Name(), - ClientKeyData: []byte("keydata"), - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"client-cert-data and client-cert are both specified", "client-key-data and client-key are both specified"}, - } - - test.testAuthInfo("clean", t) - test.testConfig(t) -} -func TestValidateCleanCertFilesAuthInfo(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") - defer os.Remove(tempFile.Name()) - - config := clientcmdapi.NewConfig() - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - ClientCertificate: tempFile.Name(), - ClientKey: tempFile.Name(), - } - test := configValidationTest{ - config: config, - } - - test.testAuthInfo("clean", t) - test.testConfig(t) -} -func TestValidateCleanTokenAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Token: "any-value", - } - test := configValidationTest{ - config: config, - } - - test.testAuthInfo("clean", t) - test.testConfig(t) -} - -func TestValidateMultipleMethodsAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - Token: "token", - Username: "username", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"more than one authentication method", "token", "basicAuth"}, - } - - test.testAuthInfo("error", t) - test.testConfig(t) -} - -type configValidationTest struct { - config *clientcmdapi.Config - expectedErrorSubstring []string -} - -func (c configValidationTest) testContext(contextName string, t *testing.T) { - errs := validateContext(contextName, *c.config.Contexts[contextName], *c.config) - - if len(c.expectedErrorSubstring) != 0 { - if len(errs) == 0 { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } - for _, curr := range c.expectedErrorSubstring { - if len(errs) != 0 && !strings.Contains(utilerrors.NewAggregate(errs).Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, utilerrors.NewAggregate(errs)) - } - } - - } else { - if len(errs) != 0 { - t.Errorf("Unexpected error: %v", utilerrors.NewAggregate(errs)) - } - } -} -func (c configValidationTest) testConfirmUsable(contextName string, t *testing.T) { - err := ConfirmUsable(*c.config, contextName) - - if len(c.expectedErrorSubstring) != 0 { - if err == nil { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } else { - for _, curr := range c.expectedErrorSubstring { - if err != nil && !strings.Contains(err.Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, err) - } - } - } - } else { - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - } -} -func (c configValidationTest) testConfig(t *testing.T) { - err := Validate(*c.config) - - if len(c.expectedErrorSubstring) != 0 { - if err == nil { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } else { - for _, curr := range c.expectedErrorSubstring { - if err != nil && !strings.Contains(err.Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, err) - } - } - if !IsConfigurationInvalid(err) { - t.Errorf("all errors should be configuration invalid: %v", err) - } - } - } else { - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - } -} -func (c configValidationTest) testCluster(clusterName string, t *testing.T) { - errs := validateClusterInfo(clusterName, *c.config.Clusters[clusterName]) - - if len(c.expectedErrorSubstring) != 0 { - if len(errs) == 0 { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } - for _, curr := range c.expectedErrorSubstring { - if len(errs) != 0 && !strings.Contains(utilerrors.NewAggregate(errs).Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, utilerrors.NewAggregate(errs)) - } - } - - } else { - if len(errs) != 0 { - t.Errorf("Unexpected error: %v", utilerrors.NewAggregate(errs)) - } - } -} - -func (c configValidationTest) testAuthInfo(authInfoName string, t *testing.T) { - errs := validateAuthInfo(authInfoName, *c.config.AuthInfos[authInfoName]) - - if len(c.expectedErrorSubstring) != 0 { - if len(errs) == 0 { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } - for _, curr := range c.expectedErrorSubstring { - if len(errs) != 0 && !strings.Contains(utilerrors.NewAggregate(errs).Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, utilerrors.NewAggregate(errs)) - } - } - - } else { - if len(errs) != 0 { - t.Errorf("Unexpected error: %v", utilerrors.NewAggregate(errs)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/conditions.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/conditions.go index 7102c8116..5087baa80 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/conditions.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/conditions.go @@ -153,12 +153,18 @@ func JobHasDesiredParallelism(c ExtensionsInterface, job *extensions.Job) wait.C // the desired replica count for a deployment equals its updated replicas count. // (non-terminated pods that have the desired template spec). func DeploymentHasDesiredReplicas(c ExtensionsInterface, deployment *extensions.Deployment) wait.ConditionFunc { + // If we're given a deployment where the status lags the spec, it either + // means that the deployment is stale, or that the deployment manager hasn't + // noticed the update yet. Polling status.Replicas is not safe in the latter + // case. + desiredGeneration := deployment.Generation return func() (bool, error) { deployment, err := c.Deployments(deployment.Namespace).Get(deployment.Name) if err != nil { return false, err } - return deployment.Status.UpdatedReplicas == deployment.Spec.Replicas, nil + return deployment.Status.ObservedGeneration >= desiredGeneration && + deployment.Status.UpdatedReplicas == deployment.Spec.Replicas, nil } } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/conditions_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/conditions_test.go deleted file mode 100644 index 1042461c0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/conditions_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "fmt" - "testing" - - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/util/wait" -) - -func TestRetryOnConflict(t *testing.T) { - opts := wait.Backoff{Factor: 1.0, Steps: 3} - conflictErr := errors.NewConflict(unversioned.GroupResource{Resource: "test"}, "other", nil) - - // never returns - err := RetryOnConflict(opts, func() error { - return conflictErr - }) - if err != conflictErr { - t.Errorf("unexpected error: %v", err) - } - - // returns immediately - i := 0 - err = RetryOnConflict(opts, func() error { - i++ - return nil - }) - if err != nil || i != 1 { - t.Errorf("unexpected error: %v", err) - } - - // returns immediately on error - testErr := fmt.Errorf("some other error") - err = RetryOnConflict(opts, func() error { - return testErr - }) - if err != testErr { - t.Errorf("unexpected error: %v", err) - } - - // keeps retrying - i = 0 - err = RetryOnConflict(opts, func() error { - if i < 2 { - i++ - return errors.NewConflict(unversioned.GroupResource{Resource: "test"}, "other", nil) - } - return nil - }) - if err != nil || i != 2 { - t.Errorf("unexpected error: %v", err) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/containerinfo_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/containerinfo_test.go deleted file mode 100644 index 5e7e9768d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/containerinfo_test.go +++ /dev/null @@ -1,200 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "path" - "reflect" - "strconv" - "strings" - "testing" - "time" - - cadvisorapi "github.com/google/cadvisor/info/v1" - cadvisorapitest "github.com/google/cadvisor/info/v1/test" -) - -func testHTTPContainerInfoGetter( - req *cadvisorapi.ContainerInfoRequest, - cinfo *cadvisorapi.ContainerInfo, - podID string, - containerID string, - status int, - t *testing.T, -) { - expectedPath := "/stats" - if len(podID) > 0 && len(containerID) > 0 { - expectedPath = path.Join(expectedPath, podID, containerID) - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if status != 0 { - w.WriteHeader(status) - } - if strings.TrimRight(r.URL.Path, "/") != strings.TrimRight(expectedPath, "/") { - t.Fatalf("Received request to an invalid path. Should be %v. got %v", - expectedPath, r.URL.Path) - } - - var receivedReq cadvisorapi.ContainerInfoRequest - err := json.NewDecoder(r.Body).Decode(&receivedReq) - if err != nil { - t.Fatal(err) - } - // Note: This will not make a deep copy of req. - // So changing req after Get*Info would be a race. - expectedReq := req - // Fill any empty fields with default value - if !expectedReq.Equals(receivedReq) { - t.Errorf("received wrong request") - } - err = json.NewEncoder(w).Encode(cinfo) - if err != nil { - t.Fatal(err) - } - })) - // TODO: Uncomment when fix #19254 - // defer ts.Close() - hostURL, err := url.Parse(ts.URL) - if err != nil { - t.Fatal(err) - } - parts := strings.Split(hostURL.Host, ":") - - port, err := strconv.Atoi(parts[1]) - if err != nil { - t.Fatal(err) - } - - containerInfoGetter := &HTTPContainerInfoGetter{ - Client: http.DefaultClient, - Port: port, - } - - var receivedContainerInfo *cadvisorapi.ContainerInfo - if len(podID) > 0 && len(containerID) > 0 { - receivedContainerInfo, err = containerInfoGetter.GetContainerInfo(parts[0], podID, containerID, req) - } else { - receivedContainerInfo, err = containerInfoGetter.GetRootInfo(parts[0], req) - } - if status == 0 || status == http.StatusOK { - if err != nil { - t.Errorf("received unexpected error: %v", err) - } - - if !receivedContainerInfo.Eq(cinfo) { - t.Error("received unexpected container info") - } - } else { - if err == nil { - t.Error("did not receive expected error.") - } - } -} - -func TestHTTPContainerInfoGetterGetContainerInfoSuccessfully(t *testing.T) { - req := &cadvisorapi.ContainerInfoRequest{ - NumStats: 10, - } - cinfo := cadvisorapitest.GenerateRandomContainerInfo( - "dockerIDWhichWillNotBeChecked", // docker ID - 2, // Number of cores - req, - 1*time.Second, - ) - testHTTPContainerInfoGetter(req, cinfo, "somePodID", "containerNameInK8S", 0, t) -} - -func TestHTTPContainerInfoGetterGetRootInfoSuccessfully(t *testing.T) { - req := &cadvisorapi.ContainerInfoRequest{ - NumStats: 10, - } - cinfo := cadvisorapitest.GenerateRandomContainerInfo( - "dockerIDWhichWillNotBeChecked", // docker ID - 2, // Number of cores - req, - 1*time.Second, - ) - testHTTPContainerInfoGetter(req, cinfo, "", "", 0, t) -} - -func TestHTTPContainerInfoGetterGetContainerInfoWithError(t *testing.T) { - req := &cadvisorapi.ContainerInfoRequest{ - NumStats: 10, - } - cinfo := cadvisorapitest.GenerateRandomContainerInfo( - "dockerIDWhichWillNotBeChecked", // docker ID - 2, // Number of cores - req, - 1*time.Second, - ) - testHTTPContainerInfoGetter(req, cinfo, "somePodID", "containerNameInK8S", http.StatusNotFound, t) -} - -func TestHTTPContainerInfoGetterGetRootInfoWithError(t *testing.T) { - req := &cadvisorapi.ContainerInfoRequest{ - NumStats: 10, - } - cinfo := cadvisorapitest.GenerateRandomContainerInfo( - "dockerIDWhichWillNotBeChecked", // docker ID - 2, // Number of cores - req, - 1*time.Second, - ) - testHTTPContainerInfoGetter(req, cinfo, "", "", http.StatusNotFound, t) -} - -func TestHTTPGetMachineInfo(t *testing.T) { - mspec := &cadvisorapi.MachineInfo{ - NumCores: 4, - MemoryCapacity: 2048, - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - err := json.NewEncoder(w).Encode(mspec) - if err != nil { - t.Fatal(err) - } - })) - // TODO: Uncomment when fix #19254 - // defer ts.Close() - hostURL, err := url.Parse(ts.URL) - if err != nil { - t.Fatal(err) - } - parts := strings.Split(hostURL.Host, ":") - - port, err := strconv.Atoi(parts[1]) - if err != nil { - t.Fatal(err) - } - - containerInfoGetter := &HTTPContainerInfoGetter{ - Client: http.DefaultClient, - Port: port, - } - - received, err := containerInfoGetter.GetMachineInfo(parts[0]) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(received, mspec) { - t.Errorf("received wrong machine spec") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/daemon_sets_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/daemon_sets_test.go deleted file mode 100644 index 2bfbb44b0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/daemon_sets_test.go +++ /dev/null @@ -1,199 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/extensions" -) - -func getDSResourceName() string { - return "daemonsets" -} - -func TestListDaemonSets(t *testing.T) { - ns := api.NamespaceAll - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getDSResourceName(), ns, ""), - }, - Response: simple.Response{StatusCode: 200, - Body: &extensions.DaemonSetList{ - Items: []extensions.DaemonSet{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.DaemonSetSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - }, - }, - } - receivedDSs, err := c.Setup(t).Extensions().DaemonSets(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, receivedDSs, err) - -} - -func TestGetDaemonSet(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Extensions.ResourcePath(getDSResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.DaemonSetSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - } - receivedDaemonSet, err := c.Setup(t).Extensions().DaemonSets(ns).Get("foo") - defer c.Close() - c.Validate(t, receivedDaemonSet, err) -} - -func TestGetDaemonSetWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedPod, err := c.Setup(t).Extensions().DaemonSets(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedPod, err) -} - -func TestUpdateDaemonSet(t *testing.T) { - ns := api.NamespaceDefault - requestDaemonSet := &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Extensions.ResourcePath(getDSResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.DaemonSetSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - } - receivedDaemonSet, err := c.Setup(t).Extensions().DaemonSets(ns).Update(requestDaemonSet) - defer c.Close() - c.Validate(t, receivedDaemonSet, err) -} - -func TestUpdateDaemonSetUpdateStatus(t *testing.T) { - ns := api.NamespaceDefault - requestDaemonSet := &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Extensions.ResourcePath(getDSResourceName(), ns, "foo") + "/status", Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.DaemonSetSpec{ - Template: api.PodTemplateSpec{}, - }, - Status: extensions.DaemonSetStatus{}, - }, - }, - } - receivedDaemonSet, err := c.Setup(t).Extensions().DaemonSets(ns).UpdateStatus(requestDaemonSet) - defer c.Close() - c.Validate(t, receivedDaemonSet, err) -} - -func TestDeleteDaemon(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Extensions.ResourcePath(getDSResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Extensions().DaemonSets(ns).Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestCreateDaemonSet(t *testing.T) { - ns := api.NamespaceDefault - requestDaemonSet := &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "POST", Path: testapi.Extensions.ResourcePath(getDSResourceName(), ns, ""), Body: requestDaemonSet, Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.DaemonSetSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - } - receivedDaemonSet, err := c.Setup(t).Extensions().DaemonSets(ns).Create(requestDaemonSet) - defer c.Close() - c.Validate(t, receivedDaemonSet, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/deployment_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/deployment_test.go deleted file mode 100644 index 2480c3a25..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/deployment_test.go +++ /dev/null @@ -1,240 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/http" - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/labels" -) - -func getDeploymentsResourceName() string { - return "deployments" -} - -func TestDeploymentCreate(t *testing.T) { - ns := api.NamespaceDefault - deployment := extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Extensions.ResourcePath(getDeploymentsResourceName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: &deployment, - }, - Response: simple.Response{StatusCode: 200, Body: &deployment}, - } - - response, err := c.Setup(t).Deployments(ns).Create(&deployment) - defer c.Close() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - c.Validate(t, response, err) -} - -func TestDeploymentGet(t *testing.T) { - ns := api.NamespaceDefault - deployment := &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getDeploymentsResourceName(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: deployment}, - } - - response, err := c.Setup(t).Deployments(ns).Get("abc") - defer c.Close() - c.Validate(t, response, err) -} - -func TestDeploymentList(t *testing.T) { - ns := api.NamespaceDefault - deploymentList := &extensions.DeploymentList{ - Items: []extensions.Deployment{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getDeploymentsResourceName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: deploymentList}, - } - response, err := c.Setup(t).Deployments(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestDeploymentUpdate(t *testing.T) { - ns := api.NamespaceDefault - deployment := &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Extensions.ResourcePath(getDeploymentsResourceName(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{StatusCode: 200, Body: deployment}, - } - response, err := c.Setup(t).Deployments(ns).Update(deployment) - defer c.Close() - c.Validate(t, response, err) -} - -func TestDeploymentUpdateStatus(t *testing.T) { - ns := api.NamespaceDefault - deployment := &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Extensions.ResourcePath(getDeploymentsResourceName(), ns, "abc") + "/status", - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{StatusCode: 200, Body: deployment}, - } - response, err := c.Setup(t).Deployments(ns).UpdateStatus(deployment) - defer c.Close() - c.Validate(t, response, err) -} - -func TestDeploymentDelete(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "DELETE", - Path: testapi.Extensions.ResourcePath(getDeploymentsResourceName(), ns, "foo"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Deployments(ns).Delete("foo", nil) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestDeploymentWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePathWithPrefix("watch", getDeploymentsResourceName(), "", ""), - Query: url.Values{"resourceVersion": []string{}}, - }, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).Deployments(api.NamespaceAll).Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestListDeploymentsLabels(t *testing.T) { - ns := api.NamespaceDefault - labelSelectorQueryParamName := unversioned.LabelSelectorQueryParam(testapi.Extensions.GroupVersion().String()) - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath("deployments", ns, ""), - Query: simple.BuildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})}, - Response: simple.Response{ - StatusCode: http.StatusOK, - Body: &extensions.DeploymentList{ - Items: []extensions.Deployment{ - { - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - }, - }, - }, - }, - } - c.Setup(t) - defer c.Close() - c.QueryValidator[labelSelectorQueryParamName] = simple.ValidateLabels - selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector() - options := api.ListOptions{LabelSelector: selector} - receivedPodList, err := c.Deployments(ns).List(options) - c.Validate(t, receivedPodList, err) -} - -func TestDeploymentRollback(t *testing.T) { - ns := api.NamespaceDefault - deploymentRollback := &extensions.DeploymentRollback{ - Name: "abc", - UpdatedAnnotations: map[string]string{}, - RollbackTo: extensions.RollbackConfig{Revision: 1}, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Extensions.ResourcePath(getDeploymentsResourceName(), ns, "abc") + "/rollback", - Query: simple.BuildQueryValues(nil), - Body: deploymentRollback, - }, - Response: simple.Response{StatusCode: http.StatusOK}, - } - err := c.Setup(t).Deployments(ns).Rollback(deploymentRollback) - defer c.Close() - c.ValidateCommon(t, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/endpoints_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/endpoints_test.go deleted file mode 100644 index ef1701585..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/endpoints_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func TestListEndpoints(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Default.ResourcePath("endpoints", ns, ""), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, - Body: &api.EndpointsList{ - Items: []api.Endpoints{ - { - ObjectMeta: api.ObjectMeta{Name: "endpoint-1"}, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "10.245.1.2"}, {IP: "10.245.1.3"}}, - Ports: []api.EndpointPort{{Port: 8080}}, - }}, - }, - }, - }, - }, - } - receivedEndpointsList, err := c.Setup(t).Endpoints(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, receivedEndpointsList, err) -} - -func TestGetEndpoints(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Default.ResourcePath("endpoints", ns, "endpoint-1"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: &api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "endpoint-1"}}}, - } - response, err := c.Setup(t).Endpoints(ns).Get("endpoint-1") - defer c.Close() - c.Validate(t, response, err) -} - -func TestGetEndpointWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedPod, err := c.Setup(t).Endpoints(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedPod, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/events_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/events_test.go deleted file mode 100644 index 371c7544e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/events_test.go +++ /dev/null @@ -1,205 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" -) - -func TestEventSearch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("events", "baz", ""), - Query: url.Values{ - unversioned.FieldSelectorQueryParam(testapi.Default.GroupVersion().String()): []string{ - GetInvolvedObjectNameFieldLabel(testapi.Default.GroupVersion().String()) + "=foo,", - "involvedObject.namespace=baz,", - "involvedObject.kind=Pod", - }, - unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()): []string{}, - }, - }, - Response: simple.Response{StatusCode: 200, Body: &api.EventList{}}, - } - eventList, err := c.Setup(t).Events("baz").Search( - &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "baz", - SelfLink: testapi.Default.SelfLink("pods", ""), - }, - }, - ) - defer c.Close() - c.Validate(t, eventList, err) -} - -func TestEventCreate(t *testing.T) { - objReference := &api.ObjectReference{ - Kind: "foo", - Namespace: "nm", - Name: "objref1", - UID: "uid", - APIVersion: "apiv1", - ResourceVersion: "1", - } - timeStamp := unversioned.Now() - event := &api.Event{ - ObjectMeta: api.ObjectMeta{ - Namespace: api.NamespaceDefault, - }, - InvolvedObject: *objReference, - FirstTimestamp: timeStamp, - LastTimestamp: timeStamp, - Count: 1, - Type: api.EventTypeNormal, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath("events", api.NamespaceDefault, ""), - Body: event, - }, - Response: simple.Response{StatusCode: 200, Body: event}, - } - - response, err := c.Setup(t).Events(api.NamespaceDefault).Create(event) - defer c.Close() - - if err != nil { - t.Fatalf("%v should be nil.", err) - } - - if e, a := *objReference, response.InvolvedObject; !reflect.DeepEqual(e, a) { - t.Errorf("%#v != %#v.", e, a) - } -} - -func TestEventGet(t *testing.T) { - objReference := &api.ObjectReference{ - Kind: "foo", - Namespace: "nm", - Name: "objref1", - UID: "uid", - APIVersion: "apiv1", - ResourceVersion: "1", - } - timeStamp := unversioned.Now() - event := &api.Event{ - ObjectMeta: api.ObjectMeta{ - Namespace: "other", - }, - InvolvedObject: *objReference, - FirstTimestamp: timeStamp, - LastTimestamp: timeStamp, - Count: 1, - Type: api.EventTypeNormal, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("events", "other", "1"), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: event}, - } - - response, err := c.Setup(t).Events("other").Get("1") - defer c.Close() - - if err != nil { - t.Fatalf("%v should be nil.", err) - } - - if e, r := event.InvolvedObject, response.InvolvedObject; !reflect.DeepEqual(e, r) { - t.Errorf("%#v != %#v.", e, r) - } -} - -func TestEventList(t *testing.T) { - ns := api.NamespaceDefault - objReference := &api.ObjectReference{ - Kind: "foo", - Namespace: ns, - Name: "objref1", - UID: "uid", - APIVersion: "apiv1", - ResourceVersion: "1", - } - timeStamp := unversioned.Now() - eventList := &api.EventList{ - Items: []api.Event{ - { - InvolvedObject: *objReference, - FirstTimestamp: timeStamp, - LastTimestamp: timeStamp, - Count: 1, - Type: api.EventTypeNormal, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("events", ns, ""), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: eventList}, - } - response, err := c.Setup(t).Events(ns).List(api.ListOptions{}) - defer c.Close() - - if err != nil { - t.Errorf("%#v should be nil.", err) - } - - if len(response.Items) != 1 { - t.Errorf("%#v response.Items should have len 1.", response.Items) - } - - responseEvent := response.Items[0] - if e, r := eventList.Items[0].InvolvedObject, - responseEvent.InvolvedObject; !reflect.DeepEqual(e, r) { - t.Errorf("%#v != %#v.", e, r) - } -} - -func TestEventDelete(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "DELETE", - Path: testapi.Default.ResourcePath("events", ns, "foo"), - }, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Events(ns).Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/extensions.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/extensions.go index a95bd1b89..5db86dbb8 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/extensions.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/extensions.go @@ -20,6 +20,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/client/restclient" ) // Interface holds the experimental methods for clients of Kubernetes @@ -42,7 +43,7 @@ type ExtensionsInterface interface { // Features of Extensions group are not supported and may be changed or removed in // incompatible ways at any time. type ExtensionsClient struct { - *RESTClient + *restclient.RESTClient } func (c *ExtensionsClient) PodSecurityPolicies() PodSecurityPolicyInterface { @@ -85,12 +86,12 @@ func (c *ExtensionsClient) ReplicaSets(namespace string) ReplicaSetInterface { // provides access to experimental Kubernetes features. // Features of Extensions group are not supported and may be changed or removed in // incompatible ways at any time. -func NewExtensions(c *Config) (*ExtensionsClient, error) { +func NewExtensions(c *restclient.Config) (*ExtensionsClient, error) { config := *c if err := setExtensionsDefaults(&config); err != nil { return nil, err } - client, err := RESTClientFor(&config) + client, err := restclient.RESTClientFor(&config) if err != nil { return nil, err } @@ -101,7 +102,7 @@ func NewExtensions(c *Config) (*ExtensionsClient, error) { // panics if there is an error in the config. // Features of Extensions group are not supported and may be changed or removed in // incompatible ways at any time. -func NewExtensionsOrDie(c *Config) *ExtensionsClient { +func NewExtensionsOrDie(c *restclient.Config) *ExtensionsClient { client, err := NewExtensions(c) if err != nil { panic(err) @@ -109,7 +110,7 @@ func NewExtensionsOrDie(c *Config) *ExtensionsClient { return client } -func setExtensionsDefaults(config *Config) error { +func setExtensionsDefaults(config *restclient.Config) error { // if experimental group is not registered, return an error g, err := registered.Group(extensions.GroupName) if err != nil { @@ -117,7 +118,7 @@ func setExtensionsDefaults(config *Config) error { } config.APIPath = defaultAPIPath if config.UserAgent == "" { - config.UserAgent = DefaultKubernetesUserAgent() + config.UserAgent = restclient.DefaultKubernetesUserAgent() } // TODO: Unconditionally set the config.Version, until we fix the config. //if config.Version == "" { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/fake/fake.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/fake/fake.go deleted file mode 100644 index 3a314708f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/fake/fake.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2014 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 is made a separate package and should only be imported by tests, because -// it imports testapi -package fake - -import ( - "net/http" - "net/url" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -func CreateHTTPClient(roundTripper func(*http.Request) (*http.Response, error)) *http.Client { - return &http.Client{ - Transport: roundTripperFunc(roundTripper), - } -} - -type roundTripperFunc func(*http.Request) (*http.Response, error) - -func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return f(req) -} - -// RESTClient provides a fake RESTClient interface. -type RESTClient struct { - Client *http.Client - Codec runtime.Codec - Req *http.Request - Resp *http.Response - Err error -} - -func (c *RESTClient) Get() *unversioned.Request { - return c.request("GET") -} - -func (c *RESTClient) Put() *unversioned.Request { - return c.request("PUT") -} - -func (c *RESTClient) Patch(_ api.PatchType) *unversioned.Request { - return c.request("PATCH") -} - -func (c *RESTClient) Post() *unversioned.Request { - return c.request("POST") -} - -func (c *RESTClient) Delete() *unversioned.Request { - return c.request("DELETE") -} - -func (c *RESTClient) request(verb string) *unversioned.Request { - return unversioned.NewRequest(c, verb, &url.URL{Host: "localhost"}, "", unversioned.ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: c.Codec}, nil, nil) -} - -func (c *RESTClient) Do(req *http.Request) (*http.Response, error) { - if c.Err != nil { - return nil, c.Err - } - c.Req = req - if c.Client != nil { - return c.Client.Do(req) - } - return c.Resp, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/flags_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/flags_test.go deleted file mode 100644 index ab0f94d04..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/flags_test.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "testing" - "time" - - "k8s.io/kubernetes/pkg/util/sets" -) - -type fakeFlagSet struct { - t *testing.T - set sets.String -} - -func (f *fakeFlagSet) StringVar(p *string, name, value, usage string) { - if p == nil { - f.t.Errorf("unexpected nil pointer") - } - if usage == "" { - f.t.Errorf("unexpected empty usage") - } - f.set.Insert(name) -} - -func (f *fakeFlagSet) BoolVar(p *bool, name string, value bool, usage string) { - if p == nil { - f.t.Errorf("unexpected nil pointer") - } - if usage == "" { - f.t.Errorf("unexpected empty usage") - } - f.set.Insert(name) -} - -func (f *fakeFlagSet) UintVar(p *uint, name string, value uint, usage string) { - if p == nil { - f.t.Errorf("unexpected nil pointer") - } - if usage == "" { - f.t.Errorf("unexpected empty usage") - } - f.set.Insert(name) -} - -func (f *fakeFlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { - if p == nil { - f.t.Errorf("unexpected nil pointer") - } - if usage == "" { - f.t.Errorf("unexpected empty usage") - } - f.set.Insert(name) -} - -func (f *fakeFlagSet) IntVar(p *int, name string, value int, usage string) { - if p == nil { - f.t.Errorf("unexpected nil pointer") - } - if usage == "" { - f.t.Errorf("unexpected empty usage") - } - f.set.Insert(name) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper.go index 346b3fdc4..3ee6d6ec6 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper.go @@ -17,26 +17,17 @@ limitations under the License. package unversioned import ( - "encoding/json" "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "path" "reflect" - gruntime "runtime" - "strings" - "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/autoscaling" + "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/client/restclient" + "k8s.io/kubernetes/pkg/client/typed/discovery" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/version" ) @@ -46,112 +37,22 @@ const ( defaultAPIPath = "/apis" ) -// Config holds the common attributes that can be passed to a Kubernetes client on -// initialization. -type Config struct { - // Host must be a host string, a host:port pair, or a URL to the base of the apiserver. - // If a URL is given then the (optional) Path of that URL represents a prefix that must - // be appended to all request URIs used to access the apiserver. This allows a frontend - // proxy to easily relocate all of the apiserver endpoints. - Host string - // APIPath is a sub-path that points to an API root. - APIPath string - // Prefix is the sub path of the server. If not specified, the client will set - // a default value. Use "/" to indicate the server root should be used - Prefix string - - // ContentConfig contains settings that affect how objects are transformed when - // sent to the server. - ContentConfig - - // Server requires Basic authentication - Username string - Password string - - // Server requires Bearer authentication. This client will not attempt to use - // refresh tokens for an OAuth2 flow. - // TODO: demonstrate an OAuth2 compatible client. - BearerToken string - - // TLSClientConfig contains settings to enable transport layer security - TLSClientConfig - - // Server should be accessed without verifying the TLS - // certificate. For testing only. - Insecure bool - - // UserAgent is an optional field that specifies the caller of this request. - UserAgent string - - // Transport may be used for custom HTTP behavior. This attribute may not - // be specified with the TLS client certificate options. Use WrapTransport - // for most client level operations. - Transport http.RoundTripper - // WrapTransport will be invoked for custom HTTP behavior after the underlying - // transport is initialized (either the transport created from TLSClientConfig, - // Transport, or http.DefaultTransport). The config may layer other RoundTrippers - // 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 float32 - - // Maximum burst for throttle - Burst int -} - -// TLSClientConfig contains settings to enable transport layer security -type TLSClientConfig struct { - // Server requires TLS client certificate authentication - CertFile string - // Server requires TLS client certificate authentication - KeyFile string - // Trusted root certificates for server - CAFile string - - // CertData holds PEM-encoded bytes (typically read from a client certificate file). - // CertData takes precedence over CertFile - CertData []byte - // KeyData holds PEM-encoded bytes (typically read from a client certificate key file). - // KeyData takes precedence over KeyFile - KeyData []byte - // CAData holds PEM-encoded bytes (typically read from a root certificates bundle). - // CAData takes precedence over CAFile - CAData []byte -} - -type ContentConfig struct { - // 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, - // "application/json" is used. - ContentType string - // GroupVersion is the API version to talk to. Must be provided when initializing - // a RESTClient directly. When initializing a Client, will be set with the default - // code version. - GroupVersion *unversioned.GroupVersion - // 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. - Codec runtime.Codec -} - // New creates a Kubernetes client for the given config. This client works with pods, // replication controllers, daemons, and services. It allows operations such as list, get, update // and delete on these objects. An error is returned if the provided configuration // is not valid. -func New(c *Config) (*Client, error) { +func New(c *restclient.Config) (*Client, error) { config := *c if err := SetKubernetesDefaults(&config); err != nil { return nil, err } - client, err := RESTClientFor(&config) + client, err := restclient.RESTClientFor(&config) if err != nil { return nil, err } discoveryConfig := *c - discoveryClient, err := NewDiscoveryClientForConfig(&discoveryConfig) + discoveryClient, err := discovery.NewDiscoveryClientForConfig(&discoveryConfig) if err != nil { return nil, err } @@ -165,6 +66,15 @@ func New(c *Config) (*Client, error) { } } + var batchClient *BatchClient + if registered.IsRegistered(batch.GroupName) { + batchConfig := *c + batchClient, err = NewBatch(&batchConfig) + if err != nil { + return nil, err + } + } + var extensionsClient *ExtensionsClient if registered.IsRegistered(extensions.GroupName) { extensionsConfig := *c @@ -174,13 +84,13 @@ func New(c *Config) (*Client, error) { } } - return &Client{RESTClient: client, AutoscalingClient: autoscalingClient, ExtensionsClient: extensionsClient, DiscoveryClient: discoveryClient}, nil + return &Client{RESTClient: client, AutoscalingClient: autoscalingClient, BatchClient: batchClient, ExtensionsClient: extensionsClient, DiscoveryClient: discoveryClient}, nil } // MatchesServerVersion queries the server to compares the build version // (git hash) of the client with the server's build version. It returns an error // if it failed to contact the server or if the versions are not an exact match. -func MatchesServerVersion(client *Client, c *Config) error { +func MatchesServerVersion(client *Client, c *restclient.Config) error { var err error if client == nil { client, err = New(c) @@ -200,66 +110,6 @@ func MatchesServerVersion(client *Client, c *Config) error { return nil } -func ExtractGroupVersions(l *unversioned.APIGroupList) []string { - var groupVersions []string - for _, g := range l.Groups { - for _, gv := range g.Versions { - groupVersions = append(groupVersions, gv.GroupVersion) - } - } - return groupVersions -} - -// ServerAPIVersions returns the GroupVersions supported by the API server. -// It creates a RESTClient based on the passed in config, but it doesn't rely -// on the Version and Codec of the config, because it uses AbsPath and -// takes the raw response. -func ServerAPIVersions(c *Config) (groupVersions []string, err error) { - transport, err := TransportFor(c) - if err != nil { - return nil, err - } - client := http.Client{Transport: transport} - - configCopy := *c - configCopy.GroupVersion = nil - configCopy.APIPath = "" - baseURL, _, err := defaultServerUrlFor(&configCopy) - if err != nil { - return nil, err - } - // Get the groupVersions exposed at /api - originalPath := baseURL.Path - baseURL.Path = path.Join(originalPath, legacyAPIPath) - resp, err := client.Get(baseURL.String()) - if err != nil { - return nil, err - } - var v unversioned.APIVersions - defer resp.Body.Close() - err = json.NewDecoder(resp.Body).Decode(&v) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - - groupVersions = append(groupVersions, v.Versions...) - // Get the groupVersions exposed at /apis - baseURL.Path = path.Join(originalPath, defaultAPIPath) - resp2, err := client.Get(baseURL.String()) - if err != nil { - return nil, err - } - var apiGroupList unversioned.APIGroupList - defer resp2.Body.Close() - err = json.NewDecoder(resp2.Body).Decode(&apiGroupList) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - groupVersions = append(groupVersions, ExtractGroupVersions(&apiGroupList)...) - - return groupVersions, nil -} - // NegotiateVersion queries the server's supported api versions to find // a version that both client and server support. // - If no version is provided, try registered client versions in order of @@ -269,7 +119,7 @@ func ServerAPIVersions(c *Config) (groupVersions []string, err error) { // stderr and try client's registered versions in order of preference. // - If version is config default, and the server does not support it, // return an error. -func NegotiateVersion(client *Client, c *Config, requestedGV *unversioned.GroupVersion, clientRegisteredGVs []unversioned.GroupVersion) (*unversioned.GroupVersion, error) { +func NegotiateVersion(client *Client, c *restclient.Config, requestedGV *unversioned.GroupVersion, clientRegisteredGVs []unversioned.GroupVersion) (*unversioned.GroupVersion, error) { var err error if client == nil { client, err = New(c) @@ -287,7 +137,7 @@ func NegotiateVersion(client *Client, c *Config, requestedGV *unversioned.GroupV // not a negotiation specific error. return nil, err } - versions := ExtractGroupVersions(groups) + versions := unversioned.ExtractGroupVersions(groups) serverVersions := sets.String{} for _, v := range versions { serverVersions.Insert(v) @@ -339,7 +189,7 @@ func NegotiateVersion(client *Client, c *Config, requestedGV *unversioned.GroupV } // NewOrDie creates a Kubernetes client and panics if the provided API version is not recognized. -func NewOrDie(c *Config) *Client { +func NewOrDie(c *restclient.Config) *Client { client, err := New(c) if err != nil { panic(err) @@ -347,39 +197,9 @@ func NewOrDie(c *Config) *Client { return client } -// 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 -// 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") - if len(host) == 0 || len(port) == 0 { - return nil, fmt.Errorf("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined") - } - - token, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/" + api.ServiceAccountTokenKey) - if err != nil { - return nil, err - } - tlsClientConfig := TLSClientConfig{} - rootCAFile := "/var/run/secrets/kubernetes.io/serviceaccount/" + api.ServiceAccountRootCAKey - if _, err := util.CertPoolFromFile(rootCAFile); err != nil { - glog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err) - } else { - tlsClientConfig.CAFile = rootCAFile - } - - return &Config{ - // TODO: switch to using cluster DNS. - Host: "https://" + net.JoinHostPort(host, port), - BearerToken: string(token), - TLSClientConfig: tlsClientConfig, - }, nil -} - // NewInCluster is a shortcut for calling InClusterConfig() and then New(). func NewInCluster() (*Client, error) { - cc, err := InClusterConfig() + cc, err := restclient.InClusterConfig() if err != nil { return nil, err } @@ -389,13 +209,10 @@ func NewInCluster() (*Client, error) { // SetKubernetesDefaults sets default values on the provided client config for accessing the // Kubernetes API or returns an error if any of the defaults are impossible or invalid. // TODO: this method needs to be split into one that sets defaults per group, expected to be fix in PR "Refactoring clientcache.go and helper.go #14592" -func SetKubernetesDefaults(config *Config) error { +func SetKubernetesDefaults(config *restclient.Config) error { if config.APIPath == "" { config.APIPath = legacyAPIPath } - if len(config.UserAgent) == 0 { - config.UserAgent = DefaultKubernetesUserAgent() - } g, err := registered.Group(api.GroupName) if err != nil { return err @@ -406,233 +223,6 @@ func SetKubernetesDefaults(config *Config) error { if config.Codec == nil { config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) } - if config.QPS == 0.0 { - config.QPS = 5.0 - } - if config.Burst == 0 { - config.Burst = 10 - } - return nil -} - -// RESTClientFor returns a RESTClient that satisfies the requested attributes on a client Config -// object. Note that a RESTClient may require fields that are optional when initializing a Client. -// A RESTClient created by this method is generic - it expects to operate on an API that follows -// the Kubernetes conventions, but may not be the Kubernetes API. -func RESTClientFor(config *Config) (*RESTClient, error) { - if config.GroupVersion == nil { - return nil, fmt.Errorf("GroupVersion is required when initializing a RESTClient") - } - if config.Codec == nil { - return nil, fmt.Errorf("Codec is required when initializing a RESTClient") - } - - baseURL, versionedAPIPath, err := defaultServerUrlFor(config) - if err != nil { - return nil, err - } - - transport, err := TransportFor(config) - if err != nil { - return nil, err - } - - var httpClient *http.Client - if transport != http.DefaultTransport { - httpClient = &http.Client{Transport: transport} - } - - client := NewRESTClient(baseURL, versionedAPIPath, config.ContentConfig, config.QPS, config.Burst, httpClient) - - return client, nil -} - -// UnversionedRESTClientFor is the same as RESTClientFor, except that it allows -// the config.Version to be empty. -func UnversionedRESTClientFor(config *Config) (*RESTClient, error) { - if config.Codec == nil { - return nil, fmt.Errorf("Codec is required when initializing a RESTClient") - } - - baseURL, versionedAPIPath, err := defaultServerUrlFor(config) - if err != nil { - return nil, err - } - - transport, err := TransportFor(config) - if err != nil { - return nil, err - } - - var httpClient *http.Client - if transport != http.DefaultTransport { - httpClient = &http.Client{Transport: transport} - } - - versionConfig := config.ContentConfig - if versionConfig.GroupVersion == nil { - v := unversioned.SchemeGroupVersion - versionConfig.GroupVersion = &v - } - - client := NewRESTClient(baseURL, versionedAPIPath, versionConfig, config.QPS, config.Burst, httpClient) - return client, nil -} - -// DefaultServerURL converts a host, host:port, or URL string to the default base server API path -// to use with a Client at a given API version following the standard conventions for a -// Kubernetes API. -func DefaultServerURL(host, apiPath string, groupVersion unversioned.GroupVersion, defaultTLS bool) (*url.URL, string, error) { - if host == "" { - return nil, "", fmt.Errorf("host must be a URL or a host:port pair") - } - base := host - hostURL, err := url.Parse(base) - if err != nil { - return nil, "", err - } - if hostURL.Scheme == "" { - scheme := "http://" - if defaultTLS { - scheme = "https://" - } - hostURL, err = url.Parse(scheme + base) - if err != nil { - return nil, "", err - } - if hostURL.Path != "" && hostURL.Path != "/" { - return nil, "", fmt.Errorf("host must be a URL or a host:port pair: %q", base) - } - } - - // hostURL.Path is optional; a non-empty Path is treated as a prefix that is to be applied to - // all URIs used to access the host. this is useful when there's a proxy in front of the - // apiserver that has relocated the apiserver endpoints, forwarding all requests from, for - // example, /a/b/c to the apiserver. in this case the Path should be /a/b/c. - // - // if running without a frontend proxy (that changes the location of the apiserver), then - // hostURL.Path should be blank. - // - // versionedAPIPath, a path relative to baseURL.Path, points to a versioned API base - versionedAPIPath := path.Join("/", apiPath) - - // Add the version to the end of the path - if len(groupVersion.Group) > 0 { - versionedAPIPath = path.Join(versionedAPIPath, groupVersion.Group, groupVersion.Version) - - } else { - versionedAPIPath = path.Join(versionedAPIPath, groupVersion.Version) - - } - - return hostURL, versionedAPIPath, nil -} - -// IsConfigTransportTLS returns true if and only if the provided config will result in a protected -// connection to the server when it is passed to client.New() or client.RESTClientFor(). -// Use to determine when to send credentials over the wire. -// -// Note: the Insecure flag is ignored when testing for this value, so MITM attacks are -// still possible. -func IsConfigTransportTLS(config Config) bool { - // determination of TLS transport does not logically require a version to be specified - // modify the copy of the config we got to satisfy preconditions for defaultServerUrlFor - config.GroupVersion = defaultVersionFor(&config) - - baseURL, _, err := defaultServerUrlFor(&config) - if err != nil { - return false - } - return baseURL.Scheme == "https" -} - -// defaultServerUrlFor is shared between IsConfigTransportTLS and RESTClientFor. It -// requires Host and Version to be set prior to being called. -func defaultServerUrlFor(config *Config) (*url.URL, string, error) { - // TODO: move the default to secure when the apiserver supports TLS by default - // config.Insecure is taken to mean "I want HTTPS but don't bother checking the certs against a CA." - hasCA := len(config.CAFile) != 0 || len(config.CAData) != 0 - hasCert := len(config.CertFile) != 0 || len(config.CertData) != 0 - defaultTLS := hasCA || hasCert || config.Insecure - host := config.Host - if host == "" { - host = "localhost" - } - - if config.GroupVersion != nil { - return DefaultServerURL(host, config.APIPath, *config.GroupVersion, defaultTLS) - } - return DefaultServerURL(host, config.APIPath, unversioned.GroupVersion{}, defaultTLS) -} - -// defaultVersionFor is shared between IsConfigTransportTLS and RESTClientFor -func defaultVersionFor(config *Config) *unversioned.GroupVersion { - if config.GroupVersion == nil { - // Clients default to the preferred code API version - // TODO: implement version negotiation (highest version supported by server) - // TODO this drops out when groupmeta is refactored - copyGroupVersion := registered.GroupOrDie(api.GroupName).GroupVersion - return ©GroupVersion - } - - return config.GroupVersion -} - -// DefaultKubernetesUserAgent returns the default user agent that clients can use. -func DefaultKubernetesUserAgent() string { - commit := version.Get().GitCommit - if len(commit) > 7 { - commit = commit[:7] - } - if len(commit) == 0 { - commit = "unknown" - } - version := version.Get().GitVersion - seg := strings.SplitN(version, "-", 2) - version = seg[0] - return fmt.Sprintf("%s/%s (%s/%s) kubernetes/%s", path.Base(os.Args[0]), version, gruntime.GOOS, gruntime.GOARCH, commit) -} - -// LoadTLSFiles copies the data from the CertFile, KeyFile, and CAFile fields into the CertData, -// KeyData, and CAFile fields, or returns an error. If no error is returned, all three fields are -// either populated or were empty to start. -func LoadTLSFiles(c *Config) error { - var err error - c.CAData, err = dataFromSliceOrFile(c.CAData, c.CAFile) - if err != nil { - return err - } - - c.CertData, err = dataFromSliceOrFile(c.CertData, c.CertFile) - if err != nil { - return err - } - - c.KeyData, err = dataFromSliceOrFile(c.KeyData, c.KeyFile) - if err != nil { - return err - } - return nil -} - -// dataFromSliceOrFile returns data from the slice (if non-empty), or from the file, -// or an error if an error occurred reading the file -func dataFromSliceOrFile(data []byte, file string) ([]byte, error) { - if len(data) > 0 { - return data, nil - } - if len(file) > 0 { - fileData, err := ioutil.ReadFile(file) - if err != nil { - return []byte{}, err - } - return fileData, nil - } - return nil, nil -} - -func AddUserAgent(config *Config, userAgent string) *Config { - fullUserAgent := DefaultKubernetesUserAgent() + "/" + userAgent - config.UserAgent = fullUserAgent - return config + + return restclient.SetKubernetesDefaults(config) } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper_blackbox_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper_blackbox_test.go deleted file mode 100644 index 5d497d503..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper_blackbox_test.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - "bytes" - "encoding/json" - "errors" - "io" - "io/ioutil" - "net/http" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/testapi" - uapi "k8s.io/kubernetes/pkg/api/unversioned" - unversionedapi "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func objBody(object interface{}) io.ReadCloser { - output, err := json.MarshalIndent(object, "", "") - if err != nil { - panic(err) - } - return ioutil.NopCloser(bytes.NewReader([]byte(output))) -} - -func TestNegotiateVersion(t *testing.T) { - tests := []struct { - name string - version *uapi.GroupVersion - expectedVersion *uapi.GroupVersion - serverVersions []string - clientVersions []uapi.GroupVersion - config *unversioned.Config - expectErr func(err error) bool - sendErr error - }{ - { - name: "server supports client default", - version: &uapi.GroupVersion{Version: "version1"}, - config: &unversioned.Config{}, - serverVersions: []string{"version1", testapi.Default.GroupVersion().String()}, - clientVersions: []uapi.GroupVersion{{Version: "version1"}, *testapi.Default.GroupVersion()}, - expectedVersion: &uapi.GroupVersion{Version: "version1"}, - }, - { - name: "server falls back to client supported", - version: testapi.Default.GroupVersion(), - config: &unversioned.Config{}, - serverVersions: []string{"version1"}, - clientVersions: []uapi.GroupVersion{{Version: "version1"}, *testapi.Default.GroupVersion()}, - expectedVersion: &uapi.GroupVersion{Version: "version1"}, - }, - { - name: "explicit version supported", - config: &unversioned.Config{ContentConfig: unversioned.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}, - serverVersions: []string{"/version1", testapi.Default.GroupVersion().String()}, - clientVersions: []uapi.GroupVersion{{Version: "version1"}, *testapi.Default.GroupVersion()}, - expectedVersion: testapi.Default.GroupVersion(), - }, - { - name: "explicit version not supported", - config: &unversioned.Config{ContentConfig: unversioned.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}, - serverVersions: []string{"version1"}, - clientVersions: []uapi.GroupVersion{{Version: "version1"}, *testapi.Default.GroupVersion()}, - expectErr: func(err error) bool { return strings.Contains(err.Error(), `server does not support API version "v1"`) }, - }, - { - name: "connection refused error", - config: &unversioned.Config{ContentConfig: unversioned.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}, - serverVersions: []string{"version1"}, - clientVersions: []uapi.GroupVersion{{Version: "version1"}, *testapi.Default.GroupVersion()}, - sendErr: errors.New("connection refused"), - expectErr: func(err error) bool { return strings.Contains(err.Error(), "connection refused") }, - }, - } - codec := testapi.Default.Codec() - - for _, test := range tests { - fakeClient := &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{ - StatusCode: 200, - Body: objBody(&unversionedapi.APIVersions{Versions: test.serverVersions}), - }, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - if test.sendErr != nil { - return nil, test.sendErr - } - return &http.Response{StatusCode: 200, Body: objBody(&unversionedapi.APIVersions{Versions: test.serverVersions})}, nil - }), - } - c := unversioned.NewOrDie(test.config) - c.DiscoveryClient.Client = fakeClient.Client - response, err := unversioned.NegotiateVersion(c, test.config, test.version, test.clientVersions) - if err == nil && test.expectErr != nil { - t.Errorf("expected error, got nil for [%s].", test.name) - } - if err != nil { - if test.expectErr == nil || !test.expectErr(err) { - t.Errorf("unexpected error for [%s]: %v.", test.name, err) - } - continue - } - if *response != *test.expectedVersion { - t.Errorf("%s: expected version %s, got %s.", test.name, test.expectedVersion, response) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper_test.go deleted file mode 100644 index 2d565afc2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/helper_test.go +++ /dev/null @@ -1,280 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "path" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestIsConfigTransportTLS(t *testing.T) { - testCases := []struct { - Config *Config - TransportTLS bool - }{ - { - Config: &Config{}, - TransportTLS: false, - }, - { - Config: &Config{ - Host: "https://localhost", - }, - TransportTLS: true, - }, - { - Config: &Config{ - Host: "localhost", - TLSClientConfig: TLSClientConfig{ - CertFile: "foo", - }, - }, - TransportTLS: true, - }, - { - Config: &Config{ - Host: "///:://localhost", - TLSClientConfig: TLSClientConfig{ - CertFile: "foo", - }, - }, - TransportTLS: false, - }, - { - Config: &Config{ - Host: "1.2.3.4:567", - Insecure: true, - }, - TransportTLS: true, - }, - } - for _, testCase := range testCases { - if err := SetKubernetesDefaults(testCase.Config); err != nil { - t.Errorf("setting defaults failed for %#v: %v", testCase.Config, err) - continue - } - useTLS := IsConfigTransportTLS(*testCase.Config) - if testCase.TransportTLS != useTLS { - t.Errorf("expected %v for %#v", testCase.TransportTLS, testCase.Config) - } - } -} - -func TestSetKubernetesDefaults(t *testing.T) { - testCases := []struct { - Config Config - After Config - Err bool - }{ - { - Config{}, - Config{ - APIPath: "/api", - ContentConfig: ContentConfig{ - GroupVersion: testapi.Default.GroupVersion(), - Codec: testapi.Default.Codec(), - }, - QPS: 5, - Burst: 10, - }, - false, - }, - // Add this test back when we fixed config and SetKubernetesDefaults - // { - // Config{ - // GroupVersion: &unversioned.GroupVersion{Group: "not.a.group", Version: "not_an_api"}, - // }, - // Config{}, - // true, - // }, - } - for _, testCase := range testCases { - val := &testCase.Config - err := SetKubernetesDefaults(val) - val.UserAgent = "" - switch { - case err == nil && testCase.Err: - t.Errorf("expected error but was nil") - continue - case err != nil && !testCase.Err: - t.Errorf("unexpected error %v", err) - continue - case err != nil: - continue - } - if !reflect.DeepEqual(*val, testCase.After) { - t.Errorf("unexpected result object: %#v", val) - } - } -} - -func TestSetKubernetesDefaultsUserAgent(t *testing.T) { - config := &Config{} - if err := SetKubernetesDefaults(config); err != nil { - t.Errorf("unexpected error: %v", err) - } - if !strings.Contains(config.UserAgent, "kubernetes/") { - t.Errorf("no user agent set: %#v", config) - } -} - -func TestHelperGetServerAPIVersions(t *testing.T) { - expect := []string{"v1", "v2", "v3"} - APIVersions := unversioned.APIVersions{Versions: expect} - expect = append(expect, "group1/v1", "group1/v2", "group2/v1", "group2/v2") - APIGroupList := unversioned.APIGroupList{ - Groups: []unversioned.APIGroup{ - { - Versions: []unversioned.GroupVersionForDiscovery{ - { - GroupVersion: "group1/v1", - }, - { - GroupVersion: "group1/v2", - }, - }, - }, - { - Versions: []unversioned.GroupVersionForDiscovery{ - { - GroupVersion: "group2/v1", - }, - { - GroupVersion: "group2/v2", - }, - }, - }, - }, - } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var output []byte - var err error - switch req.URL.Path { - case "/api": - output, err = json.Marshal(APIVersions) - - case "/apis": - output, err = json.Marshal(APIGroupList) - } - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - got, err := ServerAPIVersions(&Config{Host: server.URL, ContentConfig: ContentConfig{GroupVersion: &unversioned.GroupVersion{Group: "invalid version", Version: "one"}, Codec: testapi.Default.Codec()}}) - if err != nil { - t.Fatalf("unexpected encoding error: %v", err) - } - if e, a := expect, got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestSetsCodec(t *testing.T) { - testCases := map[string]struct { - Err bool - Prefix string - Codec runtime.Codec - }{ - testapi.Default.GroupVersion().Version: {false, "/api/" + testapi.Default.GroupVersion().Version, testapi.Default.Codec()}, - // Add this test back when we fixed config and SetKubernetesDefaults - // "invalidVersion": {true, "", nil}, - } - for version, expected := range testCases { - client, err := New(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: version}}}) - switch { - case err == nil && expected.Err: - t.Errorf("expected error but was nil") - continue - case err != nil && !expected.Err: - t.Errorf("unexpected error %v", err) - continue - case err != nil: - continue - } - if e, a := expected.Prefix, client.RESTClient.versionedAPIPath; e != a { - t.Errorf("expected %#v, got %#v", e, a) - } - if e, a := expected.Codec, client.RESTClient.contentConfig.Codec; !reflect.DeepEqual(e, a) { - t.Errorf("expected %#v, got %#v", e, a) - } - } -} - -func TestRESTClientRequires(t *testing.T) { - if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{Codec: testapi.Default.Codec()}}); err == nil { - t.Errorf("unexpected non-error") - } - if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}); err == nil { - t.Errorf("unexpected non-error") - } - if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec()}}); err != nil { - t.Errorf("unexpected error: %v", err) - } -} - -func TestValidatesHostParameter(t *testing.T) { - testCases := []struct { - Host string - APIPath string - - URL string - Err bool - }{ - {"127.0.0.1", "", "http://127.0.0.1/" + testapi.Default.GroupVersion().Version, false}, - {"127.0.0.1:8080", "", "http://127.0.0.1:8080/" + testapi.Default.GroupVersion().Version, false}, - {"foo.bar.com", "", "http://foo.bar.com/" + testapi.Default.GroupVersion().Version, false}, - {"http://host/prefix", "", "http://host/prefix/" + testapi.Default.GroupVersion().Version, false}, - {"http://host", "", "http://host/" + testapi.Default.GroupVersion().Version, false}, - {"http://host", "/", "http://host/" + testapi.Default.GroupVersion().Version, false}, - {"http://host", "/other", "http://host/other/" + testapi.Default.GroupVersion().Version, false}, - {"host/server", "", "", true}, - } - for i, testCase := range testCases { - u, versionedAPIPath, err := DefaultServerURL(testCase.Host, testCase.APIPath, *testapi.Default.GroupVersion(), false) - switch { - case err == nil && testCase.Err: - t.Errorf("expected error but was nil") - continue - case err != nil && !testCase.Err: - t.Errorf("unexpected error %v", err) - continue - case err != nil: - continue - } - u.Path = path.Join(u.Path, versionedAPIPath) - if e, a := testCase.URL, u.String(); e != a { - t.Errorf("%d: expected host %s, got %s", i, e, a) - continue - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/horizontalpodautoscaler_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/horizontalpodautoscaler_test.go deleted file mode 100644 index b35d258af..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/horizontalpodautoscaler_test.go +++ /dev/null @@ -1,225 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/autoscaling" - "k8s.io/kubernetes/pkg/apis/extensions" -) - -func getHorizontalPodAutoscalersResoureName() string { - return "horizontalpodautoscalers" -} - -func getClient(t *testing.T, c *simple.Client, ns, resourceGroup string) HorizontalPodAutoscalerInterface { - switch resourceGroup { - case autoscaling.GroupName: - return c.Setup(t).Autoscaling().HorizontalPodAutoscalers(ns) - case extensions.GroupName: - return c.Setup(t).Extensions().HorizontalPodAutoscalers(ns) - default: - t.Fatalf("Unknown group %v", resourceGroup) - } - return nil -} - -func testHorizontalPodAutoscalerCreate(t *testing.T, group testapi.TestGroup, resourceGroup string) { - ns := api.NamespaceDefault - horizontalPodAutoscaler := extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: group.ResourcePath(getHorizontalPodAutoscalersResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: &horizontalPodAutoscaler, - }, - Response: simple.Response{StatusCode: 200, Body: &horizontalPodAutoscaler}, - ResourceGroup: resourceGroup, - } - - response, err := getClient(t, c, ns, resourceGroup).Create(&horizontalPodAutoscaler) - defer c.Close() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - c.Validate(t, response, err) -} - -func TestHorizontalPodAutoscalerCreate(t *testing.T) { - testHorizontalPodAutoscalerCreate(t, testapi.Extensions, extensions.GroupName) - testHorizontalPodAutoscalerCreate(t, testapi.Autoscaling, autoscaling.GroupName) -} - -func testHorizontalPodAutoscalerGet(t *testing.T, group testapi.TestGroup, resourceGroup string) { - ns := api.NamespaceDefault - horizontalPodAutoscaler := &extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: group.ResourcePath(getHorizontalPodAutoscalersResoureName(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: horizontalPodAutoscaler}, - ResourceGroup: resourceGroup, - } - - response, err := getClient(t, c, ns, resourceGroup).Get("abc") - defer c.Close() - c.Validate(t, response, err) -} - -func TestHorizontalPodAutoscalerGet(t *testing.T) { - testHorizontalPodAutoscalerGet(t, testapi.Extensions, extensions.GroupName) - testHorizontalPodAutoscalerGet(t, testapi.Autoscaling, autoscaling.GroupName) -} - -func testHorizontalPodAutoscalerList(t *testing.T, group testapi.TestGroup, resourceGroup string) { - ns := api.NamespaceDefault - horizontalPodAutoscalerList := &extensions.HorizontalPodAutoscalerList{ - Items: []extensions.HorizontalPodAutoscaler{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: group.ResourcePath(getHorizontalPodAutoscalersResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: horizontalPodAutoscalerList}, - ResourceGroup: resourceGroup, - } - response, err := getClient(t, c, ns, resourceGroup).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestHorizontalPodAutoscalerList(t *testing.T) { - testHorizontalPodAutoscalerList(t, testapi.Extensions, extensions.GroupName) - testHorizontalPodAutoscalerList(t, testapi.Autoscaling, autoscaling.GroupName) -} - -func testHorizontalPodAutoscalerUpdate(t *testing.T, group testapi.TestGroup, resourceGroup string) { - ns := api.NamespaceDefault - horizontalPodAutoscaler := &extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: group.ResourcePath(getHorizontalPodAutoscalersResoureName(), ns, "abc"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: horizontalPodAutoscaler}, - ResourceGroup: resourceGroup, - } - response, err := getClient(t, c, ns, resourceGroup).Update(horizontalPodAutoscaler) - defer c.Close() - c.Validate(t, response, err) -} - -func TestHorizontalPodAutoscalerUpdate(t *testing.T) { - testHorizontalPodAutoscalerUpdate(t, testapi.Extensions, extensions.GroupName) - testHorizontalPodAutoscalerUpdate(t, testapi.Autoscaling, autoscaling.GroupName) -} - -func testHorizontalPodAutoscalerUpdateStatus(t *testing.T, group testapi.TestGroup, resourceGroup string) { - ns := api.NamespaceDefault - horizontalPodAutoscaler := &extensions.HorizontalPodAutoscaler{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: group.ResourcePath(getHorizontalPodAutoscalersResoureName(), ns, "abc") + "/status", Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: horizontalPodAutoscaler}, - ResourceGroup: resourceGroup, - } - response, err := getClient(t, c, ns, resourceGroup).UpdateStatus(horizontalPodAutoscaler) - defer c.Close() - c.Validate(t, response, err) -} - -func TestHorizontalPodAutoscalerUpdateStatus(t *testing.T) { - testHorizontalPodAutoscalerUpdateStatus(t, testapi.Extensions, extensions.GroupName) - testHorizontalPodAutoscalerUpdateStatus(t, testapi.Autoscaling, autoscaling.GroupName) -} - -func testHorizontalPodAutoscalerDelete(t *testing.T, group testapi.TestGroup, resourceGroup string) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: group.ResourcePath(getHorizontalPodAutoscalersResoureName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - ResourceGroup: resourceGroup, - } - err := getClient(t, c, ns, resourceGroup).Delete("foo", nil) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestHorizontalPodAutoscalerDelete(t *testing.T) { - testHorizontalPodAutoscalerDelete(t, testapi.Extensions, extensions.GroupName) - testHorizontalPodAutoscalerDelete(t, testapi.Autoscaling, autoscaling.GroupName) -} - -func testHorizontalPodAutoscalerWatch(t *testing.T, group testapi.TestGroup, resourceGroup string) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: group.ResourcePathWithPrefix("watch", getHorizontalPodAutoscalersResoureName(), "", ""), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - ResourceGroup: resourceGroup, - } - _, err := getClient(t, c, api.NamespaceAll, resourceGroup).Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestHorizontalPodAutoscalerWatch(t *testing.T) { - testHorizontalPodAutoscalerWatch(t, testapi.Extensions, extensions.GroupName) - testHorizontalPodAutoscalerWatch(t, testapi.Autoscaling, autoscaling.GroupName) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go index a86afb6dd..c2d7fde2f 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go @@ -24,6 +24,7 @@ import ( "k8s.io/kubernetes/pkg/apimachinery/registered" _ "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/componentconfig/install" _ "k8s.io/kubernetes/pkg/apis/extensions/install" _ "k8s.io/kubernetes/pkg/apis/metrics/install" diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/ingress_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/ingress_test.go deleted file mode 100644 index 6bab5f5ed..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/ingress_test.go +++ /dev/null @@ -1,240 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/extensions" -) - -func getIngressResourceName() string { - return "ingresses" -} - -func TestListIngress(t *testing.T) { - ns := api.NamespaceAll - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getIngressResourceName(), ns, ""), - }, - Response: simple.Response{StatusCode: 200, - Body: &extensions.IngressList{ - Items: []extensions.Ingress{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.IngressSpec{ - Rules: []extensions.IngressRule{}, - }, - }, - }, - }, - }, - } - receivedIngressList, err := c.Setup(t).Extensions().Ingress(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, receivedIngressList, err) -} - -func TestGetIngress(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getIngressResourceName(), ns, "foo"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.IngressSpec{ - Rules: []extensions.IngressRule{}, - }, - }, - }, - } - receivedIngress, err := c.Setup(t).Extensions().Ingress(ns).Get("foo") - defer c.Close() - c.Validate(t, receivedIngress, err) -} - -func TestGetIngressWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedIngress, err := c.Setup(t).Extensions().Ingress(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedIngress, err) -} - -func TestUpdateIngress(t *testing.T) { - ns := api.NamespaceDefault - requestIngress := &extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Extensions.ResourcePath(getIngressResourceName(), ns, "foo"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.IngressSpec{ - Rules: []extensions.IngressRule{}, - }, - }, - }, - } - receivedIngress, err := c.Setup(t).Extensions().Ingress(ns).Update(requestIngress) - defer c.Close() - c.Validate(t, receivedIngress, err) -} - -func TestUpdateIngressStatus(t *testing.T) { - ns := api.NamespaceDefault - lbStatus := api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - {IP: "127.0.0.1"}, - }, - } - requestIngress := &extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - ResourceVersion: "1", - }, - Status: extensions.IngressStatus{ - LoadBalancer: lbStatus, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Extensions.ResourcePath(getIngressResourceName(), ns, "foo") + "/status", - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.IngressSpec{ - Rules: []extensions.IngressRule{}, - }, - Status: extensions.IngressStatus{ - LoadBalancer: lbStatus, - }, - }, - }, - } - receivedIngress, err := c.Setup(t).Extensions().Ingress(ns).UpdateStatus(requestIngress) - defer c.Close() - c.Validate(t, receivedIngress, err) -} - -func TestDeleteIngress(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "DELETE", - Path: testapi.Extensions.ResourcePath(getIngressResourceName(), ns, "foo"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Extensions().Ingress(ns).Delete("foo", nil) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestCreateIngress(t *testing.T) { - ns := api.NamespaceDefault - requestIngress := &extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Extensions.ResourcePath(getIngressResourceName(), ns, ""), - Body: requestIngress, - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.IngressSpec{ - Rules: []extensions.IngressRule{}, - }, - }, - }, - } - receivedIngress, err := c.Setup(t).Extensions().Ingress(ns).Create(requestIngress) - defer c.Close() - c.Validate(t, receivedIngress, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/jobs.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/jobs.go index 0d10997c7..f965a0874 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/jobs.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/jobs.go @@ -101,3 +101,67 @@ func (c *jobs) UpdateStatus(job *extensions.Job) (result *extensions.Job, err er err = c.r.Put().Namespace(c.ns).Resource("jobs").Name(job.Name).SubResource("status").Body(job).Do().Into(result) return } + +// jobsV1 implements JobsNamespacer interface using BatchClient internally +type jobsV1 struct { + r *BatchClient + ns string +} + +// newJobsV1 returns a jobsV1 +func newJobsV1(c *BatchClient, namespace string) *jobsV1 { + return &jobsV1{c, namespace} +} + +// Ensure statically that jobsV1 implements JobInterface. +var _ JobInterface = &jobsV1{} + +// List returns a list of jobs that match the label and field selectors. +func (c *jobsV1) List(opts api.ListOptions) (result *extensions.JobList, err error) { + result = &extensions.JobList{} + err = c.r.Get().Namespace(c.ns).Resource("jobs").VersionedParams(&opts, api.ParameterCodec).Do().Into(result) + return +} + +// Get returns information about a particular job. +func (c *jobsV1) Get(name string) (result *extensions.Job, err error) { + result = &extensions.Job{} + err = c.r.Get().Namespace(c.ns).Resource("jobs").Name(name).Do().Into(result) + return +} + +// Create creates a new job. +func (c *jobsV1) Create(job *extensions.Job) (result *extensions.Job, err error) { + result = &extensions.Job{} + err = c.r.Post().Namespace(c.ns).Resource("jobs").Body(job).Do().Into(result) + return +} + +// Update updates an existing job. +func (c *jobsV1) Update(job *extensions.Job) (result *extensions.Job, err error) { + result = &extensions.Job{} + err = c.r.Put().Namespace(c.ns).Resource("jobs").Name(job.Name).Body(job).Do().Into(result) + return +} + +// Delete deletes a job, returns error if one occurs. +func (c *jobsV1) Delete(name string, options *api.DeleteOptions) (err error) { + return c.r.Delete().Namespace(c.ns).Resource("jobs").Name(name).Body(options).Do().Error() +} + +// Watch returns a watch.Interface that watches the requested jobs. +func (c *jobsV1) Watch(opts api.ListOptions) (watch.Interface, error) { + return c.r.Get(). + Prefix("watch"). + Namespace(c.ns). + Resource("jobs"). + VersionedParams(&opts, api.ParameterCodec). + Watch() +} + +// UpdateStatus takes the name of the job and the new status. Returns the server's representation of the job, and an error, if it occurs. +func (c *jobsV1) UpdateStatus(job *extensions.Job) (result *extensions.Job, err error) { + result = &extensions.Job{} + err = c.r.Put().Namespace(c.ns).Resource("jobs").Name(job.Name).SubResource("status").Body(job).Do().Into(result) + return +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/jobs_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/jobs_test.go deleted file mode 100644 index 76a87eab0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/jobs_test.go +++ /dev/null @@ -1,232 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/extensions" -) - -func getJobResourceName() string { - return "jobs" -} - -func TestListJobs(t *testing.T) { - ns := api.NamespaceAll - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getJobResourceName(), ns, ""), - }, - Response: simple.Response{StatusCode: 200, - Body: &extensions.JobList{ - Items: []extensions.Job{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.JobSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - }, - }, - } - receivedJobList, err := c.Setup(t).Extensions().Jobs(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, receivedJobList, err) -} - -func TestGetJob(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getJobResourceName(), ns, "foo"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.JobSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - } - receivedJob, err := c.Setup(t).Extensions().Jobs(ns).Get("foo") - defer c.Close() - c.Validate(t, receivedJob, err) -} - -func TestGetJobWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedJob, err := c.Setup(t).Extensions().Jobs(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedJob, err) -} - -func TestUpdateJob(t *testing.T) { - ns := api.NamespaceDefault - requestJob := &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Extensions.ResourcePath(getJobResourceName(), ns, "foo"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.JobSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - } - receivedJob, err := c.Setup(t).Extensions().Jobs(ns).Update(requestJob) - defer c.Close() - c.Validate(t, receivedJob, err) -} - -func TestUpdateJobStatus(t *testing.T) { - ns := api.NamespaceDefault - requestJob := &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Extensions.ResourcePath(getJobResourceName(), ns, "foo") + "/status", - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.JobSpec{ - Template: api.PodTemplateSpec{}, - }, - Status: extensions.JobStatus{ - Active: 1, - }, - }, - }, - } - receivedJob, err := c.Setup(t).Extensions().Jobs(ns).UpdateStatus(requestJob) - defer c.Close() - c.Validate(t, receivedJob, err) -} - -func TestDeleteJob(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "DELETE", - Path: testapi.Extensions.ResourcePath(getJobResourceName(), ns, "foo"), - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Extensions().Jobs(ns).Delete("foo", nil) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestCreateJob(t *testing.T) { - ns := api.NamespaceDefault - requestJob := &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Extensions.ResourcePath(getJobResourceName(), ns, ""), - Body: requestJob, - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.JobSpec{ - Template: api.PodTemplateSpec{}, - }, - }, - }, - } - receivedJob, err := c.Setup(t).Extensions().Jobs(ns).Create(requestJob) - defer c.Close() - c.Validate(t, receivedJob, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/limit_ranges_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/limit_ranges_test.go deleted file mode 100644 index f6936570c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/limit_ranges_test.go +++ /dev/null @@ -1,189 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func getLimitRangesResourceName() string { - return "limitranges" -} - -func TestLimitRangeCreate(t *testing.T) { - ns := api.NamespaceDefault - limitRange := &api.LimitRange{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - }, - Min: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), - api.ResourceMemory: resource.MustParse("100"), - }, - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath(getLimitRangesResourceName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: limitRange, - }, - Response: simple.Response{StatusCode: 200, Body: limitRange}, - } - - response, err := c.Setup(t).LimitRanges(ns).Create(limitRange) - defer c.Close() - c.Validate(t, response, err) -} - -func TestLimitRangeGet(t *testing.T) { - ns := api.NamespaceDefault - limitRange := &api.LimitRange{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - }, - Min: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), - api.ResourceMemory: resource.MustParse("100"), - }, - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getLimitRangesResourceName(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: limitRange}, - } - - response, err := c.Setup(t).LimitRanges(ns).Get("abc") - defer c.Close() - c.Validate(t, response, err) -} - -func TestLimitRangeList(t *testing.T) { - ns := api.NamespaceDefault - - limitRangeList := &api.LimitRangeList{ - Items: []api.LimitRange{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getLimitRangesResourceName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: limitRangeList}, - } - response, err := c.Setup(t).LimitRanges(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestLimitRangeUpdate(t *testing.T) { - ns := api.NamespaceDefault - limitRange := &api.LimitRange{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - ResourceVersion: "1", - }, - Spec: api.LimitRangeSpec{ - Limits: []api.LimitRangeItem{ - { - Type: api.LimitTypePod, - Max: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - }, - Min: api.ResourceList{ - api.ResourceCPU: resource.MustParse("0"), - api.ResourceMemory: resource.MustParse("100"), - }, - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath(getLimitRangesResourceName(), ns, "abc"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: limitRange}, - } - response, err := c.Setup(t).LimitRanges(ns).Update(limitRange) - defer c.Close() - c.Validate(t, response, err) -} - -func TestLimitRangeDelete(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath(getLimitRangesResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).LimitRanges(ns).Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestLimitRangeWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePathWithPrefix("watch", getLimitRangesResourceName(), "", ""), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).LimitRanges(api.NamespaceAll).Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/namespaces_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/namespaces_test.go deleted file mode 100644 index 509980e7e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/namespaces_test.go +++ /dev/null @@ -1,189 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func TestNamespaceCreate(t *testing.T) { - // we create a namespace relative to another namespace - namespace := &api.Namespace{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath("namespaces", "", ""), - Body: namespace, - }, - Response: simple.Response{StatusCode: 200, Body: namespace}, - } - - // from the source ns, provision a new global namespace "foo" - response, err := c.Setup(t).Namespaces().Create(namespace) - defer c.Close() - - if err != nil { - t.Errorf("%#v should be nil.", err) - } - - if e, a := response.Name, namespace.Name; e != a { - t.Errorf("%#v != %#v.", e, a) - } -} - -func TestNamespaceGet(t *testing.T) { - namespace := &api.Namespace{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("namespaces", "", "foo"), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: namespace}, - } - - response, err := c.Setup(t).Namespaces().Get("foo") - defer c.Close() - - if err != nil { - t.Errorf("%#v should be nil.", err) - } - - if e, r := response.Name, namespace.Name; e != r { - t.Errorf("%#v != %#v.", e, r) - } -} - -func TestNamespaceList(t *testing.T) { - namespaceList := &api.NamespaceList{ - Items: []api.Namespace{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("namespaces", "", ""), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: namespaceList}, - } - response, err := c.Setup(t).Namespaces().List(api.ListOptions{}) - defer c.Close() - - if err != nil { - t.Errorf("%#v should be nil.", err) - } - - if len(response.Items) != 1 { - t.Errorf("%#v response.Items should have len 1.", response.Items) - } - - responseNamespace := response.Items[0] - if e, r := responseNamespace.Name, "foo"; e != r { - t.Errorf("%#v != %#v.", e, r) - } -} - -func TestNamespaceUpdate(t *testing.T) { - requestNamespace := &api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - ResourceVersion: "1", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{api.FinalizerKubernetes}, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Default.ResourcePath("namespaces", "", "foo")}, - Response: simple.Response{StatusCode: 200, Body: requestNamespace}, - } - receivedNamespace, err := c.Setup(t).Namespaces().Update(requestNamespace) - defer c.Close() - c.Validate(t, receivedNamespace, err) -} - -func TestNamespaceFinalize(t *testing.T) { - requestNamespace := &api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - ResourceVersion: "1", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.NamespaceSpec{ - Finalizers: []api.FinalizerName{api.FinalizerKubernetes}, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Default.ResourcePath("namespaces", "", "foo") + "/finalize", - }, - Response: simple.Response{StatusCode: 200, Body: requestNamespace}, - } - receivedNamespace, err := c.Setup(t).Namespaces().Finalize(requestNamespace) - defer c.Close() - c.Validate(t, receivedNamespace, err) -} - -func TestNamespaceDelete(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath("namespaces", "", "foo")}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Namespaces().Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestNamespaceWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePathWithPrefix("watch", "namespaces", "", ""), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).Namespaces().Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/nodes_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/nodes_test.go deleted file mode 100644 index 37735ec7d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/nodes_test.go +++ /dev/null @@ -1,177 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/labels" -) - -func getNodesResourceName() string { - return "nodes" -} - -func TestListNodes(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getNodesResourceName(), "", ""), - }, - Response: simple.Response{StatusCode: 200, Body: &api.NodeList{ListMeta: unversioned.ListMeta{ResourceVersion: "1"}}}, - } - response, err := c.Setup(t).Nodes().List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestListNodesLabels(t *testing.T) { - labelSelectorQueryParamName := unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getNodesResourceName(), "", ""), - Query: simple.BuildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})}, - Response: simple.Response{ - StatusCode: 200, - Body: &api.NodeList{ - Items: []api.Node{ - { - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - }, - }, - }, - }, - } - c.Setup(t) - defer c.Close() - c.QueryValidator[labelSelectorQueryParamName] = simple.ValidateLabels - selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector() - options := api.ListOptions{LabelSelector: selector} - receivedNodeList, err := c.Nodes().List(options) - c.Validate(t, receivedNodeList, err) -} - -func TestGetNode(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getNodesResourceName(), "", "1"), - }, - Response: simple.Response{StatusCode: 200, Body: &api.Node{ObjectMeta: api.ObjectMeta{Name: "node-1"}}}, - } - response, err := c.Setup(t).Nodes().Get("1") - defer c.Close() - c.Validate(t, response, err) -} - -func TestGetNodeWithNoName(t *testing.T) { - c := &simple.Client{Error: true} - receivedNode, err := c.Setup(t).Nodes().Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedNode, err) -} - -func TestCreateNode(t *testing.T) { - requestNode := &api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "node-1", - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: resource.MustParse("1000m"), - api.ResourceMemory: resource.MustParse("1Mi"), - }, - }, - Spec: api.NodeSpec{ - Unschedulable: false, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath(getNodesResourceName(), "", ""), - Body: requestNode}, - Response: simple.Response{ - StatusCode: 200, - Body: requestNode, - }, - } - receivedNode, err := c.Setup(t).Nodes().Create(requestNode) - defer c.Close() - c.Validate(t, receivedNode, err) -} - -func TestDeleteNode(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "DELETE", - Path: testapi.Default.ResourcePath(getNodesResourceName(), "", "foo"), - }, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Nodes().Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestUpdateNode(t *testing.T) { - requestNode := &api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - ResourceVersion: "1", - }, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: resource.MustParse("1000m"), - api.ResourceMemory: resource.MustParse("1Mi"), - }, - }, - Spec: api.NodeSpec{ - Unschedulable: true, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Default.ResourcePath(getNodesResourceName(), "", "foo"), - }, - Response: simple.Response{StatusCode: 200, Body: requestNode}, - } - response, err := c.Setup(t).Nodes().Update(requestNode) - defer c.Close() - c.Validate(t, response, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/persistentvolume_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/persistentvolume_test.go deleted file mode 100644 index 329539a83..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/persistentvolume_test.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func getPersistentVolumesResoureName() string { - return "persistentvolumes" -} - -func TestPersistentVolumeCreate(t *testing.T) { - pv := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }, - } - - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath(getPersistentVolumesResoureName(), "", ""), - Query: simple.BuildQueryValues(nil), - Body: pv, - }, - Response: simple.Response{StatusCode: 200, Body: pv}, - } - - response, err := c.Setup(t).PersistentVolumes().Create(pv) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeGet(t *testing.T) { - persistentVolume := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getPersistentVolumesResoureName(), "", "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: persistentVolume}, - } - - response, err := c.Setup(t).PersistentVolumes().Get("abc") - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeList(t *testing.T) { - persistentVolumeList := &api.PersistentVolumeList{ - Items: []api.PersistentVolume{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getPersistentVolumesResoureName(), "", ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: persistentVolumeList}, - } - response, err := c.Setup(t).PersistentVolumes().List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeUpdate(t *testing.T) { - persistentVolume := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - ResourceVersion: "1", - }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath(getPersistentVolumesResoureName(), "", "abc"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: persistentVolume}, - } - response, err := c.Setup(t).PersistentVolumes().Update(persistentVolume) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeStatusUpdate(t *testing.T) { - persistentVolume := &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - ResourceVersion: "1", - }, - Spec: api.PersistentVolumeSpec{ - Capacity: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{Path: "/foo"}, - }, - }, - Status: api.PersistentVolumeStatus{ - Phase: api.VolumeBound, - Message: "foo", - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Default.ResourcePath(getPersistentVolumesResoureName(), "", "abc") + "/status", - Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: persistentVolume}, - } - response, err := c.Setup(t).PersistentVolumes().UpdateStatus(persistentVolume) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeDelete(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath(getPersistentVolumesResoureName(), "", "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).PersistentVolumes().Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestPersistentVolumeWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePathWithPrefix("watch", getPersistentVolumesResoureName(), "", ""), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).PersistentVolumes().Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumeclaim_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumeclaim_test.go deleted file mode 100644 index 837b72a9c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumeclaim_test.go +++ /dev/null @@ -1,212 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func getPersistentVolumeClaimsResoureName() string { - return "persistentvolumeclaims" -} - -func TestPersistentVolumeClaimCreate(t *testing.T) { - ns := api.NamespaceDefault - pv := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }, - } - - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath(getPersistentVolumeClaimsResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: pv, - }, - Response: simple.Response{StatusCode: 200, Body: pv}, - } - - response, err := c.Setup(t).PersistentVolumeClaims(ns).Create(pv) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeClaimGet(t *testing.T) { - ns := api.NamespaceDefault - persistentVolumeClaim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getPersistentVolumeClaimsResoureName(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: persistentVolumeClaim}, - } - - response, err := c.Setup(t).PersistentVolumeClaims(ns).Get("abc") - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeClaimList(t *testing.T) { - ns := api.NamespaceDefault - persistentVolumeList := &api.PersistentVolumeClaimList{ - Items: []api.PersistentVolumeClaim{ - { - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "ns"}, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getPersistentVolumeClaimsResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: persistentVolumeList}, - } - response, err := c.Setup(t).PersistentVolumeClaims(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeClaimUpdate(t *testing.T) { - ns := api.NamespaceDefault - persistentVolumeClaim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - ResourceVersion: "1", - }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath(getPersistentVolumeClaimsResoureName(), ns, "abc"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: persistentVolumeClaim}, - } - response, err := c.Setup(t).PersistentVolumeClaims(ns).Update(persistentVolumeClaim) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeClaimStatusUpdate(t *testing.T) { - ns := api.NamespaceDefault - persistentVolumeClaim := &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - ResourceVersion: "1", - }, - Spec: api.PersistentVolumeClaimSpec{ - AccessModes: []api.PersistentVolumeAccessMode{ - api.ReadWriteOnce, - api.ReadOnlyMany, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceStorage): resource.MustParse("10G"), - }, - }, - }, - Status: api.PersistentVolumeClaimStatus{ - Phase: api.ClaimBound, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Default.ResourcePath(getPersistentVolumeClaimsResoureName(), ns, "abc") + "/status", - Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: persistentVolumeClaim}, - } - response, err := c.Setup(t).PersistentVolumeClaims(ns).UpdateStatus(persistentVolumeClaim) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPersistentVolumeClaimDelete(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath(getPersistentVolumeClaimsResoureName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).PersistentVolumeClaims(ns).Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestPersistentVolumeClaimWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePathWithPrefix("watch", getPersistentVolumeClaimsResoureName(), "", ""), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).PersistentVolumeClaims(api.NamespaceAll).Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pod_templates_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pod_templates_test.go deleted file mode 100644 index bd9bcb549..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pod_templates_test.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func getPodTemplatesResoureName() string { - return "podtemplates" -} - -func TestPodTemplateCreate(t *testing.T) { - ns := api.NamespaceDefault - podTemplate := api.PodTemplate{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - }, - Template: api.PodTemplateSpec{}, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath(getPodTemplatesResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: &podTemplate, - }, - Response: simple.Response{StatusCode: 200, Body: &podTemplate}, - } - - response, err := c.Setup(t).PodTemplates(ns).Create(&podTemplate) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPodTemplateGet(t *testing.T) { - ns := api.NamespaceDefault - podTemplate := &api.PodTemplate{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - }, - Template: api.PodTemplateSpec{}, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getPodTemplatesResoureName(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: podTemplate}, - } - - response, err := c.Setup(t).PodTemplates(ns).Get("abc") - defer c.Close() - c.Validate(t, response, err) -} - -func TestPodTemplateList(t *testing.T) { - ns := api.NamespaceDefault - podTemplateList := &api.PodTemplateList{ - Items: []api.PodTemplate{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getPodTemplatesResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: podTemplateList}, - } - response, err := c.Setup(t).PodTemplates(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPodTemplateUpdate(t *testing.T) { - ns := api.NamespaceDefault - podTemplate := &api.PodTemplate{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: ns, - ResourceVersion: "1", - }, - Template: api.PodTemplateSpec{}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath(getPodTemplatesResoureName(), ns, "abc"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: podTemplate}, - } - response, err := c.Setup(t).PodTemplates(ns).Update(podTemplate) - defer c.Close() - c.Validate(t, response, err) -} - -func TestPodTemplateDelete(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath(getPodTemplatesResoureName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).PodTemplates(ns).Delete("foo", nil) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestPodTemplateWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePathWithPrefix("watch", getPodTemplatesResoureName(), "", ""), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).PodTemplates(api.NamespaceAll).Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pods.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pods.go index 04bb989c2..426d3ee8e 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pods.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pods.go @@ -18,6 +18,7 @@ package unversioned import ( "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/watch" ) @@ -36,7 +37,7 @@ type PodInterface interface { Watch(opts api.ListOptions) (watch.Interface, error) Bind(binding *api.Binding) error UpdateStatus(pod *api.Pod) (*api.Pod, error) - GetLogs(name string, opts *api.PodLogOptions) *Request + GetLogs(name string, opts *api.PodLogOptions) *restclient.Request } // pods implements PodsNamespacer interface @@ -109,6 +110,6 @@ func (c *pods) UpdateStatus(pod *api.Pod) (result *api.Pod, err error) { } // Get constructs a request for getting the logs for a pod -func (c *pods) GetLogs(name string, opts *api.PodLogOptions) *Request { +func (c *pods) GetLogs(name string, opts *api.PodLogOptions) *restclient.Request { return c.r.Get().Namespace(c.ns).Name(name).Resource("pods").SubResource("log").VersionedParams(opts, api.ParameterCodec) } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pods_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pods_test.go deleted file mode 100644 index 49175facb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/pods_test.go +++ /dev/null @@ -1,228 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import . "k8s.io/kubernetes/pkg/client/unversioned" - -import ( - "net/http" - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" - "k8s.io/kubernetes/pkg/labels" -) - -func TestListEmptyPods(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Default.ResourcePath("pods", ns, ""), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: http.StatusOK, Body: &api.PodList{}}, - } - podList, err := c.Setup(t).Pods(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, podList, err) -} - -func TestListPods(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Default.ResourcePath("pods", ns, ""), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: http.StatusOK, - Body: &api.PodList{ - Items: []api.Pod{ - { - Status: api.PodStatus{ - Phase: api.PodRunning, - }, - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - }, - }, - }, - }, - } - receivedPodList, err := c.Setup(t).Pods(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, receivedPodList, err) -} - -func TestListPodsLabels(t *testing.T) { - ns := api.NamespaceDefault - labelSelectorQueryParamName := unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("pods", ns, ""), - Query: simple.BuildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})}, - Response: simple.Response{ - StatusCode: http.StatusOK, - Body: &api.PodList{ - Items: []api.Pod{ - { - Status: api.PodStatus{ - Phase: api.PodRunning, - }, - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - }, - }, - }, - }, - } - c.Setup(t) - defer c.Close() - c.QueryValidator[labelSelectorQueryParamName] = simple.ValidateLabels - selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector() - options := api.ListOptions{LabelSelector: selector} - receivedPodList, err := c.Pods(ns).List(options) - c.Validate(t, receivedPodList, err) -} - -func TestGetPod(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Default.ResourcePath("pods", ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: http.StatusOK, - Body: &api.Pod{ - Status: api.PodStatus{ - Phase: api.PodRunning, - }, - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - }, - }, - } - receivedPod, err := c.Setup(t).Pods(ns).Get("foo") - defer c.Close() - c.Validate(t, receivedPod, err) -} - -func TestGetPodWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedPod, err := c.Setup(t).Pods(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedPod, err) -} - -func TestDeletePod(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath("pods", ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: http.StatusOK}, - } - err := c.Setup(t).Pods(ns).Delete("foo", nil) - defer c.Close() - c.Validate(t, nil, err) -} - -func TestCreatePod(t *testing.T) { - ns := api.NamespaceDefault - requestPod := &api.Pod{ - Status: api.PodStatus{ - Phase: api.PodRunning, - }, - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "POST", Path: testapi.Default.ResourcePath("pods", ns, ""), Query: simple.BuildQueryValues(nil), Body: requestPod}, - Response: simple.Response{ - StatusCode: http.StatusOK, - Body: requestPod, - }, - } - receivedPod, err := c.Setup(t).Pods(ns).Create(requestPod) - defer c.Close() - c.Validate(t, receivedPod, err) -} - -func TestUpdatePod(t *testing.T) { - ns := api.NamespaceDefault - requestPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - ResourceVersion: "1", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Status: api.PodStatus{ - Phase: api.PodRunning, - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath("pods", ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: http.StatusOK, Body: requestPod}, - } - receivedPod, err := c.Setup(t).Pods(ns).Update(requestPod) - defer c.Close() - c.Validate(t, receivedPod, err) -} - -func TestPodGetLogs(t *testing.T) { - ns := api.NamespaceDefault - opts := &api.PodLogOptions{ - Follow: true, - Timestamps: true, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("pods", ns, "podName") + "/log", - Query: url.Values{ - "follow": []string{"true"}, - "timestamps": []string{"true"}, - }, - }, - Response: simple.Response{StatusCode: http.StatusOK}, - } - - body, err := c.Setup(t).Pods(ns).GetLogs("podName", opts).Stream() - defer c.Close() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - defer body.Close() - c.ValidateCommon(t, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/podsecuritypolicy_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/podsecuritypolicy_test.go deleted file mode 100644 index dee0f5935..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/podsecuritypolicy_test.go +++ /dev/null @@ -1,138 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - "fmt" - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/extensions" - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -func TestPodSecurityPolicyCreate(t *testing.T) { - ns := api.NamespaceNone - scc := &extensions.PodSecurityPolicy{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - } - - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Extensions.ResourcePath(getPSPResourcename(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: scc, - }, - Response: simple.Response{StatusCode: 200, Body: scc}, - } - - response, err := c.Setup(t).PodSecurityPolicies().Create(scc) - c.Validate(t, response, err) -} - -func TestPodSecurityPolicyGet(t *testing.T) { - ns := api.NamespaceNone - scc := &extensions.PodSecurityPolicy{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getPSPResourcename(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: scc}, - } - - response, err := c.Setup(t).PodSecurityPolicies().Get("abc") - c.Validate(t, response, err) -} - -func TestPodSecurityPolicyList(t *testing.T) { - ns := api.NamespaceNone - sccList := &extensions.PodSecurityPolicyList{ - Items: []extensions.PodSecurityPolicy{ - { - ObjectMeta: api.ObjectMeta{ - Name: "abc", - }, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getPSPResourcename(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: sccList}, - } - response, err := c.Setup(t).PodSecurityPolicies().List(api.ListOptions{}) - c.Validate(t, response, err) -} - -func TestPodSecurityPolicyUpdate(t *testing.T) { - ns := api.NamespaceNone - scc := &extensions.PodSecurityPolicy{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - ResourceVersion: "1", - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Extensions.ResourcePath(getPSPResourcename(), ns, "abc"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: scc}, - } - response, err := c.Setup(t).PodSecurityPolicies().Update(scc) - c.Validate(t, response, err) -} - -func TestPodSecurityPolicyDelete(t *testing.T) { - ns := api.NamespaceNone - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Extensions.ResourcePath(getPSPResourcename(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).PodSecurityPolicies().Delete("foo") - c.Validate(t, nil, err) -} - -func TestPodSecurityPolicyWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: fmt.Sprintf("%s/watch/%s", testapi.Extensions.ResourcePath("", "", ""), getPSPResourcename()), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).PodSecurityPolicies().Watch(api.ListOptions{}) - c.Validate(t, nil, err) -} - -func getPSPResourcename() string { - return "podsecuritypolicies" -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/doc.go deleted file mode 100644 index 032f180f9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package portforward adds support for SSH-like port forwarding from the client's -// local host to remote containers. -package portforward diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/portforward.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/portforward.go deleted file mode 100644 index 78e6695e6..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/portforward.go +++ /dev/null @@ -1,329 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package portforward - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "strconv" - "strings" - "sync" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/kubelet/server/portforward" - "k8s.io/kubernetes/pkg/util/httpstream" - "k8s.io/kubernetes/pkg/util/runtime" -) - -// PortForwarder knows how to listen for local connections and forward them to -// a remote pod via an upgraded HTTP request. -type PortForwarder struct { - ports []ForwardedPort - stopChan <-chan struct{} - - dialer httpstream.Dialer - streamConn httpstream.Connection - listeners []io.Closer - Ready chan struct{} - requestIDLock sync.Mutex - requestID int -} - -// ForwardedPort contains a Local:Remote port pairing. -type ForwardedPort struct { - Local uint16 - Remote uint16 -} - -/* - valid port specifications: - - 5000 - - forwards from localhost:5000 to pod:5000 - - 8888:5000 - - forwards from localhost:8888 to pod:5000 - - 0:5000 - :5000 - - selects a random available local port, - forwards from localhost: to pod:5000 -*/ -func parsePorts(ports []string) ([]ForwardedPort, error) { - var forwards []ForwardedPort - for _, portString := range ports { - parts := strings.Split(portString, ":") - var localString, remoteString string - if len(parts) == 1 { - localString = parts[0] - remoteString = parts[0] - } else if len(parts) == 2 { - localString = parts[0] - if localString == "" { - // support :5000 - localString = "0" - } - remoteString = parts[1] - } else { - return nil, fmt.Errorf("Invalid port format '%s'", portString) - } - - localPort, err := strconv.ParseUint(localString, 10, 16) - if err != nil { - return nil, fmt.Errorf("Error parsing local port '%s': %s", localString, err) - } - - remotePort, err := strconv.ParseUint(remoteString, 10, 16) - if err != nil { - return nil, fmt.Errorf("Error parsing remote port '%s': %s", remoteString, err) - } - if remotePort == 0 { - return nil, fmt.Errorf("Remote port must be > 0") - } - - forwards = append(forwards, ForwardedPort{uint16(localPort), uint16(remotePort)}) - } - - return forwards, nil -} - -// New creates a new PortForwarder. -func New(dialer httpstream.Dialer, ports []string, stopChan <-chan struct{}) (*PortForwarder, error) { - if len(ports) == 0 { - return nil, errors.New("You must specify at least 1 port") - } - parsedPorts, err := parsePorts(ports) - if err != nil { - return nil, err - } - return &PortForwarder{ - dialer: dialer, - ports: parsedPorts, - stopChan: stopChan, - Ready: make(chan struct{}), - }, nil -} - -// ForwardPorts formats and executes a port forwarding request. The connection will remain -// open until stopChan is closed. -func (pf *PortForwarder) ForwardPorts() error { - defer pf.Close() - - var err error - pf.streamConn, _, err = pf.dialer.Dial(portforward.PortForwardProtocolV1Name) - if err != nil { - return fmt.Errorf("error upgrading connection: %s", err) - } - defer pf.streamConn.Close() - - return pf.forward() -} - -// forward dials the remote host specific in req, upgrades the request, starts -// listeners for each port specified in ports, and forwards local connections -// to the remote host via streams. -func (pf *PortForwarder) forward() error { - var err error - - listenSuccess := false - for _, port := range pf.ports { - err = pf.listenOnPort(&port) - switch { - case err == nil: - listenSuccess = true - default: - glog.Warningf("Unable to listen on port %d: %v", port.Local, err) - } - } - - if !listenSuccess { - return fmt.Errorf("Unable to listen on any of the requested ports: %v", pf.ports) - } - - close(pf.Ready) - - // wait for interrupt or conn closure - select { - case <-pf.stopChan: - case <-pf.streamConn.CloseChan(): - runtime.HandleError(errors.New("lost connection to pod")) - } - - return nil -} - -// listenOnPort delegates tcp4 and tcp6 listener creation and waits for connections on both of these addresses. -// If both listener creation fail, an error is raised. -func (pf *PortForwarder) listenOnPort(port *ForwardedPort) error { - errTcp4 := pf.listenOnPortAndAddress(port, "tcp4", "127.0.0.1") - errTcp6 := pf.listenOnPortAndAddress(port, "tcp6", "[::1]") - if errTcp4 != nil && errTcp6 != nil { - return fmt.Errorf("All listeners failed to create with the following errors: %s, %s", errTcp4, errTcp6) - } - return nil -} - -// listenOnPortAndAddress delegates listener creation and waits for new connections -// in the background f -func (pf *PortForwarder) listenOnPortAndAddress(port *ForwardedPort, protocol string, address string) error { - listener, err := pf.getListener(protocol, address, port) - if err != nil { - return err - } - pf.listeners = append(pf.listeners, listener) - go pf.waitForConnection(listener, *port) - return nil -} - -// getListener creates a listener on the interface targeted by the given hostname on the given port with -// the given protocol. protocol is in net.Listen style which basically admits values like tcp, tcp4, tcp6 -func (pf *PortForwarder) getListener(protocol string, hostname string, port *ForwardedPort) (net.Listener, error) { - listener, err := net.Listen(protocol, fmt.Sprintf("%s:%d", hostname, port.Local)) - if err != nil { - runtime.HandleError(fmt.Errorf("Unable to create listener: Error %s", err)) - return nil, err - } - listenerAddress := listener.Addr().String() - host, localPort, _ := net.SplitHostPort(listenerAddress) - localPortUInt, err := strconv.ParseUint(localPort, 10, 16) - - if err != nil { - return nil, fmt.Errorf("Error parsing local port: %s from %s (%s)", err, listenerAddress, host) - } - port.Local = uint16(localPortUInt) - glog.Infof("Forwarding from %s:%d -> %d", hostname, localPortUInt, port.Remote) - - return listener, nil -} - -// waitForConnection waits for new connections to listener and handles them in -// the background. -func (pf *PortForwarder) waitForConnection(listener net.Listener, port ForwardedPort) { - for { - conn, err := listener.Accept() - if err != nil { - // TODO consider using something like https://github.com/hydrogen18/stoppableListener? - if !strings.Contains(strings.ToLower(err.Error()), "use of closed network connection") { - runtime.HandleError(fmt.Errorf("Error accepting connection on port %d: %v", port.Local, err)) - } - return - } - go pf.handleConnection(conn, port) - } -} - -func (pf *PortForwarder) nextRequestID() int { - pf.requestIDLock.Lock() - defer pf.requestIDLock.Unlock() - id := pf.requestID - pf.requestID++ - return id -} - -// handleConnection copies data between the local connection and the stream to -// the remote server. -func (pf *PortForwarder) handleConnection(conn net.Conn, port ForwardedPort) { - defer conn.Close() - - glog.Infof("Handling connection for %d", port.Local) - - requestID := pf.nextRequestID() - - // create error stream - headers := http.Header{} - headers.Set(api.StreamType, api.StreamTypeError) - headers.Set(api.PortHeader, fmt.Sprintf("%d", port.Remote)) - headers.Set(api.PortForwardRequestIDHeader, strconv.Itoa(requestID)) - errorStream, err := pf.streamConn.CreateStream(headers) - if err != nil { - runtime.HandleError(fmt.Errorf("error creating error stream for port %d -> %d: %v", port.Local, port.Remote, err)) - return - } - // we're not writing to this stream - errorStream.Close() - - errorChan := make(chan error) - go func() { - message, err := ioutil.ReadAll(errorStream) - switch { - case err != nil: - errorChan <- fmt.Errorf("error reading from error stream for port %d -> %d: %v", port.Local, port.Remote, err) - case len(message) > 0: - errorChan <- fmt.Errorf("an error occurred forwarding %d -> %d: %v", port.Local, port.Remote, string(message)) - } - close(errorChan) - }() - - // create data stream - headers.Set(api.StreamType, api.StreamTypeData) - dataStream, err := pf.streamConn.CreateStream(headers) - if err != nil { - runtime.HandleError(fmt.Errorf("error creating forwarding stream for port %d -> %d: %v", port.Local, port.Remote, err)) - return - } - - localError := make(chan struct{}) - remoteDone := make(chan struct{}) - - go func() { - // Copy from the remote side to the local port. - if _, err := io.Copy(conn, dataStream); err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - runtime.HandleError(fmt.Errorf("error copying from remote stream to local connection: %v", err)) - } - - // inform the select below that the remote copy is done - close(remoteDone) - }() - - go func() { - // inform server we're not sending any more data after copy unblocks - defer dataStream.Close() - - // Copy from the local port to the remote side. - if _, err := io.Copy(dataStream, conn); err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - runtime.HandleError(fmt.Errorf("error copying from local connection to remote stream: %v", err)) - // break out of the select below without waiting for the other copy to finish - close(localError) - } - }() - - // wait for either a local->remote error or for copying from remote->local to finish - select { - case <-remoteDone: - case <-localError: - } - - // always expect something on errorChan (it may be nil) - err = <-errorChan - if err != nil { - runtime.HandleError(err) - } -} - -func (pf *PortForwarder) Close() { - // stop all listeners - for _, l := range pf.listeners { - if err := l.Close(); err != nil { - runtime.HandleError(fmt.Errorf("error closing listener: %v", err)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/portforward_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/portforward_test.go deleted file mode 100644 index 2d5060b29..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/portforward/portforward_test.go +++ /dev/null @@ -1,400 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package portforward - -import ( - "bytes" - "fmt" - "io" - "net" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "strings" - "sync" - "testing" - "time" - - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/remotecommand" - kubeletserver "k8s.io/kubernetes/pkg/kubelet/server" - "k8s.io/kubernetes/pkg/types" - "k8s.io/kubernetes/pkg/util/httpstream" -) - -type fakeDialer struct { - dialed bool - conn httpstream.Connection - err error - negotiatedProtocol string -} - -func (d *fakeDialer) Dial(protocols ...string) (httpstream.Connection, string, error) { - d.dialed = true - return d.conn, d.negotiatedProtocol, d.err -} - -func TestParsePortsAndNew(t *testing.T) { - tests := []struct { - input []string - expected []ForwardedPort - expectParseError bool - expectNewError bool - }{ - {input: []string{}, expectNewError: true}, - {input: []string{"a"}, expectParseError: true, expectNewError: true}, - {input: []string{":a"}, expectParseError: true, expectNewError: true}, - {input: []string{"-1"}, expectParseError: true, expectNewError: true}, - {input: []string{"65536"}, expectParseError: true, expectNewError: true}, - {input: []string{"0"}, expectParseError: true, expectNewError: true}, - {input: []string{"0:0"}, expectParseError: true, expectNewError: true}, - {input: []string{"a:5000"}, expectParseError: true, expectNewError: true}, - {input: []string{"5000:a"}, expectParseError: true, expectNewError: true}, - { - input: []string{"5000", "5000:5000", "8888:5000", "5000:8888", ":5000", "0:5000"}, - expected: []ForwardedPort{ - {5000, 5000}, - {5000, 5000}, - {8888, 5000}, - {5000, 8888}, - {0, 5000}, - {0, 5000}, - }, - }, - } - - for i, test := range tests { - parsed, err := parsePorts(test.input) - haveError := err != nil - if e, a := test.expectParseError, haveError; e != a { - t.Fatalf("%d: parsePorts: error expected=%t, got %t: %s", i, e, a, err) - } - - dialer := &fakeDialer{} - expectedStopChan := make(chan struct{}) - pf, err := New(dialer, test.input, expectedStopChan) - haveError = err != nil - if e, a := test.expectNewError, haveError; e != a { - t.Fatalf("%d: New: error expected=%t, got %t: %s", i, e, a, err) - } - - if test.expectParseError || test.expectNewError { - continue - } - - for pi, expectedPort := range test.expected { - if e, a := expectedPort.Local, parsed[pi].Local; e != a { - t.Fatalf("%d: local expected: %d, got: %d", i, e, a) - } - if e, a := expectedPort.Remote, parsed[pi].Remote; e != a { - t.Fatalf("%d: remote expected: %d, got: %d", i, e, a) - } - } - - if dialer.dialed { - t.Fatalf("%d: expected not dialed", i) - } - if e, a := test.expected, pf.ports; !reflect.DeepEqual(e, a) { - t.Fatalf("%d: ports: expected %#v, got %#v", i, e, a) - } - if e, a := expectedStopChan, pf.stopChan; e != a { - t.Fatalf("%d: stopChan: expected %#v, got %#v", i, e, a) - } - if pf.Ready == nil { - t.Fatalf("%d: Ready should be non-nil", i) - } - } -} - -type GetListenerTestCase struct { - Hostname string - Protocol string - ShouldRaiseError bool - ExpectedListenerAddress string -} - -func TestGetListener(t *testing.T) { - var pf PortForwarder - testCases := []GetListenerTestCase{ - { - Hostname: "localhost", - Protocol: "tcp4", - ShouldRaiseError: false, - ExpectedListenerAddress: "127.0.0.1", - }, - { - Hostname: "127.0.0.1", - Protocol: "tcp4", - ShouldRaiseError: false, - ExpectedListenerAddress: "127.0.0.1", - }, - { - Hostname: "[::1]", - Protocol: "tcp6", - ShouldRaiseError: false, - ExpectedListenerAddress: "::1", - }, - { - Hostname: "[::1]", - Protocol: "tcp4", - ShouldRaiseError: true, - }, - { - Hostname: "127.0.0.1", - Protocol: "tcp6", - ShouldRaiseError: true, - }, - { - // IPv6 address must be put into brackets. This test reveals this. - Hostname: "::1", - Protocol: "tcp6", - ShouldRaiseError: true, - }, - } - - for i, testCase := range testCases { - expectedListenerPort := "12345" - listener, err := pf.getListener(testCase.Protocol, testCase.Hostname, &ForwardedPort{12345, 12345}) - if err != nil && strings.Contains(err.Error(), "cannot assign requested address") { - t.Logf("Can't test #%d: %v", i, err) - continue - } - errorRaised := err != nil - - if testCase.ShouldRaiseError != errorRaised { - t.Errorf("Test case #%d failed: Data %v an error has been raised(%t) where it should not (or reciprocally): %v", i, testCase, testCase.ShouldRaiseError, err) - continue - } - if errorRaised { - continue - } - - if listener == nil { - t.Errorf("Test case #%d did not raise an error but failed in initializing listener", i) - continue - } - - host, port, _ := net.SplitHostPort(listener.Addr().String()) - t.Logf("Asked a %s forward for: %s:%v, got listener %s:%s, expected: %s", testCase.Protocol, testCase.Hostname, 12345, host, port, expectedListenerPort) - if host != testCase.ExpectedListenerAddress { - t.Errorf("Test case #%d failed: Listener does not listen on exepected address: asked %v got %v", i, testCase.ExpectedListenerAddress, host) - } - if port != expectedListenerPort { - t.Errorf("Test case #%d failed: Listener does not listen on exepected port: asked %v got %v", i, expectedListenerPort, port) - - } - listener.Close() - - } -} - -// fakePortForwarder simulates port forwarding for testing. It implements -// kubeletserver.PortForwarder. -type fakePortForwarder struct { - lock sync.Mutex - // stores data expected from the stream per port - expected map[uint16]string - // stores data received from the stream per port - received map[uint16]string - // data to be sent to the stream per port - send map[uint16]string -} - -var _ kubeletserver.PortForwarder = &fakePortForwarder{} - -func (pf *fakePortForwarder) PortForward(name string, uid types.UID, port uint16, stream io.ReadWriteCloser) error { - defer stream.Close() - - // read from the client - received := make([]byte, len(pf.expected[port])) - n, err := stream.Read(received) - if err != nil { - return fmt.Errorf("error reading from client for port %d: %v", port, err) - } - if n != len(pf.expected[port]) { - return fmt.Errorf("unexpected length read from client for port %d: got %d, expected %d. data=%q", port, n, len(pf.expected[port]), string(received)) - } - - // store the received content - pf.lock.Lock() - pf.received[port] = string(received) - pf.lock.Unlock() - - // send the hardcoded data to the client - io.Copy(stream, strings.NewReader(pf.send[port])) - - return nil -} - -// fakePortForwardServer creates an HTTP server that can handle port forwarding -// requests. -func fakePortForwardServer(t *testing.T, testName string, serverSends, expectedFromClient map[uint16]string) http.HandlerFunc { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - pf := &fakePortForwarder{ - expected: expectedFromClient, - received: make(map[uint16]string), - send: serverSends, - } - kubeletserver.ServePortForward(w, req, pf, "pod", "uid", 0, 10*time.Second) - - for port, expected := range expectedFromClient { - actual, ok := pf.received[port] - if !ok { - t.Errorf("%s: server didn't receive any data for port %d", testName, port) - continue - } - - if expected != actual { - t.Errorf("%s: server expected to receive %q, got %q for port %d", testName, expected, actual, port) - } - } - - for port, actual := range pf.received { - if _, ok := expectedFromClient[port]; !ok { - t.Errorf("%s: server unexpectedly received %q for port %d", testName, actual, port) - } - } - }) -} - -func TestForwardPorts(t *testing.T) { - tests := map[string]struct { - ports []string - clientSends map[uint16]string - serverSends map[uint16]string - }{ - "forward 1 port with no data either direction": { - ports: []string{"5000"}, - }, - "forward 2 ports with bidirectional data": { - ports: []string{"5001", "6000"}, - clientSends: map[uint16]string{ - 5001: "abcd", - 6000: "ghij", - }, - serverSends: map[uint16]string{ - 5001: "1234", - 6000: "5678", - }, - }, - } - - for testName, test := range tests { - server := httptest.NewServer(fakePortForwardServer(t, testName, test.serverSends, test.clientSends)) - - url, _ := url.Parse(server.URL) - exec, err := remotecommand.NewExecutor(&client.Config{}, "POST", url) - if err != nil { - t.Fatal(err) - } - - stopChan := make(chan struct{}, 1) - - pf, err := New(exec, test.ports, stopChan) - if err != nil { - t.Fatalf("%s: unexpected error calling New: %v", testName, err) - } - - doneChan := make(chan error) - go func() { - doneChan <- pf.ForwardPorts() - }() - <-pf.Ready - - for port, data := range test.clientSends { - clientConn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port)) - if err != nil { - t.Errorf("%s: error dialing %d: %s", testName, port, err) - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - defer clientConn.Close() - - n, err := clientConn.Write([]byte(data)) - if err != nil && err != io.EOF { - t.Errorf("%s: Error sending data '%s': %s", testName, data, err) - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - if n == 0 { - t.Errorf("%s: unexpected write of 0 bytes", testName) - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - b := make([]byte, 4) - n, err = clientConn.Read(b) - if err != nil && err != io.EOF { - t.Errorf("%s: Error reading data: %s", testName, err) - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - if !bytes.Equal([]byte(test.serverSends[port]), b) { - t.Errorf("%s: expected to read '%s', got '%s'", testName, test.serverSends[port], b) - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - } - // tell r.ForwardPorts to stop - close(stopChan) - - // wait for r.ForwardPorts to actually return - err = <-doneChan - if err != nil { - t.Errorf("%s: unexpected error: %s", testName, err) - } - // TODO: Uncomment when fix #19254 - // server.Close() - } - -} - -func TestForwardPortsReturnsErrorWhenAllBindsFailed(t *testing.T) { - server := httptest.NewServer(fakePortForwardServer(t, "allBindsFailed", nil, nil)) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - url, _ := url.Parse(server.URL) - exec, err := remotecommand.NewExecutor(&client.Config{}, "POST", url) - if err != nil { - t.Fatal(err) - } - - stopChan1 := make(chan struct{}, 1) - defer close(stopChan1) - - pf1, err := New(exec, []string{"5555"}, stopChan1) - if err != nil { - t.Fatalf("error creating pf1: %v", err) - } - go pf1.ForwardPorts() - <-pf1.Ready - - stopChan2 := make(chan struct{}, 1) - pf2, err := New(exec, []string{"5555"}, stopChan2) - if err != nil { - t.Fatalf("error creating pf2: %v", err) - } - if err := pf2.ForwardPorts(); err == nil { - t.Fatal("expected non-nil error for pf2.ForwardPorts") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/doc.go deleted file mode 100644 index 88197ed0d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package remotecommand adds support for executing commands in containers, -// with support for separate stdin, stdout, and stderr streams, as well as -// TTY. -package remotecommand diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/remotecommand.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/remotecommand.go deleted file mode 100644 index d827f1010..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/remotecommand.go +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package remotecommand - -import ( - "fmt" - "io" - "net/http" - "net/url" - - "github.com/golang/glog" - - "k8s.io/kubernetes/pkg/client/transport" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/util/httpstream" - "k8s.io/kubernetes/pkg/util/httpstream/spdy" -) - -// Executor is an interface for transporting shell-style streams. -type Executor interface { - // Stream initiates the transport of the standard shell streams. It will transport any - // non-nil stream to a remote system, and return an error if a problem occurs. If tty - // is set, the stderr stream is not used (raw TTY manages stdout and stderr over the - // stdout stream). - Stream(stdin io.Reader, stdout, stderr io.Writer, tty bool) error -} - -// StreamExecutor supports the ability to dial an httpstream connection and the ability to -// run a command line stream protocol over that dialer. -type StreamExecutor interface { - Executor - httpstream.Dialer -} - -// streamExecutor handles transporting standard shell streams over an httpstream connection. -type streamExecutor struct { - upgrader httpstream.UpgradeRoundTripper - transport http.RoundTripper - - method string - url *url.URL -} - -// NewExecutor connects to the provided server and upgrades the connection to -// multiplexed bidirectional streams. The current implementation uses SPDY, -// but this could be replaced with HTTP/2 once it's available, or something else. -// TODO: the common code between this and portforward could be abstracted. -func NewExecutor(config *client.Config, method string, url *url.URL) (StreamExecutor, error) { - tlsConfig, err := client.TLSConfigFor(config) - if err != nil { - return nil, err - } - - upgradeRoundTripper := spdy.NewRoundTripper(tlsConfig) - wrapper, err := client.HTTPWrappersForConfig(config, upgradeRoundTripper) - if err != nil { - return nil, err - } - - return &streamExecutor{ - upgrader: upgradeRoundTripper, - transport: wrapper, - method: method, - url: url, - }, nil -} - -// NewStreamExecutor upgrades the request so that it supports multiplexed bidirectional -// streams. This method takes a stream upgrader and an optional function that is invoked -// to wrap the round tripper. This method may be used by clients that are lower level than -// Kubernetes clients or need to provide their own upgrade round tripper. -func NewStreamExecutor(upgrader httpstream.UpgradeRoundTripper, fn func(http.RoundTripper) http.RoundTripper, method string, url *url.URL) (StreamExecutor, error) { - var rt http.RoundTripper = upgrader - if fn != nil { - rt = fn(rt) - } - return &streamExecutor{ - upgrader: upgrader, - transport: rt, - method: method, - url: url, - }, nil -} - -// Dial opens a connection to a remote server and attempts to negotiate a SPDY -// connection. Upon success, it returns the connection and the protocol -// selected by the server. -func (e *streamExecutor) Dial(protocols ...string) (httpstream.Connection, string, error) { - rt := transport.DebugWrappers(e.transport) - - // TODO the client probably shouldn't be created here, as it doesn't allow - // flexibility to allow callers to configure it. - client := &http.Client{Transport: rt} - - req, err := http.NewRequest(e.method, e.url.String(), nil) - if err != nil { - return nil, "", fmt.Errorf("error creating request: %v", err) - } - for i := range protocols { - req.Header.Add(httpstream.HeaderProtocolVersion, protocols[i]) - } - - resp, err := client.Do(req) - if err != nil { - return nil, "", fmt.Errorf("error sending request: %v", err) - } - defer resp.Body.Close() - - conn, err := e.upgrader.NewConnection(resp) - if err != nil { - return nil, "", err - } - - return conn, resp.Header.Get(httpstream.HeaderProtocolVersion), nil -} - -const ( - // The SPDY subprotocol "channel.k8s.io" is used for remote command - // attachment/execution. This represents the initial unversioned subprotocol, - // which has the known bugs http://issues.k8s.io/13394 and - // http://issues.k8s.io/13395. - StreamProtocolV1Name = "channel.k8s.io" - // The SPDY subprotocol "v2.channel.k8s.io" is used for remote command - // attachment/execution. It is the second version of the subprotocol and - // resolves the issues present in the first version. - StreamProtocolV2Name = "v2.channel.k8s.io" -) - -type streamProtocolHandler interface { - stream(httpstream.Connection) error -} - -// Stream opens a protocol streamer to the server and streams until a client closes -// the connection or the server disconnects. -func (e *streamExecutor) Stream(stdin io.Reader, stdout, stderr io.Writer, tty bool) error { - supportedProtocols := []string{StreamProtocolV2Name, StreamProtocolV1Name} - conn, protocol, err := e.Dial(supportedProtocols...) - if err != nil { - return err - } - defer conn.Close() - - var streamer streamProtocolHandler - - switch protocol { - case StreamProtocolV2Name: - streamer = &streamProtocolV2{ - stdin: stdin, - stdout: stdout, - stderr: stderr, - tty: tty, - } - case "": - glog.V(4).Infof("The server did not negotiate a streaming protocol version. Falling back to %s", StreamProtocolV1Name) - fallthrough - case StreamProtocolV1Name: - streamer = &streamProtocolV1{ - stdin: stdin, - stdout: stdout, - stderr: stderr, - tty: tty, - } - } - - return streamer.stream(conn) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/remotecommand_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/remotecommand_test.go deleted file mode 100644 index 71acd239d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/remotecommand_test.go +++ /dev/null @@ -1,413 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package remotecommand - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/util/httpstream" - "k8s.io/kubernetes/pkg/util/httpstream/spdy" -) - -type streamAndReply struct { - httpstream.Stream - replySent <-chan struct{} -} - -func waitStreamReply(replySent <-chan struct{}, notify chan<- struct{}, stop <-chan struct{}) { - select { - case <-replySent: - notify <- struct{}{} - case <-stop: - } -} - -func fakeExecServer(t *testing.T, i int, stdinData, stdoutData, stderrData, errorData string, tty bool, messageCount int) http.HandlerFunc { - // error + stdin + stdout - expectedStreams := 3 - if !tty { - // stderr - expectedStreams++ - } - - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - protocol, err := httpstream.Handshake(req, w, []string{StreamProtocolV2Name}, StreamProtocolV1Name) - if err != nil { - t.Fatal(err) - } - if protocol != StreamProtocolV2Name { - t.Fatalf("unexpected protocol: %s", protocol) - } - streamCh := make(chan streamAndReply) - - upgrader := spdy.NewResponseUpgrader() - conn := upgrader.UpgradeResponse(w, req, func(stream httpstream.Stream, replySent <-chan struct{}) error { - streamCh <- streamAndReply{Stream: stream, replySent: replySent} - return nil - }) - // from this point on, we can no longer call methods on w - if conn == nil { - // The upgrader is responsible for notifying the client of any errors that - // occurred during upgrading. All we can do is return here at this point - // if we weren't successful in upgrading. - return - } - defer conn.Close() - - var errorStream, stdinStream, stdoutStream, stderrStream httpstream.Stream - receivedStreams := 0 - replyChan := make(chan struct{}) - stop := make(chan struct{}) - defer close(stop) - WaitForStreams: - for { - select { - case stream := <-streamCh: - streamType := stream.Headers().Get(api.StreamType) - switch streamType { - case api.StreamTypeError: - errorStream = stream - go waitStreamReply(stream.replySent, replyChan, stop) - case api.StreamTypeStdin: - stdinStream = stream - go waitStreamReply(stream.replySent, replyChan, stop) - case api.StreamTypeStdout: - stdoutStream = stream - go waitStreamReply(stream.replySent, replyChan, stop) - case api.StreamTypeStderr: - stderrStream = stream - go waitStreamReply(stream.replySent, replyChan, stop) - default: - t.Errorf("%d: unexpected stream type: %q", i, streamType) - } - - if receivedStreams == expectedStreams { - break WaitForStreams - } - case <-replyChan: - receivedStreams++ - if receivedStreams == expectedStreams { - break WaitForStreams - } - } - } - - if len(errorData) > 0 { - n, err := fmt.Fprint(errorStream, errorData) - if err != nil { - t.Errorf("%d: error writing to errorStream: %v", i, err) - } - if e, a := len(errorData), n; e != a { - t.Errorf("%d: expected to write %d bytes to errorStream, but only wrote %d", i, e, a) - } - errorStream.Close() - } - - if len(stdoutData) > 0 { - for j := 0; j < messageCount; j++ { - n, err := fmt.Fprint(stdoutStream, stdoutData) - if err != nil { - t.Errorf("%d: error writing to stdoutStream: %v", i, err) - } - if e, a := len(stdoutData), n; e != a { - t.Errorf("%d: expected to write %d bytes to stdoutStream, but only wrote %d", i, e, a) - } - } - stdoutStream.Close() - } - if len(stderrData) > 0 { - for j := 0; j < messageCount; j++ { - n, err := fmt.Fprint(stderrStream, stderrData) - if err != nil { - t.Errorf("%d: error writing to stderrStream: %v", i, err) - } - if e, a := len(stderrData), n; e != a { - t.Errorf("%d: expected to write %d bytes to stderrStream, but only wrote %d", i, e, a) - } - } - stderrStream.Close() - } - if len(stdinData) > 0 { - data := make([]byte, len(stdinData)) - for j := 0; j < messageCount; j++ { - n, err := io.ReadFull(stdinStream, data) - if err != nil { - t.Errorf("%d: error reading stdin stream: %v", i, err) - } - if e, a := len(stdinData), n; e != a { - t.Errorf("%d: expected to read %d bytes from stdinStream, but only read %d", i, e, a) - } - if e, a := stdinData, string(data); e != a { - t.Errorf("%d: stdin: expected %q, got %q", i, e, a) - } - } - stdinStream.Close() - } - }) -} - -func TestRequestExecuteRemoteCommand(t *testing.T) { - testCases := []struct { - Stdin string - Stdout string - Stderr string - Error string - Tty bool - MessageCount int - }{ - { - Error: "bail", - }, - { - Stdin: "a", - Stdout: "b", - Stderr: "c", - // TODO bump this to a larger number such as 100 once - // https://github.com/docker/spdystream/issues/55 is fixed and the Godep - // is bumped. Sending multiple messages over stdin/stdout/stderr results - // in more frames being spread across multiple spdystream frame workers. - // This makes it more likely that the spdystream bug will be encountered, - // where streams are closed as soon as a goaway frame is received, and - // any pending frames that haven't been processed yet may not be - // delivered (it's a race). - MessageCount: 1, - }, - { - Stdin: "a", - Stdout: "b", - Tty: true, - }, - } - - for i, testCase := range testCases { - localOut := &bytes.Buffer{} - localErr := &bytes.Buffer{} - - server := httptest.NewServer(fakeExecServer(t, i, testCase.Stdin, testCase.Stdout, testCase.Stderr, testCase.Error, testCase.Tty, testCase.MessageCount)) - - url, _ := url.ParseRequestURI(server.URL) - c := client.NewRESTClient(url, "", client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Group: "x"}}, -1, -1, nil) - req := c.Post().Resource("testing") - req.SetHeader(httpstream.HeaderProtocolVersion, StreamProtocolV2Name) - req.Param("command", "ls") - req.Param("command", "/") - conf := &client.Config{ - Host: server.URL, - } - e, err := NewExecutor(conf, "POST", req.URL()) - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - err = e.Stream(strings.NewReader(strings.Repeat(testCase.Stdin, testCase.MessageCount)), localOut, localErr, testCase.Tty) - hasErr := err != nil - - if len(testCase.Error) > 0 { - if !hasErr { - t.Errorf("%d: expected an error", i) - } else { - if e, a := testCase.Error, err.Error(); !strings.Contains(a, e) { - t.Errorf("%d: expected error stream read '%v', got '%v'", i, e, a) - } - } - - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - - if hasErr { - t.Errorf("%d: unexpected error: %v", i, err) - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - - if len(testCase.Stdout) > 0 { - if e, a := strings.Repeat(testCase.Stdout, testCase.MessageCount), localOut; e != a.String() { - t.Errorf("%d: expected stdout data '%s', got '%s'", i, e, a) - } - } - - if testCase.Stderr != "" { - if e, a := strings.Repeat(testCase.Stderr, testCase.MessageCount), localErr; e != a.String() { - t.Errorf("%d: expected stderr data '%s', got '%s'", i, e, a) - } - } - - // TODO: Uncomment when fix #19254 - // server.Close() - } -} - -// TODO: this test is largely cut and paste, refactor to share code -func TestRequestAttachRemoteCommand(t *testing.T) { - testCases := []struct { - Stdin string - Stdout string - Stderr string - Error string - Tty bool - }{ - { - Error: "bail", - }, - { - Stdin: "a", - Stdout: "b", - Stderr: "c", - }, - { - Stdin: "a", - Stdout: "b", - Tty: true, - }, - } - - for i, testCase := range testCases { - localOut := &bytes.Buffer{} - localErr := &bytes.Buffer{} - - server := httptest.NewServer(fakeExecServer(t, i, testCase.Stdin, testCase.Stdout, testCase.Stderr, testCase.Error, testCase.Tty, 1)) - - url, _ := url.ParseRequestURI(server.URL) - c := client.NewRESTClient(url, "", client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Group: "x"}}, -1, -1, nil) - req := c.Post().Resource("testing") - - conf := &client.Config{ - Host: server.URL, - } - e, err := NewExecutor(conf, "POST", req.URL()) - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - err = e.Stream(strings.NewReader(testCase.Stdin), localOut, localErr, testCase.Tty) - hasErr := err != nil - - if len(testCase.Error) > 0 { - if !hasErr { - t.Errorf("%d: expected an error", i) - } else { - if e, a := testCase.Error, err.Error(); !strings.Contains(a, e) { - t.Errorf("%d: expected error stream read '%v', got '%v'", i, e, a) - } - } - - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - - if hasErr { - t.Errorf("%d: unexpected error: %v", i, err) - // TODO: Uncomment when fix #19254 - // server.Close() - continue - } - - if len(testCase.Stdout) > 0 { - if e, a := testCase.Stdout, localOut; e != a.String() { - t.Errorf("%d: expected stdout data '%s', got '%s'", i, e, a) - } - } - - if testCase.Stderr != "" { - if e, a := testCase.Stderr, localErr; e != a.String() { - t.Errorf("%d: expected stderr data '%s', got '%s'", i, e, a) - } - } - - // TODO: Uncomment when fix #19254 - // server.Close() - } -} - -type fakeUpgrader struct { - req *http.Request - resp *http.Response - conn httpstream.Connection - err, connErr error - checkResponse bool - - t *testing.T -} - -func (u *fakeUpgrader) RoundTrip(req *http.Request) (*http.Response, error) { - u.req = req - return u.resp, u.err -} - -func (u *fakeUpgrader) NewConnection(resp *http.Response) (httpstream.Connection, error) { - if u.checkResponse && u.resp != resp { - u.t.Errorf("response objects passed did not match: %#v", resp) - } - return u.conn, u.connErr -} - -type fakeConnection struct { - httpstream.Connection -} - -// Dial is the common functionality between any stream based upgrader, regardless of protocol. -// This method ensures that someone can use a generic stream executor without being dependent -// on the core Kube client config behavior. -func TestDial(t *testing.T) { - upgrader := &fakeUpgrader{ - t: t, - checkResponse: true, - conn: &fakeConnection{}, - resp: &http.Response{ - StatusCode: http.StatusSwitchingProtocols, - Body: ioutil.NopCloser(&bytes.Buffer{}), - }, - } - var called bool - testFn := func(rt http.RoundTripper) http.RoundTripper { - if rt != upgrader { - t.Fatalf("unexpected round tripper: %#v", rt) - } - called = true - return rt - } - exec, err := NewStreamExecutor(upgrader, testFn, "POST", &url.URL{Host: "something.com", Scheme: "https"}) - if err != nil { - t.Fatal(err) - } - conn, protocol, err := exec.Dial("protocol1") - if err != nil { - t.Fatal(err) - } - if conn != upgrader.conn { - t.Errorf("unexpected connection: %#v", conn) - } - if !called { - t.Errorf("wrapper not called") - } - _ = protocol -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/v1.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/v1.go deleted file mode 100644 index f5428e0f9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/v1.go +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package remotecommand - -import ( - "fmt" - "io" - "io/ioutil" - "net/http" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/util/httpstream" -) - -// streamProtocolV1 implements the first version of the streaming exec & attach -// protocol. This version has some bugs, such as not being able to detecte when -// non-interactive stdin data has ended. See http://issues.k8s.io/13394 and -// http://issues.k8s.io/13395 for more details. -type streamProtocolV1 struct { - stdin io.Reader - stdout io.Writer - stderr io.Writer - tty bool -} - -var _ streamProtocolHandler = &streamProtocolV1{} - -func (e *streamProtocolV1) stream(conn httpstream.Connection) error { - doneChan := make(chan struct{}, 2) - errorChan := make(chan error) - - cp := func(s string, dst io.Writer, src io.Reader) { - glog.V(6).Infof("Copying %s", s) - defer glog.V(6).Infof("Done copying %s", s) - if _, err := io.Copy(dst, src); err != nil && err != io.EOF { - glog.Errorf("Error copying %s: %v", s, err) - } - if s == api.StreamTypeStdout || s == api.StreamTypeStderr { - doneChan <- struct{}{} - } - } - - var ( - err error - errorStream, remoteStdin, remoteStdout, remoteStderr httpstream.Stream - ) - - // set up all the streams first - headers := http.Header{} - headers.Set(api.StreamType, api.StreamTypeError) - errorStream, err = conn.CreateStream(headers) - if err != nil { - return err - } - defer errorStream.Reset() - - // Create all the streams first, then start the copy goroutines. The server doesn't start its copy - // goroutines until it's received all of the streams. If the client creates the stdin stream and - // immediately begins copying stdin data to the server, it's possible to overwhelm and wedge the - // spdy frame handler in the server so that it is full of unprocessed frames. The frames aren't - // getting processed because the server hasn't started its copying, and it won't do that until it - // gets all the streams. By creating all the streams first, we ensure that the server is ready to - // process data before the client starts sending any. See https://issues.k8s.io/16373 for more info. - if e.stdin != nil { - headers.Set(api.StreamType, api.StreamTypeStdin) - remoteStdin, err = conn.CreateStream(headers) - if err != nil { - return err - } - defer remoteStdin.Reset() - } - - if e.stdout != nil { - headers.Set(api.StreamType, api.StreamTypeStdout) - remoteStdout, err = conn.CreateStream(headers) - if err != nil { - return err - } - defer remoteStdout.Reset() - } - - if e.stderr != nil && !e.tty { - headers.Set(api.StreamType, api.StreamTypeStderr) - remoteStderr, err = conn.CreateStream(headers) - if err != nil { - return err - } - defer remoteStderr.Reset() - } - - // now that all the streams have been created, proceed with reading & copying - - // always read from errorStream - go func() { - message, err := ioutil.ReadAll(errorStream) - if err != nil && err != io.EOF { - errorChan <- fmt.Errorf("Error reading from error stream: %s", err) - return - } - if len(message) > 0 { - errorChan <- fmt.Errorf("Error executing remote command: %s", message) - return - } - }() - - if e.stdin != nil { - // TODO this goroutine will never exit cleanly (the io.Copy never unblocks) - // because stdin is not closed until the process exits. If we try to call - // stdin.Close(), it returns no error but doesn't unblock the copy. It will - // exit when the process exits, instead. - go cp(api.StreamTypeStdin, remoteStdin, e.stdin) - } - - waitCount := 0 - completedStreams := 0 - - if e.stdout != nil { - waitCount++ - go cp(api.StreamTypeStdout, e.stdout, remoteStdout) - } - - if e.stderr != nil && !e.tty { - waitCount++ - go cp(api.StreamTypeStderr, e.stderr, remoteStderr) - } - -Loop: - for { - select { - case <-doneChan: - completedStreams++ - if completedStreams == waitCount { - break Loop - } - case err := <-errorChan: - return err - } - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/v2.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/v2.go deleted file mode 100644 index 67e8637cf..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/remotecommand/v2.go +++ /dev/null @@ -1,166 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package remotecommand - -import ( - "fmt" - "io" - "io/ioutil" - "net/http" - "sync" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/util/httpstream" - "k8s.io/kubernetes/pkg/util/runtime" -) - -// streamProtocolV2 implements version 2 of the streaming protocol for attach -// and exec. The original streaming protocol was unversioned. As a result, this -// version is referred to as version 2, even though it is the first actual -// numbered version. -type streamProtocolV2 struct { - stdin io.Reader - stdout io.Writer - stderr io.Writer - tty bool -} - -var _ streamProtocolHandler = &streamProtocolV2{} - -func (e *streamProtocolV2) stream(conn httpstream.Connection) error { - var ( - err error - errorStream, remoteStdin, remoteStdout, remoteStderr httpstream.Stream - ) - - headers := http.Header{} - - // set up all the streams first - // set up error stream - errorChan := make(chan error) - headers.Set(api.StreamType, api.StreamTypeError) - errorStream, err = conn.CreateStream(headers) - if err != nil { - return err - } - - // set up stdin stream - if e.stdin != nil { - headers.Set(api.StreamType, api.StreamTypeStdin) - remoteStdin, err = conn.CreateStream(headers) - if err != nil { - return err - } - } - - // set up stdout stream - if e.stdout != nil { - headers.Set(api.StreamType, api.StreamTypeStdout) - remoteStdout, err = conn.CreateStream(headers) - if err != nil { - return err - } - } - - // set up stderr stream - if e.stderr != nil && !e.tty { - headers.Set(api.StreamType, api.StreamTypeStderr) - remoteStderr, err = conn.CreateStream(headers) - if err != nil { - return err - } - } - - // now that all the streams have been created, proceed with reading & copying - - // always read from errorStream - go func() { - message, err := ioutil.ReadAll(errorStream) - switch { - case err != nil && err != io.EOF: - errorChan <- fmt.Errorf("error reading from error stream: %s", err) - case len(message) > 0: - errorChan <- fmt.Errorf("error executing remote command: %s", message) - default: - errorChan <- nil - } - close(errorChan) - }() - - var wg sync.WaitGroup - var once sync.Once - - if e.stdin != nil { - // copy from client's stdin to container's stdin - go func() { - // if e.stdin is noninteractive, e.g. `echo abc | kubectl exec -i -- cat`, make sure - // we close remoteStdin as soon as the copy from e.stdin to remoteStdin finishes. Otherwise - // the executed command will remain running. - defer once.Do(func() { remoteStdin.Close() }) - - if _, err := io.Copy(remoteStdin, e.stdin); err != nil { - runtime.HandleError(err) - } - }() - - // read from remoteStdin until the stream is closed. this is essential to - // be able to exit interactive sessions cleanly and not leak goroutines or - // hang the client's terminal. - // - // go-dockerclient's current hijack implementation - // (https://github.com/fsouza/go-dockerclient/blob/89f3d56d93788dfe85f864a44f85d9738fca0670/client.go#L564) - // waits for all three streams (stdin/stdout/stderr) to finish copying - // before returning. When hijack finishes copying stdout/stderr, it calls - // Close() on its side of remoteStdin, which allows this copy to complete. - // When that happens, we must Close() on our side of remoteStdin, to - // allow the copy in hijack to complete, and hijack to return. - go func() { - defer once.Do(func() { remoteStdin.Close() }) - // this "copy" doesn't actually read anything - it's just here to wait for - // the server to close remoteStdin. - if _, err := io.Copy(ioutil.Discard, remoteStdin); err != nil { - runtime.HandleError(err) - } - }() - } - - if e.stdout != nil { - wg.Add(1) - go func() { - defer wg.Done() - if _, err := io.Copy(e.stdout, remoteStdout); err != nil { - runtime.HandleError(err) - } - }() - } - - if e.stderr != nil && !e.tty { - wg.Add(1) - go func() { - defer wg.Done() - if _, err := io.Copy(e.stderr, remoteStderr); err != nil { - runtime.HandleError(err) - } - }() - } - - // we're waiting for stdout/stderr to finish copying - wg.Wait() - - // waits for errorStream to finish reading with an error or nil - return <-errorChan -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/replica_sets_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/replica_sets_test.go deleted file mode 100644 index 960baae04..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/replica_sets_test.go +++ /dev/null @@ -1,197 +0,0 @@ -/* -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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/extensions" -) - -func getReplicaSetResourceName() string { - return "replicasets" -} - -func TestListReplicaSets(t *testing.T) { - ns := api.NamespaceAll - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getReplicaSetResourceName(), ns, ""), - }, - Response: simple.Response{StatusCode: 200, - Body: &extensions.ReplicaSetList{ - Items: []extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - }, - }, - } - receivedRSList, err := c.Setup(t).Extensions().ReplicaSets(ns).List(api.ListOptions{}) - c.Validate(t, receivedRSList, err) -} - -func TestGetReplicaSet(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Extensions.ResourcePath(getReplicaSetResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - } - receivedRS, err := c.Setup(t).Extensions().ReplicaSets(ns).Get("foo") - c.Validate(t, receivedRS, err) -} - -func TestGetReplicaSetWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedPod, err := c.Setup(t).Extensions().ReplicaSets(ns).Get("") - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedPod, err) -} - -func TestUpdateReplicaSet(t *testing.T) { - ns := api.NamespaceDefault - requestRS := &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Extensions.ResourcePath(getReplicaSetResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - } - receivedRS, err := c.Setup(t).Extensions().ReplicaSets(ns).Update(requestRS) - c.Validate(t, receivedRS, err) -} - -func TestUpdateStatusReplicaSet(t *testing.T) { - ns := api.NamespaceDefault - requestRS := &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Extensions.ResourcePath(getReplicaSetResourceName(), ns, "foo") + "/status", Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - Status: extensions.ReplicaSetStatus{ - Replicas: 2, - }, - }, - }, - } - receivedRS, err := c.Setup(t).Extensions().ReplicaSets(ns).UpdateStatus(requestRS) - c.Validate(t, receivedRS, err) -} -func TestDeleteReplicaSet(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Extensions.ResourcePath(getReplicaSetResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Extensions().ReplicaSets(ns).Delete("foo", nil) - c.Validate(t, nil, err) -} - -func TestCreateReplicaSet(t *testing.T) { - ns := api.NamespaceDefault - requestRS := &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "POST", Path: testapi.Extensions.ResourcePath(getReplicaSetResourceName(), ns, ""), Body: requestRS, Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - } - receivedRS, err := c.Setup(t).Extensions().ReplicaSets(ns).Create(requestRS) - c.Validate(t, receivedRS, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/replication_controllers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/replication_controllers_test.go deleted file mode 100644 index 151423b92..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/replication_controllers_test.go +++ /dev/null @@ -1,204 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func getRCResourceName() string { - return "replicationcontrollers" -} - -func TestListControllers(t *testing.T) { - ns := api.NamespaceAll - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getRCResourceName(), ns, ""), - }, - Response: simple.Response{StatusCode: 200, - Body: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - }, - }, - } - receivedControllerList, err := c.Setup(t).ReplicationControllers(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, receivedControllerList, err) - -} - -func TestGetController(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Default.ResourcePath(getRCResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - } - receivedController, err := c.Setup(t).ReplicationControllers(ns).Get("foo") - defer c.Close() - c.Validate(t, receivedController, err) -} - -func TestGetControllerWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedPod, err := c.Setup(t).ReplicationControllers(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedPod, err) -} - -func TestUpdateController(t *testing.T) { - ns := api.NamespaceDefault - requestController := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath(getRCResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - } - receivedController, err := c.Setup(t).ReplicationControllers(ns).Update(requestController) - defer c.Close() - c.Validate(t, receivedController, err) -} - -func TestUpdateStatusController(t *testing.T) { - ns := api.NamespaceDefault - requestController := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath(getRCResourceName(), ns, "foo") + "/status", Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - Status: api.ReplicationControllerStatus{ - Replicas: 2, - }, - }, - }, - } - receivedController, err := c.Setup(t).ReplicationControllers(ns).UpdateStatus(requestController) - defer c.Close() - c.Validate(t, receivedController, err) -} -func TestDeleteController(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath(getRCResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).ReplicationControllers(ns).Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestCreateController(t *testing.T) { - ns := api.NamespaceDefault - requestController := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "POST", Path: testapi.Default.ResourcePath(getRCResourceName(), ns, ""), Body: requestController, Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{}, - }, - }, - }, - } - receivedController, err := c.Setup(t).ReplicationControllers(ns).Create(requestController) - defer c.Close() - c.Validate(t, receivedController, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/request_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/request_test.go deleted file mode 100644 index 266be6b24..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/request_test.go +++ /dev/null @@ -1,1313 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - apierrors "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/httpstream" - "k8s.io/kubernetes/pkg/util/intstr" - utiltesting "k8s.io/kubernetes/pkg/util/testing" - "k8s.io/kubernetes/pkg/watch" - watchjson "k8s.io/kubernetes/pkg/watch/json" -) - -func TestNewRequestSetsAccept(t *testing.T) { - r := NewRequest(nil, "get", &url.URL{Path: "/path/"}, "", ContentConfig{}, nil, nil) - if r.headers.Get("Accept") != "" { - t.Errorf("unexpected headers: %#v", r.headers) - } - r = NewRequest(nil, "get", &url.URL{Path: "/path/"}, "", ContentConfig{ContentType: "application/other"}, nil, nil) - if r.headers.Get("Accept") != "application/other, */*" { - t.Errorf("unexpected headers: %#v", r.headers) - } -} - -func TestRequestWithErrorWontChange(t *testing.T) { - original := Request{ - err: errors.New("test"), - content: ContentConfig{GroupVersion: testapi.Default.GroupVersion()}, - } - r := original - changed := r.Param("foo", "bar"). - LabelsSelectorParam(labels.Set{"a": "b"}.AsSelector()). - UintParam("uint", 1). - AbsPath("/abs"). - Prefix("test"). - Suffix("testing"). - Namespace("new"). - Resource("foos"). - Name("bars"). - Body("foo"). - Timeout(time.Millisecond) - if changed != &r { - t.Errorf("returned request should point to the same object") - } - if !reflect.DeepEqual(changed, &original) { - t.Errorf("expected %#v, got %#v", &original, changed) - } -} - -func TestRequestPreservesBaseTrailingSlash(t *testing.T) { - r := &Request{baseURL: &url.URL{}, pathPrefix: "/path/"} - if s := r.URL().String(); s != "/path/" { - t.Errorf("trailing slash should be preserved: %s", s) - } -} - -func TestRequestAbsPathPreservesTrailingSlash(t *testing.T) { - r := (&Request{baseURL: &url.URL{}}).AbsPath("/foo/") - if s := r.URL().String(); s != "/foo/" { - t.Errorf("trailing slash should be preserved: %s", s) - } - - r = (&Request{baseURL: &url.URL{}}).AbsPath("/foo/") - if s := r.URL().String(); s != "/foo/" { - t.Errorf("trailing slash should be preserved: %s", s) - } -} - -func TestRequestAbsPathJoins(t *testing.T) { - r := (&Request{baseURL: &url.URL{}}).AbsPath("foo/bar", "baz") - if s := r.URL().String(); s != "foo/bar/baz" { - t.Errorf("trailing slash should be preserved: %s", s) - } -} - -func TestRequestSetsNamespace(t *testing.T) { - r := (&Request{ - baseURL: &url.URL{ - Path: "/", - }, - }).Namespace("foo") - if r.namespace == "" { - t.Errorf("namespace should be set: %#v", r) - } - - if s := r.URL().String(); s != "namespaces/foo" { - t.Errorf("namespace should be in path: %s", s) - } -} - -func TestRequestOrdersNamespaceInPath(t *testing.T) { - r := (&Request{ - baseURL: &url.URL{}, - pathPrefix: "/test/", - }).Name("bar").Resource("baz").Namespace("foo") - if s := r.URL().String(); s != "/test/namespaces/foo/baz/bar" { - t.Errorf("namespace should be in order in path: %s", s) - } -} - -func TestRequestOrdersSubResource(t *testing.T) { - r := (&Request{ - baseURL: &url.URL{}, - pathPrefix: "/test/", - }).Name("bar").Resource("baz").Namespace("foo").Suffix("test").SubResource("a", "b") - if s := r.URL().String(); s != "/test/namespaces/foo/baz/bar/a/b/test" { - t.Errorf("namespace should be in order in path: %s", s) - } -} - -func TestRequestSetTwiceError(t *testing.T) { - if (&Request{}).Name("bar").Name("baz").err == nil { - t.Errorf("setting name twice should result in error") - } - if (&Request{}).Namespace("bar").Namespace("baz").err == nil { - t.Errorf("setting namespace twice should result in error") - } - if (&Request{}).Resource("bar").Resource("baz").err == nil { - t.Errorf("setting resource twice should result in error") - } - if (&Request{}).SubResource("bar").SubResource("baz").err == nil { - t.Errorf("setting subresource twice should result in error") - } -} - -func TestInvalidSegments(t *testing.T) { - invalidSegments := []string{".", "..", "test/segment", "test%2bsegment"} - setters := map[string]func(string, *Request){ - "namespace": func(s string, r *Request) { r.Namespace(s) }, - "resource": func(s string, r *Request) { r.Resource(s) }, - "name": func(s string, r *Request) { r.Name(s) }, - "subresource": func(s string, r *Request) { r.SubResource(s) }, - } - for _, invalidSegment := range invalidSegments { - for setterName, setter := range setters { - r := &Request{} - setter(invalidSegment, r) - if r.err == nil { - t.Errorf("%s: %s: expected error, got none", setterName, invalidSegment) - } - } - } -} - -func TestRequestParam(t *testing.T) { - r := (&Request{}).Param("foo", "a") - if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}}) { - t.Errorf("should have set a param: %#v", r) - } - - r.Param("bar", "1") - r.Param("bar", "2") - if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}, "bar": []string{"1", "2"}}) { - t.Errorf("should have set a param: %#v", r) - } -} - -func TestRequestVersionedParams(t *testing.T) { - r := (&Request{content: ContentConfig{GroupVersion: &v1.SchemeGroupVersion}}).Param("foo", "a") - if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}}) { - t.Errorf("should have set a param: %#v", r) - } - r.VersionedParams(&api.PodLogOptions{Follow: true, Container: "bar"}, api.ParameterCodec) - - if !reflect.DeepEqual(r.params, url.Values{ - "foo": []string{"a"}, - "container": []string{"bar"}, - "follow": []string{"true"}, - }) { - t.Errorf("should have set a param: %#v", r) - } -} - -func TestRequestVersionedParamsFromListOptions(t *testing.T) { - r := &Request{content: ContentConfig{GroupVersion: &v1.SchemeGroupVersion}} - r.VersionedParams(&api.ListOptions{ResourceVersion: "1"}, api.ParameterCodec) - if !reflect.DeepEqual(r.params, url.Values{ - "resourceVersion": []string{"1"}, - }) { - t.Errorf("should have set a param: %#v", r) - } - - var timeout int64 = 10 - r.VersionedParams(&api.ListOptions{ResourceVersion: "2", TimeoutSeconds: &timeout}, api.ParameterCodec) - if !reflect.DeepEqual(r.params, url.Values{ - "resourceVersion": []string{"1", "2"}, - "timeoutSeconds": []string{"10"}, - }) { - t.Errorf("should have set a param: %#v", r) - } -} - -func TestRequestURI(t *testing.T) { - r := (&Request{}).Param("foo", "a") - r.Prefix("other") - r.RequestURI("/test?foo=b&a=b&c=1&c=2") - if r.pathPrefix != "/test" { - t.Errorf("path is wrong: %#v", r) - } - if !reflect.DeepEqual(r.params, url.Values{"a": []string{"b"}, "foo": []string{"b"}, "c": []string{"1", "2"}}) { - t.Errorf("should have set a param: %#v", r) - } -} - -type NotAnAPIObject struct{} - -func (obj NotAnAPIObject) GroupVersionKind() *unversioned.GroupVersionKind { return nil } -func (obj NotAnAPIObject) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) {} - -func TestRequestBody(t *testing.T) { - // test unknown type - r := (&Request{}).Body([]string{"test"}) - if r.err == nil || r.body != nil { - t.Errorf("should have set err and left body nil: %#v", r) - } - - // test error set when failing to read file - f, err := ioutil.TempFile("", "test") - if err != nil { - t.Fatalf("unable to create temp file") - } - defer f.Close() - os.Remove(f.Name()) - r = (&Request{}).Body(f.Name()) - if r.err == nil || r.body != nil { - t.Errorf("should have set err and left body nil: %#v", r) - } - - // test unencodable api object - r = (&Request{content: ContentConfig{Codec: testapi.Default.Codec()}}).Body(&NotAnAPIObject{}) - if r.err == nil || r.body != nil { - t.Errorf("should have set err and left body nil: %#v", r) - } -} - -func TestResultIntoWithErrReturnsErr(t *testing.T) { - res := Result{err: errors.New("test")} - if err := res.Into(&api.Pod{}); err != res.err { - t.Errorf("should have returned exact error from result") - } -} - -func TestURLTemplate(t *testing.T) { - uri, _ := url.Parse("http://localhost") - r := NewRequest(nil, "POST", uri, "", ContentConfig{GroupVersion: &unversioned.GroupVersion{Group: "test"}}, nil, nil) - r.Prefix("pre1").Resource("r1").Namespace("ns").Name("nm").Param("p0", "v0") - full := r.URL() - if full.String() != "http://localhost/pre1/namespaces/ns/r1/nm?p0=v0" { - t.Errorf("unexpected initial URL: %s", full) - } - actual := r.finalURLTemplate() - expected := "http://localhost/pre1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D?p0=%7Bvalue%7D" - if actual != expected { - t.Errorf("unexpected URL template: %s %s", actual, expected) - } - if r.URL().String() != full.String() { - t.Errorf("creating URL template changed request: %s -> %s", full.String(), r.URL().String()) - } -} - -func TestTransformResponse(t *testing.T) { - invalid := []byte("aaaaa") - uri, _ := url.Parse("http://localhost") - testCases := []struct { - Response *http.Response - Data []byte - Created bool - Error bool - ErrFn func(err error) bool - }{ - {Response: &http.Response{StatusCode: 200}, Data: []byte{}}, - {Response: &http.Response{StatusCode: 201}, Data: []byte{}, Created: true}, - {Response: &http.Response{StatusCode: 199}, Error: true}, - {Response: &http.Response{StatusCode: 500}, Error: true}, - {Response: &http.Response{StatusCode: 422}, Error: true}, - {Response: &http.Response{StatusCode: 409}, Error: true}, - {Response: &http.Response{StatusCode: 404}, Error: true}, - {Response: &http.Response{StatusCode: 401}, Error: true}, - { - Response: &http.Response{ - StatusCode: 401, - Header: http.Header{"Content-Type": []string{"application/json"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Error: true, - ErrFn: func(err error) bool { - return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err) - }, - }, - { - Response: &http.Response{ - StatusCode: 401, - Header: http.Header{"Content-Type": []string{"text/any"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Error: true, - ErrFn: func(err error) bool { - return strings.Contains(err.Error(), "server has asked for the client to provide") && apierrors.IsUnauthorized(err) - }, - }, - {Response: &http.Response{StatusCode: 403}, Error: true}, - {Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, - {Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, - } - for i, test := range testCases { - r := NewRequest(nil, "", uri, "", ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec()}, nil, nil) - if test.Response.Body == nil { - test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - } - result := r.transformResponse(test.Response, &http.Request{}) - response, created, err := result.body, result.statusCode == http.StatusCreated, result.err - hasErr := err != nil - if hasErr != test.Error { - t.Errorf("%d: unexpected error: %t %v", i, test.Error, err) - } else if hasErr && test.Response.StatusCode > 399 { - status, ok := err.(apierrors.APIStatus) - if !ok { - t.Errorf("%d: response should have been transformable into APIStatus: %v", i, err) - continue - } - if int(status.Status().Code) != test.Response.StatusCode { - t.Errorf("%d: status code did not match response: %#v", i, status.Status()) - } - } - if test.ErrFn != nil && !test.ErrFn(err) { - t.Errorf("%d: error function did not match: %v", i, err) - } - if !(test.Data == nil && response == nil) && !api.Semantic.DeepDerivative(test.Data, response) { - t.Errorf("%d: unexpected response: %#v %#v", i, test.Data, response) - } - if test.Created != created { - t.Errorf("%d: expected created %t, got %t", i, test.Created, created) - } - } -} - -func TestTransformUnstructuredError(t *testing.T) { - testCases := []struct { - Req *http.Request - Res *http.Response - - Resource string - Name string - - ErrFn func(error) bool - }{ - { - Resource: "foo", - Name: "bar", - Req: &http.Request{ - Method: "POST", - }, - Res: &http.Response{ - StatusCode: http.StatusConflict, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsAlreadyExists, - }, - { - Resource: "foo", - Name: "bar", - Req: &http.Request{ - Method: "PUT", - }, - Res: &http.Response{ - StatusCode: http.StatusConflict, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsConflict, - }, - { - Resource: "foo", - Name: "bar", - Req: &http.Request{}, - Res: &http.Response{ - StatusCode: http.StatusNotFound, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsNotFound, - }, - { - Req: &http.Request{}, - Res: &http.Response{ - StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsBadRequest, - }, - } - - for _, testCase := range testCases { - r := &Request{ - content: ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec()}, - resourceName: testCase.Name, - resource: testCase.Resource, - } - result := r.transformResponse(testCase.Res, testCase.Req) - err := result.err - if !testCase.ErrFn(err) { - t.Errorf("unexpected error: %v", err) - continue - } - if len(testCase.Name) != 0 && !strings.Contains(err.Error(), testCase.Name) { - t.Errorf("unexpected error string: %s", err) - } - if len(testCase.Resource) != 0 && !strings.Contains(err.Error(), testCase.Resource) { - t.Errorf("unexpected error string: %s", err) - } - } -} - -type clientFunc func(req *http.Request) (*http.Response, error) - -func (f clientFunc) Do(req *http.Request) (*http.Response, error) { - return f(req) -} - -func TestRequestWatch(t *testing.T) { - testCases := []struct { - Request *Request - Err bool - ErrFn func(error) bool - Empty bool - }{ - { - Request: &Request{err: errors.New("bail")}, - Err: true, - }, - { - Request: &Request{baseURL: &url.URL{}, pathPrefix: "%"}, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("err") - }), - baseURL: &url.URL{}, - }, - Err: true, - }, - { - Request: &Request{ - content: ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec()}, - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusForbidden, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - }, nil - }), - baseURL: &url.URL{}, - }, - Err: true, - ErrFn: func(err error) bool { - return apierrors.IsForbidden(err) - }, - }, - { - Request: &Request{ - content: ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec()}, - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - }, nil - }), - baseURL: &url.URL{}, - }, - Err: true, - ErrFn: func(err error) bool { - return apierrors.IsUnauthorized(err) - }, - }, - { - Request: &Request{ - content: ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec()}, - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), &unversioned.Status{ - Status: unversioned.StatusFailure, - Reason: unversioned.StatusReasonUnauthorized, - })))), - }, nil - }), - baseURL: &url.URL{}, - }, - Err: true, - ErrFn: func(err error) bool { - return apierrors.IsUnauthorized(err) - }, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, io.EOF - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, &url.Error{Err: io.EOF} - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("http: can't write HTTP request on broken connection") - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("foo: connection reset by peer") - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - } - for i, testCase := range testCases { - t.Logf("testcase %v", testCase.Request) - testCase.Request.backoffMgr = &NoBackoff{} - watch, err := testCase.Request.Watch() - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err) - continue - } - if testCase.ErrFn != nil && !testCase.ErrFn(err) { - t.Errorf("%d: error not valid: %v", i, err) - } - if hasErr && watch != nil { - t.Errorf("%d: watch should be nil when error is returned", i) - continue - } - if testCase.Empty { - _, ok := <-watch.ResultChan() - if ok { - t.Errorf("%d: expected the watch to be empty: %#v", i, watch) - } - } - } -} - -func TestRequestStream(t *testing.T) { - testCases := []struct { - Request *Request - Err bool - }{ - { - Request: &Request{err: errors.New("bail")}, - Err: true, - }, - { - Request: &Request{baseURL: &url.URL{}, pathPrefix: "%"}, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("err") - }), - baseURL: &url.URL{}, - }, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), &unversioned.Status{ - Status: unversioned.StatusFailure, - Reason: unversioned.StatusReasonUnauthorized, - })))), - }, nil - }), - content: ContentConfig{Codec: testapi.Default.Codec()}, - baseURL: &url.URL{}, - }, - Err: true, - }, - } - for i, testCase := range testCases { - testCase.Request.backoffMgr = &NoBackoff{} - body, err := testCase.Request.Stream() - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err) - } - if hasErr && body != nil { - t.Errorf("%d: body should be nil when error is returned", i) - } - } -} - -type fakeUpgradeConnection struct{} - -func (c *fakeUpgradeConnection) CreateStream(headers http.Header) (httpstream.Stream, error) { - return nil, nil -} -func (c *fakeUpgradeConnection) Close() error { - return nil -} -func (c *fakeUpgradeConnection) CloseChan() <-chan bool { - return make(chan bool) -} -func (c *fakeUpgradeConnection) SetIdleTimeout(timeout time.Duration) { -} - -type fakeUpgradeRoundTripper struct { - req *http.Request - conn httpstream.Connection -} - -func (f *fakeUpgradeRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - f.req = req - b := []byte{} - body := ioutil.NopCloser(bytes.NewReader(b)) - resp := &http.Response{ - StatusCode: 101, - Body: body, - } - return resp, nil -} - -func (f *fakeUpgradeRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) { - return f.conn, nil -} - -func TestRequestDo(t *testing.T) { - testCases := []struct { - Request *Request - Err bool - }{ - { - Request: &Request{err: errors.New("bail")}, - Err: true, - }, - { - Request: &Request{baseURL: &url.URL{}, pathPrefix: "%"}, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("err") - }), - baseURL: &url.URL{}, - }, - Err: true, - }, - } - for i, testCase := range testCases { - testCase.Request.backoffMgr = &NoBackoff{} - body, err := testCase.Request.Do().Raw() - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err) - } - if hasErr && body != nil { - t.Errorf("%d: body should be nil when error is returned", i) - } - } -} - -func TestDoRequestNewWay(t *testing.T) { - reqBody := "request body" - expectedObj := &api.Service{Spec: api.ServiceSpec{Ports: []api.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c := testRESTClient(t, testServer) - obj, err := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(reqBody)). - Do().Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !api.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - requestURL := testapi.Default.ResourcePathWithPrefix("foo/bar", "", "", "baz") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &reqBody) -} - -// This test assumes that the client implementation backs off exponentially, for an individual request. -func TestBackoffLifecycle(t *testing.T) { - count := 0 - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - count++ - t.Logf("Attempt %d", count) - if count == 5 || count == 9 { - w.WriteHeader(http.StatusOK) - return - } else { - w.WriteHeader(http.StatusGatewayTimeout) - return - } - })) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c := testRESTClient(t, testServer) - - // Test backoff recovery and increase. This correlates to the constants - // which are used in the server implementation returning StatusOK above. - seconds := []int{0, 1, 2, 4, 8, 0, 1, 2, 4, 0} - request := c.Verb("POST").Prefix("backofftest").Suffix("abc") - request.backoffMgr = &URLBackoff{ - Backoff: util.NewBackOff( - time.Duration(1)*time.Second, - time.Duration(200)*time.Second)} - for _, sec := range seconds { - start := time.Now() - request.DoRaw() - finish := time.Since(start) - t.Logf("%v finished in %v", sec, finish) - if finish < time.Duration(sec)*time.Second || finish >= time.Duration(sec+5)*time.Second { - t.Fatalf("%v not in range %v", finish, sec) - } - } -} - -func TestCheckRetryClosesBody(t *testing.T) { - count := 0 - ch := make(chan struct{}) - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - count++ - t.Logf("attempt %d", count) - if count >= 5 { - w.WriteHeader(http.StatusOK) - close(ch) - return - } - w.Header().Set("Retry-After", "0") - w.WriteHeader(apierrors.StatusTooManyRequests) - })) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - - c := testRESTClient(t, testServer) - _, err := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(strings.Repeat("abcd", 1000))). - DoRaw() - if err != nil { - t.Fatalf("Unexpected error: %v %#v", err, err) - } - <-ch - if count != 5 { - t.Errorf("unexpected retries: %d", count) - } -} - -func TestCheckRetryHandles429And5xx(t *testing.T) { - count := 0 - ch := make(chan struct{}) - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - t.Logf("attempt %d", count) - if count >= 4 { - w.WriteHeader(http.StatusOK) - close(ch) - return - } - w.Header().Set("Retry-After", "0") - w.WriteHeader([]int{apierrors.StatusTooManyRequests, 500, 501, 504}[count]) - count++ - })) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - - c := testRESTClient(t, testServer) - _, err := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(strings.Repeat("abcd", 1000))). - DoRaw() - if err != nil { - t.Fatalf("Unexpected error: %v %#v", err, err) - } - <-ch - if count != 4 { - t.Errorf("unexpected retries: %d", count) - } -} - -func BenchmarkCheckRetryClosesBody(b *testing.B) { - count := 0 - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - count++ - if count%3 == 0 { - w.WriteHeader(http.StatusOK) - return - } - w.Header().Set("Retry-After", "0") - w.WriteHeader(apierrors.StatusTooManyRequests) - })) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - - c := testRESTClient(b, testServer) - r := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(strings.Repeat("abcd", 1000))) - - for i := 0; i < b.N; i++ { - if _, err := r.DoRaw(); err != nil { - b.Fatalf("Unexpected error: %v %#v", err, err) - } - } -} - -func TestDoRequestNewWayReader(t *testing.T) { - reqObj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}} - reqBodyExpected, _ := runtime.Encode(testapi.Default.Codec(), reqObj) - expectedObj := &api.Service{Spec: api.ServiceSpec{Ports: []api.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c := testRESTClient(t, testServer) - obj, err := c.Verb("POST"). - Resource("bar"). - Name("baz"). - Prefix("foo"). - LabelsSelectorParam(labels.Set{"name": "foo"}.AsSelector()). - Timeout(time.Second). - Body(bytes.NewBuffer(reqBodyExpected)). - Do().Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !api.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - tmpStr := string(reqBodyExpected) - requestURL := testapi.Default.ResourcePathWithPrefix("foo", "bar", "", "baz") - requestURL += "?" + unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) + "=name%3Dfoo&timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr) -} - -func TestDoRequestNewWayObj(t *testing.T) { - reqObj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}} - reqBodyExpected, _ := runtime.Encode(testapi.Default.Codec(), reqObj) - expectedObj := &api.Service{Spec: api.ServiceSpec{Ports: []api.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c := testRESTClient(t, testServer) - obj, err := c.Verb("POST"). - Suffix("baz"). - Name("bar"). - Resource("foo"). - LabelsSelectorParam(labels.Set{"name": "foo"}.AsSelector()). - Timeout(time.Second). - Body(reqObj). - Do().Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !api.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - tmpStr := string(reqBodyExpected) - requestURL := testapi.Default.ResourcePath("foo", "", "bar/baz") - requestURL += "?" + unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) + "=name%3Dfoo&timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr) -} - -func TestDoRequestNewWayFile(t *testing.T) { - reqObj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}} - reqBodyExpected, err := runtime.Encode(testapi.Default.Codec(), reqObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - file, err := ioutil.TempFile("", "foo") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - defer file.Close() - - _, err = file.Write(reqBodyExpected) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - expectedObj := &api.Service{Spec: api.ServiceSpec{Ports: []api.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c := testRESTClient(t, testServer) - wasCreated := true - obj, err := c.Verb("POST"). - Prefix("foo/bar", "baz"). - Timeout(time.Second). - Body(file.Name()). - Do().WasCreated(&wasCreated).Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !api.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - if wasCreated { - t.Errorf("expected object was not created") - } - tmpStr := string(reqBodyExpected) - requestURL := testapi.Default.ResourcePathWithPrefix("foo/bar/baz", "", "", "") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr) -} - -func TestWasCreated(t *testing.T) { - reqObj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}} - reqBodyExpected, err := runtime.Encode(testapi.Default.Codec(), reqObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - expectedObj := &api.Service{Spec: api.ServiceSpec{Ports: []api.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 201, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c := testRESTClient(t, testServer) - wasCreated := false - obj, err := c.Verb("PUT"). - Prefix("foo/bar", "baz"). - Timeout(time.Second). - Body(reqBodyExpected). - Do().WasCreated(&wasCreated).Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !api.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - if !wasCreated { - t.Errorf("Expected object was created") - } - - tmpStr := string(reqBodyExpected) - requestURL := testapi.Default.ResourcePathWithPrefix("foo/bar/baz", "", "", "") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "PUT", &tmpStr) -} - -func TestVerbs(t *testing.T) { - c := testRESTClient(t, nil) - if r := c.Post(); r.verb != "POST" { - t.Errorf("Post verb is wrong") - } - if r := c.Put(); r.verb != "PUT" { - t.Errorf("Put verb is wrong") - } - if r := c.Get(); r.verb != "GET" { - t.Errorf("Get verb is wrong") - } - if r := c.Delete(); r.verb != "DELETE" { - t.Errorf("Delete verb is wrong") - } -} - -func TestAbsPath(t *testing.T) { - for i, tc := range []struct { - configPrefix string - resourcePrefix string - absPath string - wantsAbsPath string - }{ - {"", "", "", "/"}, - {"", "", "/", "/"}, - {"", "", "/api", "/api"}, - {"", "", "/api/", "/api/"}, - {"", "", "/apis", "/apis"}, - {"", "/foo", "/bar/foo", "/bar/foo"}, - {"", "/api/foo/123", "/bar/foo", "/bar/foo"}, - {"/p1", "", "", "/p1"}, - {"/p1", "", "/", "/p1/"}, - {"/p1", "", "/api", "/p1/api"}, - {"/p1", "", "/apis", "/p1/apis"}, - {"/p1", "/r1", "/apis", "/p1/apis"}, - {"/p1", "/api/r1", "/apis", "/p1/apis"}, - {"/p1/api/p2", "", "", "/p1/api/p2"}, - {"/p1/api/p2", "", "/", "/p1/api/p2/"}, - {"/p1/api/p2", "", "/api", "/p1/api/p2/api"}, - {"/p1/api/p2", "", "/api/", "/p1/api/p2/api/"}, - {"/p1/api/p2", "/r1", "/api/", "/p1/api/p2/api/"}, - {"/p1/api/p2", "/api/r1", "/api/", "/p1/api/p2/api/"}, - } { - c := NewOrDie(&Config{Host: "http://localhost:123" + tc.configPrefix}) - r := c.Post().Prefix(tc.resourcePrefix).AbsPath(tc.absPath) - if r.pathPrefix != tc.wantsAbsPath { - t.Errorf("test case %d failed, unexpected path: %q, expected %q", i, r.pathPrefix, tc.wantsAbsPath) - } - } -} - -func TestUintParam(t *testing.T) { - table := []struct { - name string - testVal uint64 - expectStr string - }{ - {"foo", 31415, "http://localhost?foo=31415"}, - {"bar", 42, "http://localhost?bar=42"}, - {"baz", 0, "http://localhost?baz=0"}, - } - - for _, item := range table { - u, _ := url.Parse("http://localhost") - r := NewRequest(nil, "GET", u, "", ContentConfig{GroupVersion: &unversioned.GroupVersion{Group: "test"}}, nil, nil).AbsPath("").UintParam(item.name, item.testVal) - if e, a := item.expectStr, r.URL().String(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - } -} - -func TestUnacceptableParamNames(t *testing.T) { - table := []struct { - name string - testVal string - expectSuccess bool - }{ - {"timeout", "42", false}, - } - - for _, item := range table { - c := testRESTClient(t, nil) - r := c.Get().setParam(item.name, item.testVal) - if e, a := item.expectSuccess, r.err == nil; e != a { - t.Errorf("expected %v, got %v (%v)", e, a, r.err) - } - } -} - -func TestBody(t *testing.T) { - const data = "test payload" - - obj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}} - bodyExpected, _ := runtime.Encode(testapi.Default.Codec(), obj) - - f, err := ioutil.TempFile("", "test_body") - if err != nil { - t.Fatalf("TempFile error: %v", err) - } - if _, err := f.WriteString(data); err != nil { - t.Fatalf("TempFile.WriteString error: %v", err) - } - f.Close() - - var nilObject *api.DeleteOptions - typedObject := interface{}(nilObject) - c := testRESTClient(t, nil) - tests := []struct { - input interface{} - expected string - headers map[string]string - }{ - {[]byte(data), data, nil}, - {f.Name(), data, nil}, - {strings.NewReader(data), data, nil}, - {obj, string(bodyExpected), map[string]string{"Content-Type": "application/json"}}, - {typedObject, "", nil}, - } - for i, tt := range tests { - r := c.Post().Body(tt.input) - if r.err != nil { - t.Errorf("%d: r.Body(%#v) error: %v", i, tt, r.err) - continue - } - if tt.headers != nil { - for k, v := range tt.headers { - if r.headers.Get(k) != v { - t.Errorf("%d: r.headers[%q] = %q; want %q", i, k, v, v) - } - } - } - - if r.body == nil { - if len(tt.expected) != 0 { - t.Errorf("%d: r.body = %q; want %q", i, r.body, tt.expected) - } - continue - } - buf := make([]byte, len(tt.expected)) - if _, err := r.body.Read(buf); err != nil { - t.Errorf("%d: r.body.Read error: %v", i, err) - continue - } - body := string(buf) - if body != tt.expected { - t.Errorf("%d: r.body = %q; want %q", i, body, tt.expected) - } - } -} - -func TestWatch(t *testing.T) { - var table = []struct { - t watch.EventType - obj runtime.Object - }{ - {watch.Added, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "first"}}}, - {watch.Modified, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "second"}}}, - {watch.Deleted, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "last"}}}, - } - - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - flusher, ok := w.(http.Flusher) - if !ok { - panic("need flusher!") - } - - w.Header().Set("Transfer-Encoding", "chunked") - w.WriteHeader(http.StatusOK) - flusher.Flush() - - encoder := watchjson.NewEncoder(w, testapi.Default.Codec()) - for _, item := range table { - if err := encoder.Encode(&watch.Event{Type: item.t, Object: item.obj}); err != nil { - panic(err) - } - flusher.Flush() - } - })) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - - s := testRESTClient(t, testServer) - watching, err := s.Get().Prefix("path/to/watch/thing").Watch() - if err != nil { - t.Fatalf("Unexpected error") - } - - for _, item := range table { - got, ok := <-watching.ResultChan() - if !ok { - t.Fatalf("Unexpected early close") - } - if e, a := item.t, got.Type; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - if e, a := item.obj, got.Object; !api.Semantic.DeepDerivative(e, a) { - t.Errorf("Expected %v, got %v", e, a) - } - } - - _, ok := <-watching.ResultChan() - if ok { - t.Fatal("Unexpected non-close") - } -} - -func TestStream(t *testing.T) { - expectedBody := "expected body" - - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - flusher, ok := w.(http.Flusher) - if !ok { - panic("need flusher!") - } - w.Header().Set("Transfer-Encoding", "chunked") - w.WriteHeader(http.StatusOK) - w.Write([]byte(expectedBody)) - flusher.Flush() - })) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - - s := testRESTClient(t, testServer) - readCloser, err := s.Get().Prefix("path/to/stream/thing").Stream() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - defer readCloser.Close() - buf := new(bytes.Buffer) - buf.ReadFrom(readCloser) - resultBody := buf.String() - - if expectedBody != resultBody { - t.Errorf("Expected %s, got %s", expectedBody, resultBody) - } -} - -func testRESTClient(t testing.TB, srv *httptest.Server) *RESTClient { - baseURL, _ := url.Parse("http://localhost") - if srv != nil { - var err error - baseURL, err = url.Parse(srv.URL) - if err != nil { - t.Fatalf("failed to parse test URL: %v", err) - } - } - versionedAPIPath := testapi.Default.ResourcePath("", "", "") - return NewRESTClient(baseURL, versionedAPIPath, ContentConfig{GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec()}, 0, 0, nil) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/resource_quotas_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/resource_quotas_test.go deleted file mode 100644 index ff8abddce..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/resource_quotas_test.go +++ /dev/null @@ -1,208 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" -) - -func getResourceQuotasResoureName() string { - return "resourcequotas" -} - -func TestResourceQuotaCreate(t *testing.T) { - ns := api.NamespaceDefault - resourceQuota := &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - api.ResourcePods: resource.MustParse("10"), - api.ResourceServices: resource.MustParse("10"), - api.ResourceReplicationControllers: resource.MustParse("10"), - api.ResourceQuotas: resource.MustParse("10"), - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath(getResourceQuotasResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: resourceQuota, - }, - Response: simple.Response{StatusCode: 200, Body: resourceQuota}, - } - - response, err := c.Setup(t).ResourceQuotas(ns).Create(resourceQuota) - defer c.Close() - c.Validate(t, response, err) -} - -func TestResourceQuotaGet(t *testing.T) { - ns := api.NamespaceDefault - resourceQuota := &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - api.ResourcePods: resource.MustParse("10"), - api.ResourceServices: resource.MustParse("10"), - api.ResourceReplicationControllers: resource.MustParse("10"), - api.ResourceQuotas: resource.MustParse("10"), - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getResourceQuotasResoureName(), ns, "abc"), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: resourceQuota}, - } - - response, err := c.Setup(t).ResourceQuotas(ns).Get("abc") - defer c.Close() - c.Validate(t, response, err) -} - -func TestResourceQuotaList(t *testing.T) { - ns := api.NamespaceDefault - - resourceQuotaList := &api.ResourceQuotaList{ - Items: []api.ResourceQuota{ - { - ObjectMeta: api.ObjectMeta{Name: "foo"}, - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath(getResourceQuotasResoureName(), ns, ""), - Query: simple.BuildQueryValues(nil), - Body: nil, - }, - Response: simple.Response{StatusCode: 200, Body: resourceQuotaList}, - } - response, err := c.Setup(t).ResourceQuotas(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestResourceQuotaUpdate(t *testing.T) { - ns := api.NamespaceDefault - resourceQuota := &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - ResourceVersion: "1", - }, - Spec: api.ResourceQuotaSpec{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - api.ResourcePods: resource.MustParse("10"), - api.ResourceServices: resource.MustParse("10"), - api.ResourceReplicationControllers: resource.MustParse("10"), - api.ResourceQuotas: resource.MustParse("10"), - }, - }, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath(getResourceQuotasResoureName(), ns, "abc"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: resourceQuota}, - } - response, err := c.Setup(t).ResourceQuotas(ns).Update(resourceQuota) - defer c.Close() - c.Validate(t, response, err) -} - -func TestResourceQuotaStatusUpdate(t *testing.T) { - ns := api.NamespaceDefault - resourceQuota := &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{ - Name: "abc", - Namespace: "foo", - ResourceVersion: "1", - }, - Status: api.ResourceQuotaStatus{ - Hard: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100"), - api.ResourceMemory: resource.MustParse("10000"), - api.ResourcePods: resource.MustParse("10"), - api.ResourceServices: resource.MustParse("10"), - api.ResourceReplicationControllers: resource.MustParse("10"), - api.ResourceQuotas: resource.MustParse("10"), - }, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Default.ResourcePath(getResourceQuotasResoureName(), ns, "abc") + "/status", - Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: resourceQuota}, - } - response, err := c.Setup(t).ResourceQuotas(ns).UpdateStatus(resourceQuota) - defer c.Close() - c.Validate(t, response, err) -} - -func TestResourceQuotaDelete(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath(getResourceQuotasResoureName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).ResourceQuotas(ns).Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestResourceQuotaWatch(t *testing.T) { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePathWithPrefix("watch", getResourceQuotasResoureName(), "", ""), - Query: url.Values{"resourceVersion": []string{}}}, - Response: simple.Response{StatusCode: 200}, - } - _, err := c.Setup(t).ResourceQuotas(api.NamespaceAll).Watch(api.ListOptions{}) - defer c.Close() - c.Validate(t, nil, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/restclient_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/restclient_test.go deleted file mode 100644 index 912611f4a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/restclient_test.go +++ /dev/null @@ -1,196 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - utiltesting "k8s.io/kubernetes/pkg/util/testing" -) - -func TestDoRequestSuccess(t *testing.T) { - status := &unversioned.Status{Status: unversioned.StatusSuccess} - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), status) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c, err := RESTClientFor(&Config{ - Host: testServer.URL, - ContentConfig: ContentConfig{ - GroupVersion: testapi.Default.GroupVersion(), - Codec: testapi.Default.Codec(), - }, - Username: "user", - Password: "pass", - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - body, err := c.Get().Prefix("test").Do().Raw() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if fakeHandler.RequestReceived.Header["Authorization"] == nil { - t.Errorf("Request is missing authorization header: %#v", fakeHandler.RequestReceived) - } - statusOut, err := runtime.Decode(testapi.Default.Codec(), body) - if err != nil { - t.Errorf("Unexpected error %#v", err) - } - if !reflect.DeepEqual(status, statusOut) { - t.Errorf("Unexpected mis-match. Expected %#v. Saw %#v", status, statusOut) - } - fakeHandler.ValidateRequest(t, "/"+testapi.Default.GroupVersion().String()+"/test", "GET", nil) -} - -func TestDoRequestFailed(t *testing.T) { - status := &unversioned.Status{ - Code: http.StatusNotFound, - Status: unversioned.StatusFailure, - Reason: unversioned.StatusReasonNotFound, - Message: " \"\" not found", - Details: &unversioned.StatusDetails{}, - } - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), status) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 404, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c, err := RESTClientFor(&Config{ - Host: testServer.URL, - ContentConfig: ContentConfig{ - GroupVersion: testapi.Default.GroupVersion(), - Codec: testapi.Default.Codec(), - }, - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - body, err := c.Get().Do().Raw() - if err == nil || body != nil { - t.Errorf("unexpected non-error: %#v", body) - } - ss, ok := err.(errors.APIStatus) - if !ok { - t.Errorf("unexpected error type %v", err) - } - actual := ss.Status() - expected := *status - // The decoder will apply the default Version and Kind to the Status. - expected.APIVersion = "v1" - expected.Kind = "Status" - if !reflect.DeepEqual(&expected, &actual) { - t.Errorf("Unexpected mis-match: %s", util.ObjectDiff(status, &actual)) - } -} - -func TestDoRequestCreated(t *testing.T) { - status := &unversioned.Status{Status: unversioned.StatusSuccess} - expectedBody, _ := runtime.Encode(testapi.Default.Codec(), status) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 201, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - // TODO: Uncomment when fix #19254 - // defer testServer.Close() - c, err := RESTClientFor(&Config{ - Host: testServer.URL, - ContentConfig: ContentConfig{ - GroupVersion: testapi.Default.GroupVersion(), - Codec: testapi.Default.Codec(), - }, - Username: "user", - Password: "pass", - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - created := false - body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw() - if err != nil { - t.Errorf("Unexpected error %#v", err) - } - if !created { - t.Errorf("Expected object to be created") - } - statusOut, err := runtime.Decode(testapi.Default.Codec(), body) - if err != nil { - t.Errorf("Unexpected error %#v", err) - } - if !reflect.DeepEqual(status, statusOut) { - t.Errorf("Unexpected mis-match. Expected %#v. Saw %#v", status, statusOut) - } - fakeHandler.ValidateRequest(t, "/"+testapi.Default.GroupVersion().String()+"/test", "GET", nil) -} - -func TestCreateBackoffManager(t *testing.T) { - - theUrl, _ := url.Parse("http://localhost") - - // 1 second base backoff + duration of 2 seconds -> exponential backoff for requests. - os.Setenv(envBackoffBase, "1") - os.Setenv(envBackoffDuration, "2") - backoff := readExpBackoffConfig() - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - if backoff.CalculateBackoff(theUrl)/time.Second != 2 { - t.Errorf("Backoff env not working.") - } - - // 0 duration -> no backoff. - os.Setenv(envBackoffBase, "1") - os.Setenv(envBackoffDuration, "0") - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - backoff = readExpBackoffConfig() - if backoff.CalculateBackoff(theUrl)/time.Second != 0 { - t.Errorf("Zero backoff duration, but backoff still occuring.") - } - - // No env -> No backoff. - os.Setenv(envBackoffBase, "") - os.Setenv(envBackoffDuration, "") - backoff = readExpBackoffConfig() - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - if backoff.CalculateBackoff(theUrl)/time.Second != 0 { - t.Errorf("Backoff should have been 0.") - } - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/services.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/services.go index 159187dbd..8b40a5d04 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/services.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/services.go @@ -18,6 +18,7 @@ package unversioned import ( "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/util/net" "k8s.io/kubernetes/pkg/watch" ) @@ -36,7 +37,7 @@ type ServiceInterface interface { UpdateStatus(srv *api.Service) (*api.Service, error) Delete(name string) error Watch(opts api.ListOptions) (watch.Interface, error) - ProxyGet(scheme, name, port, path string, params map[string]string) ResponseWrapper + ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper } // services implements ServicesNamespacer interface @@ -106,7 +107,7 @@ func (c *services) Watch(opts api.ListOptions) (watch.Interface, error) { } // ProxyGet returns a response of the service by calling it through the proxy. -func (c *services) ProxyGet(scheme, name, port, path string, params map[string]string) ResponseWrapper { +func (c *services) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper { request := c.r.Get(). Namespace(c.ns). Resource("services"). diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/services_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/services_test.go deleted file mode 100644 index 343aef6f6..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/services_test.go +++ /dev/null @@ -1,242 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -import ( - "net/url" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/labels" -) - -func TestListServices(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("services", ns, ""), - Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, - Body: &api.ServiceList{ - Items: []api.Service{ - { - ObjectMeta: api.ObjectMeta{ - Name: "name", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "one": "two", - }, - }, - }, - }, - }, - }, - } - receivedServiceList, err := c.Setup(t).Services(ns).List(api.ListOptions{}) - defer c.Close() - t.Logf("received services: %v %#v", err, receivedServiceList) - c.Validate(t, receivedServiceList, err) -} - -func TestListServicesLabels(t *testing.T) { - ns := api.NamespaceDefault - labelSelectorQueryParamName := unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("services", ns, ""), - Query: simple.BuildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})}, - Response: simple.Response{StatusCode: 200, - Body: &api.ServiceList{ - Items: []api.Service{ - { - ObjectMeta: api.ObjectMeta{ - Name: "name", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "one": "two", - }, - }, - }, - }, - }, - }, - } - c.Setup(t) - defer c.Close() - c.QueryValidator[labelSelectorQueryParamName] = simple.ValidateLabels - selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector() - options := api.ListOptions{LabelSelector: selector} - receivedServiceList, err := c.Services(ns).List(options) - c.Validate(t, receivedServiceList, err) -} - -func TestGetService(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("services", ns, "1"), - Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: &api.Service{ObjectMeta: api.ObjectMeta{Name: "service-1"}}}, - } - response, err := c.Setup(t).Services(ns).Get("1") - defer c.Close() - c.Validate(t, response, err) -} - -func TestGetServiceWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedPod, err := c.Setup(t).Services(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedPod, err) -} - -func TestCreateService(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "POST", - Path: testapi.Default.ResourcePath("services", ns, ""), - Body: &api.Service{ObjectMeta: api.ObjectMeta{Name: "service-1"}}, - Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: &api.Service{ObjectMeta: api.ObjectMeta{Name: "service-1"}}}, - } - response, err := c.Setup(t).Services(ns).Create(&api.Service{ObjectMeta: api.ObjectMeta{Name: "service-1"}}) - defer c.Close() - c.Validate(t, response, err) -} - -func TestUpdateService(t *testing.T) { - ns := api.NamespaceDefault - svc := &api.Service{ObjectMeta: api.ObjectMeta{Name: "service-1", ResourceVersion: "1"}} - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Default.ResourcePath("services", ns, "service-1"), Body: svc, Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200, Body: svc}, - } - response, err := c.Setup(t).Services(ns).Update(svc) - defer c.Close() - c.Validate(t, response, err) -} - -func TestDeleteService(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Default.ResourcePath("services", ns, "1"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Services(ns).Delete("1") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestUpdateServiceStatus(t *testing.T) { - ns := api.NamespaceDefault - lbStatus := api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - {IP: "127.0.0.1"}, - }, - } - requestService := &api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: ns, - ResourceVersion: "1", - }, - Status: api.ServiceStatus{ - LoadBalancer: lbStatus, - }, - } - c := &simple.Client{ - Request: simple.Request{ - Method: "PUT", - Path: testapi.Default.ResourcePath("services", ns, "foo") + "/status", - Query: simple.BuildQueryValues(nil), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Spec: api.ServiceSpec{}, - Status: api.ServiceStatus{ - LoadBalancer: lbStatus, - }, - }, - }, - } - receivedService, err := c.Setup(t).Services(ns).UpdateStatus(requestService) - defer c.Close() - c.Validate(t, receivedService, err) -} - -func TestServiceProxyGet(t *testing.T) { - body := "OK" - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("services", ns, "service-1") + "/proxy/foo", - Query: simple.BuildQueryValues(url.Values{"param-name": []string{"param-value"}}), - }, - Response: simple.Response{StatusCode: 200, RawBody: &body}, - } - response, err := c.Setup(t).Services(ns).ProxyGet("", "service-1", "", "foo", map[string]string{"param-name": "param-value"}).DoRaw() - defer c.Close() - c.ValidateRaw(t, response, err) - - // With scheme and port specified - c = &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("services", ns, "https:service-1:my-port") + "/proxy/foo", - Query: simple.BuildQueryValues(url.Values{"param-name": []string{"param-value"}}), - }, - Response: simple.Response{StatusCode: 200, RawBody: &body}, - } - response, err = c.Setup(t).Services(ns).ProxyGet("https", "service-1", "my-port", "foo", map[string]string{"param-name": "param-value"}).DoRaw() - defer c.Close() - c.ValidateRaw(t, response, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/actions.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/actions.go deleted file mode 100644 index 1e5a5e470..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/actions.go +++ /dev/null @@ -1,446 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "strings" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/runtime" -) - -func NewRootGetAction(resource, name string) GetActionImpl { - action := GetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Name = name - - return action -} - -func NewGetAction(resource, namespace, name string) GetActionImpl { - action := GetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Namespace = namespace - action.Name = name - - return action -} - -func NewRootListAction(resource string, opts api.ListOptions) ListActionImpl { - action := ListActionImpl{} - action.Verb = "list" - action.Resource = resource - labelSelector := opts.LabelSelector - if labelSelector == nil { - labelSelector = labels.Everything() - } - fieldSelector := opts.FieldSelector - if fieldSelector == nil { - fieldSelector = fields.Everything() - } - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewListAction(resource, namespace string, opts api.ListOptions) ListActionImpl { - action := ListActionImpl{} - action.Verb = "list" - action.Resource = resource - action.Namespace = namespace - labelSelector := opts.LabelSelector - if labelSelector == nil { - labelSelector = labels.Everything() - } - fieldSelector := opts.FieldSelector - if fieldSelector == nil { - fieldSelector = fields.Everything() - } - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewRootCreateAction(resource string, object runtime.Object) CreateActionImpl { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = resource - action.Object = object - - return action -} - -func NewCreateAction(resource, namespace string, object runtime.Object) CreateActionImpl { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = resource - action.Namespace = namespace - action.Object = object - - return action -} - -func NewRootUpdateAction(resource string, object runtime.Object) UpdateActionImpl { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = resource - action.Object = object - - return action -} - -func NewUpdateAction(resource, namespace string, object runtime.Object) UpdateActionImpl { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = resource - action.Namespace = namespace - action.Object = object - - return action -} - -func NewRootPatchAction(resource string, object runtime.Object) PatchActionImpl { - action := PatchActionImpl{} - action.Verb = "patch" - action.Resource = resource - action.Object = object - - return action -} - -func NewPatchAction(resource, namespace string, object runtime.Object) PatchActionImpl { - action := PatchActionImpl{} - action.Verb = "patch" - action.Resource = resource - action.Namespace = namespace - action.Object = object - - return action -} - -func NewUpdateSubresourceAction(resource, subresource, namespace string, object runtime.Object) UpdateActionImpl { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = resource - action.Subresource = subresource - action.Namespace = namespace - action.Object = object - - return action -} - -func NewRootDeleteAction(resource, name string) DeleteActionImpl { - action := DeleteActionImpl{} - action.Verb = "delete" - action.Resource = resource - action.Name = name - - return action -} - -func NewDeleteAction(resource, namespace, name string) DeleteActionImpl { - action := DeleteActionImpl{} - action.Verb = "delete" - action.Resource = resource - action.Namespace = namespace - action.Name = name - - return action -} - -func NewRootDeleteCollectionAction(resource string, opts api.ListOptions) DeleteCollectionActionImpl { - action := DeleteCollectionActionImpl{} - action.Verb = "delete-collection" - action.Resource = resource - labelSelector := opts.LabelSelector - if labelSelector == nil { - labelSelector = labels.Everything() - } - fieldSelector := opts.FieldSelector - if fieldSelector == nil { - fieldSelector = fields.Everything() - } - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewDeleteCollectionAction(resource, namespace string, opts api.ListOptions) DeleteCollectionActionImpl { - action := DeleteCollectionActionImpl{} - action.Verb = "delete-collection" - action.Resource = resource - action.Namespace = namespace - labelSelector := opts.LabelSelector - if labelSelector == nil { - labelSelector = labels.Everything() - } - fieldSelector := opts.FieldSelector - if fieldSelector == nil { - fieldSelector = fields.Everything() - } - action.ListRestrictions = ListRestrictions{labelSelector, fieldSelector} - - return action -} - -func NewRootWatchAction(resource string, opts api.ListOptions) WatchActionImpl { - action := WatchActionImpl{} - action.Verb = "watch" - action.Resource = resource - labelSelector := opts.LabelSelector - if labelSelector == nil { - labelSelector = labels.Everything() - } - fieldSelector := opts.FieldSelector - if fieldSelector == nil { - fieldSelector = fields.Everything() - } - action.WatchRestrictions = WatchRestrictions{labelSelector, fieldSelector, opts.ResourceVersion} - - return action -} - -func NewWatchAction(resource, namespace string, opts api.ListOptions) WatchActionImpl { - action := WatchActionImpl{} - action.Verb = "watch" - action.Resource = resource - action.Namespace = namespace - labelSelector := opts.LabelSelector - if labelSelector == nil { - labelSelector = labels.Everything() - } - fieldSelector := opts.FieldSelector - if fieldSelector == nil { - fieldSelector = fields.Everything() - } - action.WatchRestrictions = WatchRestrictions{labelSelector, fieldSelector, opts.ResourceVersion} - - return action -} - -func NewProxyGetAction(resource, namespace, scheme, name, port, path string, params map[string]string) ProxyGetActionImpl { - action := ProxyGetActionImpl{} - action.Verb = "get" - action.Resource = resource - action.Namespace = namespace - action.Scheme = scheme - action.Name = name - action.Port = port - action.Path = path - action.Params = params - return action -} - -type ListRestrictions struct { - Labels labels.Selector - Fields fields.Selector -} -type WatchRestrictions struct { - Labels labels.Selector - Fields fields.Selector - ResourceVersion string -} - -type Action interface { - GetNamespace() string - GetVerb() string - GetResource() string - GetSubresource() string - Matches(verb, resource string) bool -} - -type GenericAction interface { - Action - GetValue() interface{} -} - -type GetAction interface { - Action - GetName() string -} - -type ListAction interface { - Action - GetListRestrictions() ListRestrictions -} - -type CreateAction interface { - Action - GetObject() runtime.Object -} - -type UpdateAction interface { - Action - GetObject() runtime.Object -} - -type DeleteAction interface { - Action - GetName() string -} - -type WatchAction interface { - Action - GetWatchRestrictions() WatchRestrictions -} - -type ProxyGetAction interface { - Action - GetScheme() string - GetName() string - GetPort() string - GetPath() string - GetParams() map[string]string -} - -type ActionImpl struct { - Namespace string - Verb string - Resource string - Subresource string -} - -func (a ActionImpl) GetNamespace() string { - return a.Namespace -} -func (a ActionImpl) GetVerb() string { - return a.Verb -} -func (a ActionImpl) GetResource() string { - return a.Resource -} -func (a ActionImpl) GetSubresource() string { - return a.Subresource -} -func (a ActionImpl) Matches(verb, resource string) bool { - return strings.ToLower(verb) == strings.ToLower(a.Verb) && - strings.ToLower(resource) == strings.ToLower(a.Resource) -} - -type GenericActionImpl struct { - ActionImpl - Value interface{} -} - -func (a GenericActionImpl) GetValue() interface{} { - return a.Value -} - -type GetActionImpl struct { - ActionImpl - Name string -} - -func (a GetActionImpl) GetName() string { - return a.Name -} - -type ListActionImpl struct { - ActionImpl - ListRestrictions ListRestrictions -} - -func (a ListActionImpl) GetListRestrictions() ListRestrictions { - return a.ListRestrictions -} - -type CreateActionImpl struct { - ActionImpl - Object runtime.Object -} - -func (a CreateActionImpl) GetObject() runtime.Object { - return a.Object -} - -type UpdateActionImpl struct { - ActionImpl - Object runtime.Object -} - -func (a UpdateActionImpl) GetObject() runtime.Object { - return a.Object -} - -type PatchActionImpl struct { - ActionImpl - Object runtime.Object -} - -func (a PatchActionImpl) GetObject() runtime.Object { - return a.Object -} - -type DeleteActionImpl struct { - ActionImpl - Name string -} - -func (a DeleteActionImpl) GetName() string { - return a.Name -} - -type DeleteCollectionActionImpl struct { - ActionImpl - ListRestrictions ListRestrictions -} - -func (a DeleteCollectionActionImpl) GetListRestrictions() ListRestrictions { - return a.ListRestrictions -} - -type WatchActionImpl struct { - ActionImpl - WatchRestrictions WatchRestrictions -} - -func (a WatchActionImpl) GetWatchRestrictions() WatchRestrictions { - return a.WatchRestrictions -} - -type ProxyGetActionImpl struct { - ActionImpl - Scheme string - Name string - Port string - Path string - Params map[string]string -} - -func (a ProxyGetActionImpl) GetScheme() string { - return a.Scheme -} - -func (a ProxyGetActionImpl) GetName() string { - return a.Name -} - -func (a ProxyGetActionImpl) GetPort() string { - return a.Port -} - -func (a ProxyGetActionImpl) GetPath() string { - return a.Path -} - -func (a ProxyGetActionImpl) GetParams() map[string]string { - return a.Params -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_componentstatuses.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_componentstatuses.go deleted file mode 100644 index 34bf210d4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_componentstatuses.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" -) - -// Fake implements ComponentStatusInterface. -type FakeComponentStatuses struct { - Fake *Fake -} - -func (c *FakeComponentStatuses) Get(name string) (*api.ComponentStatus, error) { - obj, err := c.Fake.Invokes(NewRootGetAction("componentstatuses", name), &api.ComponentStatus{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ComponentStatus), err -} - -func (c *FakeComponentStatuses) List(opts api.ListOptions) (result *api.ComponentStatusList, err error) { - obj, err := c.Fake.Invokes(NewRootListAction("componentstatuses", opts), &api.ComponentStatusList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ComponentStatusList), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_configmaps.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_configmaps.go deleted file mode 100644 index 17a5bfeb8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_configmaps.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -const ( - configMapResourceName string = "configMaps" -) - -// FakeConfigMaps implements ConfigMapInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeConfigMaps struct { - Fake *Fake - Namespace string -} - -func (c *FakeConfigMaps) Get(name string) (*api.ConfigMap, error) { - obj, err := c.Fake.Invokes(NewGetAction(configMapResourceName, c.Namespace, name), &api.ConfigMap{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ConfigMap), err -} - -func (c *FakeConfigMaps) List(opts api.ListOptions) (*api.ConfigMapList, error) { - obj, err := c.Fake.Invokes(NewListAction(configMapResourceName, c.Namespace, opts), &api.ConfigMapList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ConfigMapList), err -} - -func (c *FakeConfigMaps) Create(cfg *api.ConfigMap) (*api.ConfigMap, error) { - obj, err := c.Fake.Invokes(NewCreateAction(configMapResourceName, c.Namespace, cfg), cfg) - if obj == nil { - return nil, err - } - - return obj.(*api.ConfigMap), err -} - -func (c *FakeConfigMaps) Update(cfg *api.ConfigMap) (*api.ConfigMap, error) { - obj, err := c.Fake.Invokes(NewUpdateAction(configMapResourceName, c.Namespace, cfg), cfg) - if obj == nil { - return nil, err - } - - return obj.(*api.ConfigMap), err -} - -func (c *FakeConfigMaps) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction(configMapResourceName, c.Namespace, name), &api.ConfigMap{}) - return err -} - -func (c *FakeConfigMaps) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction(configMapResourceName, c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_daemon_sets.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_daemon_sets.go deleted file mode 100644 index d0e1e73e1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_daemon_sets.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - kclientlib "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeDaemonSet implements DaemonInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeDaemonSets struct { - Fake *FakeExperimental - Namespace string -} - -// Ensure statically that FakeDaemonSets implements DaemonInterface. -var _ kclientlib.DaemonSetInterface = &FakeDaemonSets{} - -func (c *FakeDaemonSets) Get(name string) (*extensions.DaemonSet, error) { - obj, err := c.Fake.Invokes(NewGetAction("daemonsets", c.Namespace, name), &extensions.DaemonSet{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) List(opts api.ListOptions) (*extensions.DaemonSetList, error) { - obj, err := c.Fake.Invokes(NewListAction("daemonsets", c.Namespace, opts), &extensions.DaemonSetList{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSetList), err -} - -func (c *FakeDaemonSets) Create(daemon *extensions.DaemonSet) (*extensions.DaemonSet, error) { - obj, err := c.Fake.Invokes(NewCreateAction("daemonsets", c.Namespace, daemon), &extensions.DaemonSet{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) Update(daemon *extensions.DaemonSet) (*extensions.DaemonSet, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("daemonsets", c.Namespace, daemon), &extensions.DaemonSet{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) UpdateStatus(daemon *extensions.DaemonSet) (*extensions.DaemonSet, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("daemonsets", "status", c.Namespace, daemon), &extensions.DaemonSet{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.DaemonSet), err -} - -func (c *FakeDaemonSets) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("daemonsets", c.Namespace, name), &extensions.DaemonSet{}) - return err -} - -func (c *FakeDaemonSets) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("daemonsets", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_deployments.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_deployments.go deleted file mode 100644 index f53f27198..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_deployments.go +++ /dev/null @@ -1,105 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeDeployments implements DeploymentsInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakeDeployments struct { - Fake *FakeExperimental - Namespace string -} - -func (c *FakeDeployments) Get(name string) (*extensions.Deployment, error) { - obj, err := c.Fake.Invokes(NewGetAction("deployments", c.Namespace, name), &extensions.Deployment{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) List(opts api.ListOptions) (*extensions.DeploymentList, error) { - obj, err := c.Fake.Invokes(NewListAction("deployments", c.Namespace, opts), &extensions.DeploymentList{}) - if obj == nil { - return nil, err - } - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.DeploymentList{} - for _, deployment := range obj.(*extensions.DeploymentList).Items { - if label.Matches(labels.Set(deployment.Labels)) { - list.Items = append(list.Items, deployment) - } - } - return list, err -} - -func (c *FakeDeployments) Create(deployment *extensions.Deployment) (*extensions.Deployment, error) { - obj, err := c.Fake.Invokes(NewCreateAction("deployments", c.Namespace, deployment), deployment) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) Update(deployment *extensions.Deployment) (*extensions.Deployment, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("deployments", c.Namespace, deployment), deployment) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) UpdateStatus(deployment *extensions.Deployment) (*extensions.Deployment, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("deployments", "status", c.Namespace, deployment), deployment) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Deployment), err -} - -func (c *FakeDeployments) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("deployments", c.Namespace, name), &extensions.Deployment{}) - return err -} - -func (c *FakeDeployments) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("deployments", c.Namespace, opts)) -} - -func (c *FakeDeployments) Rollback(deploymentRollback *extensions.DeploymentRollback) error { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = "deployments" - action.Subresource = "rollback" - action.Object = deploymentRollback - - _, err := c.Fake.Invokes(action, deploymentRollback) - return err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_endpoints.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_endpoints.go deleted file mode 100644 index 68f6178f7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_endpoints.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeEndpoints implements EndpointInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeEndpoints struct { - Fake *Fake - Namespace string -} - -func (c *FakeEndpoints) Get(name string) (*api.Endpoints, error) { - obj, err := c.Fake.Invokes(NewGetAction("endpoints", c.Namespace, name), &api.Endpoints{}) - if obj == nil { - return nil, err - } - - return obj.(*api.Endpoints), err -} - -func (c *FakeEndpoints) List(opts api.ListOptions) (*api.EndpointsList, error) { - obj, err := c.Fake.Invokes(NewListAction("endpoints", c.Namespace, opts), &api.EndpointsList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.EndpointsList), err -} - -func (c *FakeEndpoints) Create(endpoints *api.Endpoints) (*api.Endpoints, error) { - obj, err := c.Fake.Invokes(NewCreateAction("endpoints", c.Namespace, endpoints), endpoints) - if obj == nil { - return nil, err - } - - return obj.(*api.Endpoints), err -} - -func (c *FakeEndpoints) Update(endpoints *api.Endpoints) (*api.Endpoints, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("endpoints", c.Namespace, endpoints), endpoints) - if obj == nil { - return nil, err - } - - return obj.(*api.Endpoints), err -} - -func (c *FakeEndpoints) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("endpoints", c.Namespace, name), &api.Endpoints{}) - return err -} - -func (c *FakeEndpoints) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("endpoints", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_events.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_events.go deleted file mode 100644 index 3da2143fc..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_events.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeEvents implements EventInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeEvents struct { - Fake *Fake - Namespace string -} - -// Get returns the given event, or an error. -func (c *FakeEvents) Get(name string) (*api.Event, error) { - action := NewRootGetAction("events", name) - if c.Namespace != "" { - action = NewGetAction("events", c.Namespace, name) - } - obj, err := c.Fake.Invokes(action, &api.Event{}) - if obj == nil { - return nil, err - } - - return obj.(*api.Event), err -} - -// List returns a list of events matching the selectors. -func (c *FakeEvents) List(opts api.ListOptions) (*api.EventList, error) { - action := NewRootListAction("events", opts) - if c.Namespace != "" { - action = NewListAction("events", c.Namespace, opts) - } - obj, err := c.Fake.Invokes(action, &api.EventList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.EventList), err -} - -// Create makes a new event. Returns the copy of the event the server returns, or an error. -func (c *FakeEvents) Create(event *api.Event) (*api.Event, error) { - action := NewRootCreateAction("events", event) - if c.Namespace != "" { - action = NewCreateAction("events", c.Namespace, event) - } - obj, err := c.Fake.Invokes(action, event) - if obj == nil { - return nil, err - } - - return obj.(*api.Event), err -} - -// Update replaces an existing event. Returns the copy of the event the server returns, or an error. -func (c *FakeEvents) Update(event *api.Event) (*api.Event, error) { - action := NewRootUpdateAction("events", event) - if c.Namespace != "" { - action = NewUpdateAction("events", c.Namespace, event) - } - obj, err := c.Fake.Invokes(action, event) - if obj == nil { - return nil, 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 := NewRootPatchAction("events", event) - if c.Namespace != "" { - action = NewPatchAction("events", c.Namespace, event) - } - obj, err := c.Fake.Invokes(action, event) - if obj == nil { - return nil, err - } - - return obj.(*api.Event), err -} - -func (c *FakeEvents) Delete(name string) error { - action := NewRootDeleteAction("events", name) - if c.Namespace != "" { - action = NewDeleteAction("events", c.Namespace, name) - } - _, err := c.Fake.Invokes(action, &api.Event{}) - return err -} - -func (c *FakeEvents) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { - action := NewRootDeleteCollectionAction("events", listOptions) - if c.Namespace != "" { - action = NewDeleteCollectionAction("events", c.Namespace, listOptions) - } - _, err := c.Fake.Invokes(action, &api.EventList{}) - return err -} - -// Watch starts watching for events matching the given selectors. -func (c *FakeEvents) Watch(opts api.ListOptions) (watch.Interface, error) { - action := NewRootWatchAction("events", opts) - if c.Namespace != "" { - action = NewWatchAction("events", c.Namespace, opts) - } - return c.Fake.InvokesWatch(action) -} - -// Search returns a list of events matching the specified object. -func (c *FakeEvents) Search(objOrRef runtime.Object) (*api.EventList, error) { - action := NewRootListAction("events", api.ListOptions{}) - if c.Namespace != "" { - action = NewListAction("events", c.Namespace, api.ListOptions{}) - } - obj, err := c.Fake.Invokes(action, &api.EventList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.EventList), err -} - -func (c *FakeEvents) GetFieldSelector(involvedObjectName, involvedObjectNamespace, involvedObjectKind, involvedObjectUID *string) fields.Selector { - action := GenericActionImpl{} - action.Verb = "get-field-selector" - action.Resource = "events" - - c.Fake.Invokes(action, nil) - return fields.Everything() -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_horizontal_pod_autoscalers.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_horizontal_pod_autoscalers.go deleted file mode 100644 index e50b326d9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_horizontal_pod_autoscalers.go +++ /dev/null @@ -1,164 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeHorizontalPodAutoscalers implements HorizontalPodAutoscalerInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakeHorizontalPodAutoscalers struct { - Fake *FakeExperimental - Namespace string -} - -func (c *FakeHorizontalPodAutoscalers) Get(name string) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewGetAction("horizontalpodautoscalers", c.Namespace, name), &extensions.HorizontalPodAutoscaler{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) List(opts api.ListOptions) (*extensions.HorizontalPodAutoscalerList, error) { - obj, err := c.Fake.Invokes(NewListAction("horizontalpodautoscalers", c.Namespace, opts), &extensions.HorizontalPodAutoscalerList{}) - if obj == nil { - return nil, err - } - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.HorizontalPodAutoscalerList{} - for _, a := range obj.(*extensions.HorizontalPodAutoscalerList).Items { - if label.Matches(labels.Set(a.Labels)) { - list.Items = append(list.Items, a) - } - } - return list, err -} - -func (c *FakeHorizontalPodAutoscalers) Create(a *extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewCreateAction("horizontalpodautoscalers", c.Namespace, a), a) - if obj == nil { - return nil, err - } - - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) Update(a *extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("horizontalpodautoscalers", c.Namespace, a), a) - if obj == nil { - return nil, err - } - - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) UpdateStatus(a *extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("horizontalpodautoscalers", "status", c.Namespace, a), &extensions.HorizontalPodAutoscaler{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalers) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("horizontalpodautoscalers", c.Namespace, name), &extensions.HorizontalPodAutoscaler{}) - return err -} - -func (c *FakeHorizontalPodAutoscalers) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("horizontalpodautoscalers", c.Namespace, opts)) -} - -// FakeHorizontalPodAutoscalers implements HorizontalPodAutoscalerInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -// This is a test implementation of HorizontalPodAutoscalersV1 -// TODO(piosz): get back to one client implementation once HPA will be graduated to GA completely -type FakeHorizontalPodAutoscalersV1 struct { - Fake *FakeAutoscaling - Namespace string -} - -func (c *FakeHorizontalPodAutoscalersV1) Get(name string) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewGetAction("horizontalpodautoscalers", c.Namespace, name), &extensions.HorizontalPodAutoscaler{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalersV1) List(opts api.ListOptions) (*extensions.HorizontalPodAutoscalerList, error) { - obj, err := c.Fake.Invokes(NewListAction("horizontalpodautoscalers", c.Namespace, opts), &extensions.HorizontalPodAutoscalerList{}) - if obj == nil { - return nil, err - } - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &extensions.HorizontalPodAutoscalerList{} - for _, a := range obj.(*extensions.HorizontalPodAutoscalerList).Items { - if label.Matches(labels.Set(a.Labels)) { - list.Items = append(list.Items, a) - } - } - return list, err -} - -func (c *FakeHorizontalPodAutoscalersV1) Create(a *extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewCreateAction("horizontalpodautoscalers", c.Namespace, a), a) - if obj == nil { - return nil, err - } - - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalersV1) Update(a *extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("horizontalpodautoscalers", c.Namespace, a), a) - if obj == nil { - return nil, err - } - - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalersV1) UpdateStatus(a *extensions.HorizontalPodAutoscaler) (*extensions.HorizontalPodAutoscaler, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("horizontalpodautoscalers", "status", c.Namespace, a), &extensions.HorizontalPodAutoscaler{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.HorizontalPodAutoscaler), err -} - -func (c *FakeHorizontalPodAutoscalersV1) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("horizontalpodautoscalers", c.Namespace, name), &extensions.HorizontalPodAutoscaler{}) - return err -} - -func (c *FakeHorizontalPodAutoscalersV1) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("horizontalpodautoscalers", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_ingress.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_ingress.go deleted file mode 100644 index b15458997..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_ingress.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeIngress implements IngressInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeIngress struct { - Fake *FakeExperimental - Namespace string -} - -func (c *FakeIngress) Get(name string) (*extensions.Ingress, error) { - obj, err := c.Fake.Invokes(NewGetAction("ingresses", c.Namespace, name), &extensions.Ingress{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Ingress), err -} - -func (c *FakeIngress) List(opts api.ListOptions) (*extensions.IngressList, error) { - obj, err := c.Fake.Invokes(NewListAction("ingresses", c.Namespace, opts), &extensions.IngressList{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.IngressList), err -} - -func (c *FakeIngress) Create(ingress *extensions.Ingress) (*extensions.Ingress, error) { - obj, err := c.Fake.Invokes(NewCreateAction("ingresses", c.Namespace, ingress), ingress) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Ingress), err -} - -func (c *FakeIngress) Update(ingress *extensions.Ingress) (*extensions.Ingress, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("ingresses", c.Namespace, ingress), ingress) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Ingress), err -} - -func (c *FakeIngress) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("ingresses", c.Namespace, name), &extensions.Ingress{}) - return err -} - -func (c *FakeIngress) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("ingresses", c.Namespace, opts)) -} - -func (c *FakeIngress) UpdateStatus(ingress *extensions.Ingress) (result *extensions.Ingress, err error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("ingresses", "status", c.Namespace, ingress), ingress) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Ingress), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_jobs.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_jobs.go deleted file mode 100644 index d6fb79fa1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_jobs.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeJobs implements JobInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeJobs struct { - Fake *FakeExperimental - Namespace string -} - -func (c *FakeJobs) Get(name string) (*extensions.Job, error) { - obj, err := c.Fake.Invokes(NewGetAction("jobs", c.Namespace, name), &extensions.Job{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Job), err -} - -func (c *FakeJobs) List(opts api.ListOptions) (*extensions.JobList, error) { - obj, err := c.Fake.Invokes(NewListAction("jobs", c.Namespace, opts), &extensions.JobList{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.JobList), err -} - -func (c *FakeJobs) Create(job *extensions.Job) (*extensions.Job, error) { - obj, err := c.Fake.Invokes(NewCreateAction("jobs", c.Namespace, job), job) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Job), err -} - -func (c *FakeJobs) Update(job *extensions.Job) (*extensions.Job, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("jobs", c.Namespace, job), job) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Job), err -} - -func (c *FakeJobs) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("jobs", c.Namespace, name), &extensions.Job{}) - return err -} - -func (c *FakeJobs) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("jobs", c.Namespace, opts)) -} - -func (c *FakeJobs) UpdateStatus(job *extensions.Job) (result *extensions.Job, err error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("jobs", "status", c.Namespace, job), job) - if obj == nil { - return nil, err - } - - return obj.(*extensions.Job), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_limit_ranges.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_limit_ranges.go deleted file mode 100644 index 3669f5ff8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_limit_ranges.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeLimitRanges implements PodsInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakeLimitRanges struct { - Fake *Fake - Namespace string -} - -func (c *FakeLimitRanges) Get(name string) (*api.LimitRange, error) { - obj, err := c.Fake.Invokes(NewGetAction("limitranges", c.Namespace, name), &api.LimitRange{}) - if obj == nil { - return nil, err - } - - return obj.(*api.LimitRange), err -} - -func (c *FakeLimitRanges) List(opts api.ListOptions) (*api.LimitRangeList, error) { - obj, err := c.Fake.Invokes(NewListAction("limitranges", c.Namespace, opts), &api.LimitRangeList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.LimitRangeList), err -} - -func (c *FakeLimitRanges) Create(limitRange *api.LimitRange) (*api.LimitRange, error) { - obj, err := c.Fake.Invokes(NewCreateAction("limitranges", c.Namespace, limitRange), limitRange) - if obj == nil { - return nil, err - } - - return obj.(*api.LimitRange), err -} - -func (c *FakeLimitRanges) Update(limitRange *api.LimitRange) (*api.LimitRange, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("limitranges", c.Namespace, limitRange), limitRange) - if obj == nil { - return nil, err - } - - return obj.(*api.LimitRange), err -} - -func (c *FakeLimitRanges) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("limitranges", c.Namespace, name), &api.LimitRange{}) - return err -} - -func (c *FakeLimitRanges) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("limitranges", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_namespaces.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_namespaces.go deleted file mode 100644 index 8c4ac1ac2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_namespaces.go +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeNamespaces implements NamespacesInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakeNamespaces struct { - Fake *Fake -} - -func (c *FakeNamespaces) Get(name string) (*api.Namespace, error) { - obj, err := c.Fake.Invokes(NewRootGetAction("namespaces", name), &api.Namespace{}) - if obj == nil { - return nil, err - } - - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) List(opts api.ListOptions) (*api.NamespaceList, error) { - obj, err := c.Fake.Invokes(NewRootListAction("namespaces", opts), &api.NamespaceList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.NamespaceList), err -} - -func (c *FakeNamespaces) Create(namespace *api.Namespace) (*api.Namespace, error) { - obj, err := c.Fake.Invokes(NewRootCreateAction("namespaces", namespace), namespace) - if obj == nil { - return nil, err - } - - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) Update(namespace *api.Namespace) (*api.Namespace, error) { - obj, err := c.Fake.Invokes(NewRootUpdateAction("namespaces", namespace), namespace) - if obj == nil { - return nil, err - } - - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) Delete(name string) error { - _, err := c.Fake.Invokes(NewRootDeleteAction("namespaces", name), &api.Namespace{}) - return err -} - -func (c *FakeNamespaces) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewRootWatchAction("namespaces", opts)) -} - -func (c *FakeNamespaces) Finalize(namespace *api.Namespace) (*api.Namespace, error) { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = "namespaces" - action.Subresource = "finalize" - action.Object = namespace - - obj, err := c.Fake.Invokes(action, namespace) - if obj == nil { - return nil, err - } - - return obj.(*api.Namespace), err -} - -func (c *FakeNamespaces) Status(namespace *api.Namespace) (*api.Namespace, error) { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = "namespaces" - action.Subresource = "status" - action.Object = namespace - - obj, err := c.Fake.Invokes(action, namespace) - if obj == nil { - return nil, err - } - - return obj.(*api.Namespace), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_nodes.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_nodes.go deleted file mode 100644 index b1943366e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_nodes.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeNodes implements NodeInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeNodes struct { - Fake *Fake -} - -func (c *FakeNodes) Get(name string) (*api.Node, error) { - obj, err := c.Fake.Invokes(NewRootGetAction("nodes", name), &api.Node{}) - if obj == nil { - return nil, err - } - - return obj.(*api.Node), err -} - -func (c *FakeNodes) List(opts api.ListOptions) (*api.NodeList, error) { - obj, err := c.Fake.Invokes(NewRootListAction("nodes", opts), &api.NodeList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.NodeList), err -} - -func (c *FakeNodes) Create(node *api.Node) (*api.Node, error) { - obj, err := c.Fake.Invokes(NewRootCreateAction("nodes", node), node) - if obj == nil { - return nil, err - } - - return obj.(*api.Node), err -} - -func (c *FakeNodes) Update(node *api.Node) (*api.Node, error) { - obj, err := c.Fake.Invokes(NewRootUpdateAction("nodes", node), node) - if obj == nil { - return nil, err - } - - return obj.(*api.Node), err -} - -func (c *FakeNodes) Delete(name string) error { - _, err := c.Fake.Invokes(NewRootDeleteAction("nodes", name), &api.Node{}) - return err -} - -func (c *FakeNodes) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewRootWatchAction("nodes", opts)) -} - -func (c *FakeNodes) UpdateStatus(node *api.Node) (*api.Node, error) { - action := CreateActionImpl{} - action.Verb = "update" - action.Resource = "nodes" - action.Subresource = "status" - action.Object = node - - obj, err := c.Fake.Invokes(action, node) - if obj == nil { - return nil, err - } - - return obj.(*api.Node), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_persistent_volume_claims.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_persistent_volume_claims.go deleted file mode 100644 index cadfb084c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_persistent_volume_claims.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -type FakePersistentVolumeClaims struct { - Fake *Fake - Namespace string -} - -func (c *FakePersistentVolumeClaims) Get(name string) (*api.PersistentVolumeClaim, error) { - obj, err := c.Fake.Invokes(NewGetAction("persistentvolumeclaims", c.Namespace, name), &api.PersistentVolumeClaim{}) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolumeClaim), err -} - -func (c *FakePersistentVolumeClaims) List(opts api.ListOptions) (*api.PersistentVolumeClaimList, error) { - obj, err := c.Fake.Invokes(NewListAction("persistentvolumeclaims", c.Namespace, opts), &api.PersistentVolumeClaimList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolumeClaimList), err -} - -func (c *FakePersistentVolumeClaims) Create(claim *api.PersistentVolumeClaim) (*api.PersistentVolumeClaim, error) { - obj, err := c.Fake.Invokes(NewCreateAction("persistentvolumeclaims", c.Namespace, claim), claim) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolumeClaim), err -} - -func (c *FakePersistentVolumeClaims) Update(claim *api.PersistentVolumeClaim) (*api.PersistentVolumeClaim, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("persistentvolumeclaims", c.Namespace, claim), claim) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolumeClaim), err -} - -func (c *FakePersistentVolumeClaims) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("persistentvolumeclaims", c.Namespace, name), &api.PersistentVolumeClaim{}) - return err -} - -func (c *FakePersistentVolumeClaims) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("persistentvolumeclaims", c.Namespace, opts)) -} - -func (c *FakePersistentVolumeClaims) UpdateStatus(claim *api.PersistentVolumeClaim) (*api.PersistentVolumeClaim, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("persistentvolumeclaims", "status", c.Namespace, claim), claim) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolumeClaim), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_persistent_volumes.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_persistent_volumes.go deleted file mode 100644 index cb184bc44..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_persistent_volumes.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -type FakePersistentVolumes struct { - Fake *Fake -} - -func (c *FakePersistentVolumes) Get(name string) (*api.PersistentVolume, error) { - obj, err := c.Fake.Invokes(NewRootGetAction("persistentvolumes", name), &api.PersistentVolume{}) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolume), err -} - -func (c *FakePersistentVolumes) List(opts api.ListOptions) (*api.PersistentVolumeList, error) { - obj, err := c.Fake.Invokes(NewRootListAction("persistentvolumes", opts), &api.PersistentVolumeList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolumeList), err -} - -func (c *FakePersistentVolumes) Create(pv *api.PersistentVolume) (*api.PersistentVolume, error) { - obj, err := c.Fake.Invokes(NewRootCreateAction("persistentvolumes", pv), pv) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolume), err -} - -func (c *FakePersistentVolumes) Update(pv *api.PersistentVolume) (*api.PersistentVolume, error) { - obj, err := c.Fake.Invokes(NewRootUpdateAction("persistentvolumes", pv), pv) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolume), err -} - -func (c *FakePersistentVolumes) Delete(name string) error { - _, err := c.Fake.Invokes(NewRootDeleteAction("persistentvolumes", name), &api.PersistentVolume{}) - return err -} - -func (c *FakePersistentVolumes) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewRootWatchAction("persistentvolumes", opts)) -} - -func (c *FakePersistentVolumes) UpdateStatus(pv *api.PersistentVolume) (*api.PersistentVolume, error) { - action := UpdateActionImpl{} - action.Verb = "update" - action.Resource = "persistentvolumes" - action.Subresource = "status" - action.Object = pv - - obj, err := c.Fake.Invokes(action, pv) - if obj == nil { - return nil, err - } - - return obj.(*api.PersistentVolume), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_pod_templates.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_pod_templates.go deleted file mode 100644 index 47ff3d8ac..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_pod_templates.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakePodTemplates implements PodTemplatesInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakePodTemplates struct { - Fake *Fake - Namespace string -} - -func (c *FakePodTemplates) Get(name string) (*api.PodTemplate, error) { - obj, err := c.Fake.Invokes(NewGetAction("podtemplates", c.Namespace, name), &api.PodTemplate{}) - if obj == nil { - return nil, err - } - - return obj.(*api.PodTemplate), err -} - -func (c *FakePodTemplates) List(opts api.ListOptions) (*api.PodTemplateList, error) { - obj, err := c.Fake.Invokes(NewListAction("podtemplates", c.Namespace, opts), &api.PodTemplateList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.PodTemplateList), err -} - -func (c *FakePodTemplates) Create(pod *api.PodTemplate) (*api.PodTemplate, error) { - obj, err := c.Fake.Invokes(NewCreateAction("podtemplates", c.Namespace, pod), pod) - if obj == nil { - return nil, err - } - - return obj.(*api.PodTemplate), err -} - -func (c *FakePodTemplates) Update(pod *api.PodTemplate) (*api.PodTemplate, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("podtemplates", c.Namespace, pod), pod) - if obj == nil { - return nil, err - } - - return obj.(*api.PodTemplate), err -} - -func (c *FakePodTemplates) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("podtemplates", c.Namespace, name), &api.PodTemplate{}) - return err -} - -func (c *FakePodTemplates) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("podtemplates", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_pods.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_pods.go deleted file mode 100644 index 824356aac..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_pods.go +++ /dev/null @@ -1,117 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/watch" -) - -// FakePods implements PodsInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakePods struct { - Fake *Fake - Namespace string -} - -func (c *FakePods) Get(name string) (*api.Pod, error) { - obj, err := c.Fake.Invokes(NewGetAction("pods", c.Namespace, name), &api.Pod{}) - if obj == nil { - return nil, err - } - - return obj.(*api.Pod), err -} - -func (c *FakePods) List(opts api.ListOptions) (*api.PodList, error) { - obj, err := c.Fake.Invokes(NewListAction("pods", c.Namespace, opts), &api.PodList{}) - if obj == nil { - return nil, err - } - label := opts.LabelSelector - if label == nil { - label = labels.Everything() - } - list := &api.PodList{} - for _, pod := range obj.(*api.PodList).Items { - if label.Matches(labels.Set(pod.Labels)) { - list.Items = append(list.Items, pod) - } - } - return list, err -} - -func (c *FakePods) Create(pod *api.Pod) (*api.Pod, error) { - obj, err := c.Fake.Invokes(NewCreateAction("pods", c.Namespace, pod), pod) - if obj == nil { - return nil, err - } - - return obj.(*api.Pod), err -} - -func (c *FakePods) Update(pod *api.Pod) (*api.Pod, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("pods", c.Namespace, pod), pod) - if obj == nil { - return nil, err - } - - return obj.(*api.Pod), err -} - -func (c *FakePods) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("pods", c.Namespace, name), &api.Pod{}) - return err -} - -func (c *FakePods) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("pods", c.Namespace, opts)) -} - -func (c *FakePods) Bind(binding *api.Binding) error { - action := CreateActionImpl{} - action.Verb = "create" - action.Resource = "pods" - action.Subresource = "bindings" - action.Object = binding - - _, err := c.Fake.Invokes(action, binding) - return err -} - -func (c *FakePods) UpdateStatus(pod *api.Pod) (*api.Pod, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("pods", "status", c.Namespace, pod), pod) - if obj == nil { - return nil, err - } - - return obj.(*api.Pod), err -} - -func (c *FakePods) GetLogs(name string, opts *api.PodLogOptions) *client.Request { - action := GenericActionImpl{} - action.Verb = "get" - action.Namespace = c.Namespace - action.Resource = "pod" - action.Subresource = "logs" - action.Value = opts - - _, _ = c.Fake.Invokes(action, &api.Pod{}) - return &client.Request{} -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_podsecuritypolicy.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_podsecuritypolicy.go deleted file mode 100644 index bb611d322..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_podsecuritypolicy.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/watch" -) - -// FakePodSecurityPolicy implements PodSecurityPolicyInterface. Meant to be -// embedded into a struct to get a default implementation. This makes faking out just -// the method you want to test easier. -type FakePodSecurityPolicy struct { - Fake *Fake - Namespace string -} - -func (c *FakePodSecurityPolicy) List(opts api.ListOptions) (*extensions.PodSecurityPolicyList, error) { - obj, err := c.Fake.Invokes(NewListAction("podsecuritypolicies", c.Namespace, opts), &extensions.PodSecurityPolicyList{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.PodSecurityPolicyList), err -} - -func (c *FakePodSecurityPolicy) Get(name string) (*extensions.PodSecurityPolicy, error) { - obj, err := c.Fake.Invokes(NewGetAction("podsecuritypolicies", c.Namespace, name), &extensions.PodSecurityPolicy{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.PodSecurityPolicy), err -} - -func (c *FakePodSecurityPolicy) Create(scc *extensions.PodSecurityPolicy) (*extensions.PodSecurityPolicy, error) { - obj, err := c.Fake.Invokes(NewCreateAction("podsecuritypolicies", c.Namespace, scc), &extensions.PodSecurityPolicy{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.PodSecurityPolicy), err -} - -func (c *FakePodSecurityPolicy) Update(scc *extensions.PodSecurityPolicy) (*extensions.PodSecurityPolicy, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("podsecuritypolicies", c.Namespace, scc), &extensions.PodSecurityPolicy{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.PodSecurityPolicy), err -} - -func (c *FakePodSecurityPolicy) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("podsecuritypolicies", c.Namespace, name), &extensions.PodSecurityPolicy{}) - return err -} - -func (c *FakePodSecurityPolicy) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("podsecuritypolicies", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_replica_sets.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_replica_sets.go deleted file mode 100644 index 29c985c8c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_replica_sets.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeReplicaSets implements ReplicaSetsInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeReplicaSets struct { - Fake *FakeExperimental - Namespace string -} - -func (c *FakeReplicaSets) Get(name string) (*extensions.ReplicaSet, error) { - obj, err := c.Fake.Invokes(NewGetAction("replicasets", c.Namespace, name), &extensions.ReplicaSet{}) - if obj == nil { - return nil, err - } - - return obj.(*extensions.ReplicaSet), err -} - -func (c *FakeReplicaSets) List(opts api.ListOptions) (*extensions.ReplicaSetList, error) { - obj, err := c.Fake.Invokes(NewListAction("replicasets", c.Namespace, opts), &extensions.ReplicaSetList{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.ReplicaSetList), err -} - -func (c *FakeReplicaSets) Create(rs *extensions.ReplicaSet) (*extensions.ReplicaSet, error) { - obj, err := c.Fake.Invokes(NewCreateAction("replicasets", c.Namespace, rs), rs) - if obj == nil { - return nil, err - } - - return obj.(*extensions.ReplicaSet), err -} - -func (c *FakeReplicaSets) Update(rs *extensions.ReplicaSet) (*extensions.ReplicaSet, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("replicasets", c.Namespace, rs), rs) - if obj == nil { - return nil, err - } - - return obj.(*extensions.ReplicaSet), err -} - -func (c *FakeReplicaSets) Delete(name string, options *api.DeleteOptions) error { - _, err := c.Fake.Invokes(NewDeleteAction("replicasets", c.Namespace, name), &extensions.ReplicaSet{}) - return err -} - -func (c *FakeReplicaSets) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("replicasets", c.Namespace, opts)) -} - -func (c *FakeReplicaSets) UpdateStatus(rs *extensions.ReplicaSet) (result *extensions.ReplicaSet, err error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("replicasets", "status", c.Namespace, rs), rs) - if obj == nil { - return nil, err - } - - return obj.(*extensions.ReplicaSet), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_replication_controllers.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_replication_controllers.go deleted file mode 100644 index e44b82615..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_replication_controllers.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeReplicationControllers implements ReplicationControllerInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeReplicationControllers struct { - Fake *Fake - Namespace string -} - -func (c *FakeReplicationControllers) Get(name string) (*api.ReplicationController, error) { - obj, err := c.Fake.Invokes(NewGetAction("replicationcontrollers", c.Namespace, name), &api.ReplicationController{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) List(opts api.ListOptions) (*api.ReplicationControllerList, error) { - obj, err := c.Fake.Invokes(NewListAction("replicationcontrollers", c.Namespace, opts), &api.ReplicationControllerList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ReplicationControllerList), err -} - -func (c *FakeReplicationControllers) Create(controller *api.ReplicationController) (*api.ReplicationController, error) { - obj, err := c.Fake.Invokes(NewCreateAction("replicationcontrollers", c.Namespace, controller), controller) - if obj == nil { - return nil, err - } - - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) Update(controller *api.ReplicationController) (*api.ReplicationController, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("replicationcontrollers", c.Namespace, controller), controller) - if obj == nil { - return nil, err - } - - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) UpdateStatus(controller *api.ReplicationController) (*api.ReplicationController, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("replicationcontrollers", "status", c.Namespace, controller), &api.ReplicationController{}) - if obj == nil { - return nil, err - } - return obj.(*api.ReplicationController), err -} - -func (c *FakeReplicationControllers) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("replicationcontrollers", c.Namespace, name), &api.ReplicationController{}) - return err -} - -func (c *FakeReplicationControllers) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("replicationcontrollers", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_resource_quotas.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_resource_quotas.go deleted file mode 100644 index d5090f0d0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_resource_quotas.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeResourceQuotas implements ResourceQuotaInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakeResourceQuotas struct { - Fake *Fake - Namespace string -} - -func (c *FakeResourceQuotas) Get(name string) (*api.ResourceQuota, error) { - obj, err := c.Fake.Invokes(NewGetAction("resourcequotas", c.Namespace, name), &api.ResourceQuota{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ResourceQuota), err -} - -func (c *FakeResourceQuotas) List(opts api.ListOptions) (*api.ResourceQuotaList, error) { - obj, err := c.Fake.Invokes(NewListAction("resourcequotas", c.Namespace, opts), &api.ResourceQuotaList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ResourceQuotaList), err -} - -func (c *FakeResourceQuotas) Create(resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { - obj, err := c.Fake.Invokes(NewCreateAction("resourcequotas", c.Namespace, resourceQuota), resourceQuota) - if obj == nil { - return nil, err - } - - return obj.(*api.ResourceQuota), err -} - -func (c *FakeResourceQuotas) Update(resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("resourcequotas", c.Namespace, resourceQuota), resourceQuota) - if obj == nil { - return nil, err - } - - return obj.(*api.ResourceQuota), err -} - -func (c *FakeResourceQuotas) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("resourcequotas", c.Namespace, name), &api.ResourceQuota{}) - return err -} - -func (c *FakeResourceQuotas) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("resourcequotas", c.Namespace, opts)) -} - -func (c *FakeResourceQuotas) UpdateStatus(resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("resourcequotas", "status", c.Namespace, resourceQuota), resourceQuota) - if obj == nil { - return nil, err - } - - return obj.(*api.ResourceQuota), err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_scales.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_scales.go deleted file mode 100644 index 53ff5f87d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_scales.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/apis/extensions" -) - -// FakeScales implements ScaleInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the methods you want to test easier. -type FakeScales struct { - Fake *FakeExperimental - Namespace string -} - -func (c *FakeScales) Get(kind string, name string) (result *extensions.Scale, err error) { - action := GetActionImpl{} - action.Verb = "get" - action.Namespace = c.Namespace - action.Resource = kind - action.Subresource = "scale" - action.Name = name - obj, err := c.Fake.Invokes(action, &extensions.Scale{}) - result = obj.(*extensions.Scale) - return -} - -func (c *FakeScales) Update(kind string, scale *extensions.Scale) (result *extensions.Scale, err error) { - action := UpdateActionImpl{} - action.Verb = "update" - action.Namespace = c.Namespace - action.Resource = kind - action.Subresource = "scale" - action.Object = scale - obj, err := c.Fake.Invokes(action, scale) - result = obj.(*extensions.Scale) - return -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_secrets.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_secrets.go deleted file mode 100644 index f54cffb87..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_secrets.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// Fake implements SecretInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeSecrets struct { - Fake *Fake - Namespace string -} - -func (c *FakeSecrets) Get(name string) (*api.Secret, error) { - obj, err := c.Fake.Invokes(NewGetAction("secrets", c.Namespace, name), &api.Secret{}) - if obj == nil { - return nil, err - } - - return obj.(*api.Secret), err -} - -func (c *FakeSecrets) List(opts api.ListOptions) (*api.SecretList, error) { - obj, err := c.Fake.Invokes(NewListAction("secrets", c.Namespace, opts), &api.SecretList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.SecretList), err -} - -func (c *FakeSecrets) Create(secret *api.Secret) (*api.Secret, error) { - obj, err := c.Fake.Invokes(NewCreateAction("secrets", c.Namespace, secret), secret) - if obj == nil { - return nil, err - } - - return obj.(*api.Secret), err -} - -func (c *FakeSecrets) Update(secret *api.Secret) (*api.Secret, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("secrets", c.Namespace, secret), secret) - if obj == nil { - return nil, err - } - - return obj.(*api.Secret), err -} - -func (c *FakeSecrets) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("secrets", c.Namespace, name), &api.Secret{}) - return err -} - -func (c *FakeSecrets) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("secrets", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_service_accounts.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_service_accounts.go deleted file mode 100644 index e40641668..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_service_accounts.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeServiceAccounts implements ServiceAccountsInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeServiceAccounts struct { - Fake *Fake - Namespace string -} - -func (c *FakeServiceAccounts) Get(name string) (*api.ServiceAccount, error) { - obj, err := c.Fake.Invokes(NewGetAction("serviceaccounts", c.Namespace, name), &api.ServiceAccount{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ServiceAccount), err -} - -func (c *FakeServiceAccounts) List(opts api.ListOptions) (*api.ServiceAccountList, error) { - obj, err := c.Fake.Invokes(NewListAction("serviceaccounts", c.Namespace, opts), &api.ServiceAccountList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ServiceAccountList), err -} - -func (c *FakeServiceAccounts) Create(serviceAccount *api.ServiceAccount) (*api.ServiceAccount, error) { - obj, err := c.Fake.Invokes(NewCreateAction("serviceaccounts", c.Namespace, serviceAccount), serviceAccount) - if obj == nil { - return nil, err - } - - return obj.(*api.ServiceAccount), err -} - -func (c *FakeServiceAccounts) Update(serviceAccount *api.ServiceAccount) (*api.ServiceAccount, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("serviceaccounts", c.Namespace, serviceAccount), serviceAccount) - if obj == nil { - return nil, err - } - - return obj.(*api.ServiceAccount), err -} - -func (c *FakeServiceAccounts) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("serviceaccounts", c.Namespace, name), &api.ServiceAccount{}) - return err -} - -func (c *FakeServiceAccounts) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("serviceaccounts", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_services.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_services.go deleted file mode 100644 index 2f17c7578..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_services.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/watch" -) - -// Fake implements ServiceInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeServices struct { - Fake *Fake - Namespace string -} - -func (c *FakeServices) Get(name string) (*api.Service, error) { - obj, err := c.Fake.Invokes(NewGetAction("services", c.Namespace, name), &api.Service{}) - if obj == nil { - return nil, err - } - - return obj.(*api.Service), err -} - -func (c *FakeServices) List(opts api.ListOptions) (*api.ServiceList, error) { - obj, err := c.Fake.Invokes(NewListAction("services", c.Namespace, opts), &api.ServiceList{}) - if obj == nil { - return nil, err - } - - return obj.(*api.ServiceList), err -} - -func (c *FakeServices) Create(service *api.Service) (*api.Service, error) { - obj, err := c.Fake.Invokes(NewCreateAction("services", c.Namespace, service), service) - if obj == nil { - return nil, err - } - - return obj.(*api.Service), err -} - -func (c *FakeServices) Update(service *api.Service) (*api.Service, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("services", c.Namespace, service), service) - if obj == nil { - return nil, err - } - - return obj.(*api.Service), err -} - -func (c *FakeServices) UpdateStatus(service *api.Service) (result *api.Service, err error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("services", "status", c.Namespace, service), service) - if obj == nil { - return nil, err - } - - return obj.(*api.Service), err -} - -func (c *FakeServices) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("services", c.Namespace, name), &api.Service{}) - return err -} - -func (c *FakeServices) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("services", c.Namespace, opts)) -} - -func (c *FakeServices) ProxyGet(scheme, name, port, path string, params map[string]string) client.ResponseWrapper { - return c.Fake.InvokesProxy(NewProxyGetAction("services", c.Namespace, scheme, name, port, path, params)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_test.go deleted file mode 100644 index 303d6d786..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_test.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package testclient - -import ( - "testing" - - client "k8s.io/kubernetes/pkg/client/unversioned" -) - -// This test file just ensures that Fake and structs it is embedded in -// implement Interface. - -func TestFakeImplementsInterface(t *testing.T) { - _ = client.Interface(&Fake{}) -} - -type MyFake struct { - *Fake -} - -func TestEmbeddedFakeImplementsInterface(t *testing.T) { - _ = client.Interface(MyFake{&Fake{}}) - _ = client.Interface(&MyFake{&Fake{}}) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_thirdpartyresources.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_thirdpartyresources.go deleted file mode 100644 index 8aa198d70..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fake_thirdpartyresources.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apis/extensions" - kclientlib "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/watch" -) - -// FakeThirdPartyResources implements ThirdPartyResourceInterface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type FakeThirdPartyResources struct { - Fake *FakeExperimental - Namespace string -} - -// Ensure statically that FakeThirdPartyResources implements DaemonInterface. -var _ kclientlib.ThirdPartyResourceInterface = &FakeThirdPartyResources{} - -func (c *FakeThirdPartyResources) Get(name string) (*extensions.ThirdPartyResource, error) { - obj, err := c.Fake.Invokes(NewGetAction("thirdpartyresources", c.Namespace, name), &extensions.ThirdPartyResource{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResource), err -} - -func (c *FakeThirdPartyResources) List(opts api.ListOptions) (*extensions.ThirdPartyResourceList, error) { - obj, err := c.Fake.Invokes(NewListAction("thirdpartyresources", c.Namespace, opts), &extensions.ThirdPartyResourceList{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResourceList), err -} - -func (c *FakeThirdPartyResources) Create(daemon *extensions.ThirdPartyResource) (*extensions.ThirdPartyResource, error) { - obj, err := c.Fake.Invokes(NewCreateAction("thirdpartyresources", c.Namespace, daemon), &extensions.ThirdPartyResource{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResource), err -} - -func (c *FakeThirdPartyResources) Update(daemon *extensions.ThirdPartyResource) (*extensions.ThirdPartyResource, error) { - obj, err := c.Fake.Invokes(NewUpdateAction("thirdpartyresources", c.Namespace, daemon), &extensions.ThirdPartyResource{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResource), err -} - -func (c *FakeThirdPartyResources) UpdateStatus(daemon *extensions.ThirdPartyResource) (*extensions.ThirdPartyResource, error) { - obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("thirdpartyresources", "status", c.Namespace, daemon), &extensions.ThirdPartyResource{}) - if obj == nil { - return nil, err - } - return obj.(*extensions.ThirdPartyResource), err -} - -func (c *FakeThirdPartyResources) Delete(name string) error { - _, err := c.Fake.Invokes(NewDeleteAction("thirdpartyresources", c.Namespace, name), &extensions.ThirdPartyResource{}) - return err -} - -func (c *FakeThirdPartyResources) Watch(opts api.ListOptions) (watch.Interface, error) { - return c.Fake.InvokesWatch(NewWatchAction("thirdpartyresources", c.Namespace, opts)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fixture.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fixture.go deleted file mode 100644 index 64388fb63..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/fixture.go +++ /dev/null @@ -1,316 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "fmt" - "io/ioutil" - "reflect" - "strings" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "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 -} - -// ObjectScheme abstracts the implementation of common operations on objects. -type ObjectScheme interface { - runtime.ObjectCreater - runtime.ObjectCopier - 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 { - - return func(action Action) (bool, runtime.Object, error) { - kind, err := mapper.KindFor(unversioned.GroupVersionResource{Resource: action.GetResource()}) - if err != nil { - return false, nil, fmt.Errorf("unrecognized action %s: %v", action.GetResource(), err) - } - - // 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 - - case GetAction: - resource, err := o.Kind(kind, castAction.GetName()) - return true, resource, err - - case DeleteAction: - resource, err := o.Kind(kind, castAction.GetName()) - return true, resource, err - - case CreateAction: - meta, err := api.ObjectMetaFor(castAction.GetObject()) - if err != nil { - return true, nil, err - } - resource, err := o.Kind(kind, meta.Name) - return true, resource, err - - case UpdateAction: - meta, err := api.ObjectMetaFor(castAction.GetObject()) - if err != nil { - return true, nil, err - } - resource, err := o.Kind(kind, meta.Name) - return true, resource, err - - default: - return false, nil, fmt.Errorf("no reaction implemented for %s", action) - } - - return true, nil, nil - } -} - -// 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 - scheme ObjectScheme - decoder runtime.Decoder -} - -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), - scheme: scheme, - decoder: decoder, - } -} - -func (o objects) Kind(kind unversioned.GroupVersionKind, name string) (runtime.Object, error) { - kind.Version = runtime.APIVersionInternal - - empty, _ := o.scheme.New(kind) - nilValue := reflect.Zero(reflect.TypeOf(empty)).Interface().(runtime.Object) - - arr, ok := o.types[kind.Kind] - 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) - } - - index := o.last[kind.Kind] - if index >= len(arr) { - index = len(arr) - 1 - } - if index < 0 { - return nilValue, errors.NewNotFound(unversioned.GroupResource{Group: kind.Group, Resource: kind.Kind}, name) - } - out, err := o.scheme.Copy(arr[index]) - if err != nil { - return nilValue, err - } - o.last[kind.Kind] = index + 1 - - if status, ok := out.(*unversioned.Status); ok { - if status.Details != nil { - status.Details.Kind = kind.Kind - } - if status.Status != unversioned.StatusSuccess { - return nilValue, &errors.StatusError{ErrStatus: *status} - } - } - - return out, nil -} - -func (o objects) Add(obj runtime.Object) error { - gvk, err := o.scheme.ObjectKind(obj) - if err != nil { - return err - } - kind := gvk.Kind - - switch { - case meta.IsListType(obj): - if kind != "List" { - o.types[kind] = append(o.types[kind], obj) - } - - list, err := meta.ExtractList(obj) - if err != nil { - return err - } - if errs := runtime.DecodeList(list, o.decoder); len(errs) > 0 { - return errs[0] - } - for _, obj := range list { - if err := o.Add(obj); err != nil { - return err - } - } - default: - if status, ok := obj.(*unversioned.Status); ok && status.Details != nil { - kind = status.Details.Kind - } - o.types[kind] = append(o.types[kind], obj) - } - - return nil -} - -func DefaultWatchReactor(watchInterface watch.Interface, err error) WatchReactionFunc { - return func(action Action) (bool, watch.Interface, error) { - return true, watchInterface, err - } -} - -// SimpleReactor is a Reactor. Each reaction function is attached to a given verb,resource tuple. "*" in either field matches everything for that value. -// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions -type SimpleReactor struct { - Verb string - Resource string - - Reaction ReactionFunc -} - -func (r *SimpleReactor) Handles(action Action) bool { - verbCovers := r.Verb == "*" || r.Verb == action.GetVerb() - if !verbCovers { - return false - } - resourceCovers := r.Resource == "*" || r.Resource == action.GetResource() - if !resourceCovers { - return false - } - - return true -} - -func (r *SimpleReactor) React(action Action) (bool, runtime.Object, error) { - return r.Reaction(action) -} - -// SimpleWatchReactor is a WatchReactor. Each reaction function is attached to a given resource. "*" matches everything for that value. -// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions -type SimpleWatchReactor struct { - Resource string - - Reaction WatchReactionFunc -} - -func (r *SimpleWatchReactor) Handles(action Action) bool { - resourceCovers := r.Resource == "*" || r.Resource == action.GetResource() - if !resourceCovers { - return false - } - - return true -} - -func (r *SimpleWatchReactor) React(action Action) (bool, watch.Interface, error) { - return r.Reaction(action) -} - -// SimpleProxyReactor is a ProxyReactor. Each reaction function is attached to a given resource. "*" matches everything for that value. -// For instance, *,pods matches all verbs on pods. This allows for easier composition of reaction functions. -type SimpleProxyReactor struct { - Resource string - - Reaction ProxyReactionFunc -} - -func (r *SimpleProxyReactor) Handles(action Action) bool { - resourceCovers := r.Resource == "*" || r.Resource == action.GetResource() - if !resourceCovers { - return false - } - - return true -} - -func (r *SimpleProxyReactor) React(action Action) (bool, client.ResponseWrapper, error) { - return r.Reaction(action) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/simple/simple_testclient.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/simple/simple_testclient.go deleted file mode 100644 index ab32f5295..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/simple/simple_testclient.go +++ /dev/null @@ -1,240 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package simple - -import ( - "net/http/httptest" - "net/url" - "path" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/runtime" - utiltesting "k8s.io/kubernetes/pkg/util/testing" -) - -const NameRequiredError = "resource name may not be empty" - -type Request struct { - Method string - Path string - Header string - Query url.Values - Body runtime.Object - RawBody *string -} - -type Response struct { - StatusCode int - Body runtime.Object - RawBody *string -} - -type Client struct { - *client.Client - Clientset *clientset.Clientset - Request Request - Response Response - Error bool - Created bool - server *httptest.Server - handler *utiltesting.FakeHandler - // For query args, an optional function to validate the contents - // useful when the contents can change but still be correct. - // Maps from query arg key to validator. - // If no validator is present, string equality is used. - QueryValidator map[string]func(string, string) bool - - // If your object could exist in multiple groups, set this to - // correspond to the URL you're testing it with. - ResourceGroup string -} - -func (c *Client) Setup(t *testing.T) *Client { - c.handler = &utiltesting.FakeHandler{ - StatusCode: c.Response.StatusCode, - } - if responseBody := c.body(t, c.Response.Body, c.Response.RawBody); responseBody != nil { - c.handler.ResponseBody = *responseBody - } - c.server = httptest.NewServer(c.handler) - if c.Client == nil { - c.Client = client.NewOrDie(&client.Config{ - Host: c.server.URL, - ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}, - }) - - // TODO: caesarxuchao: hacky way to specify version of Experimental client. - // We will fix this by supporting multiple group versions in Config - c.AutoscalingClient = client.NewAutoscalingOrDie(&client.Config{ - Host: c.server.URL, - ContentConfig: client.ContentConfig{GroupVersion: testapi.Autoscaling.GroupVersion()}, - }) - c.ExtensionsClient = client.NewExtensionsOrDie(&client.Config{ - Host: c.server.URL, - ContentConfig: client.ContentConfig{GroupVersion: testapi.Extensions.GroupVersion()}, - }) - - c.Clientset = clientset.NewForConfigOrDie(&client.Config{Host: c.server.URL}) - } - c.QueryValidator = map[string]func(string, string) bool{} - return c -} - -func (c *Client) Close() { - if c.server != nil { - // TODO: Uncomment when fix #19254 - // c.server.Close() - } -} - -func (c *Client) ServerURL() string { - return c.server.URL -} - -func (c *Client) Validate(t *testing.T, received runtime.Object, err error) { - c.ValidateCommon(t, err) - - if c.Response.Body != nil && !api.Semantic.DeepDerivative(c.Response.Body, received) { - t.Errorf("bad response for request %#v: \nexpected %#v\ngot %#v\n", c.Request, c.Response.Body, received) - } -} - -func (c *Client) ValidateRaw(t *testing.T, received []byte, err error) { - c.ValidateCommon(t, err) - - if c.Response.Body != nil && !reflect.DeepEqual(c.Response.Body, received) { - t.Errorf("bad response for request %#v: expected %#v, got %#v", c.Request, c.Response.Body, received) - } -} - -func (c *Client) ValidateCommon(t *testing.T, err error) { - if c.Error { - if err == nil { - t.Errorf("error expected for %#v, got none", c.Request) - } - return - } - if err != nil { - t.Errorf("no error expected for %#v, got: %v", c.Request, err) - } - - if c.handler.RequestReceived == nil { - t.Errorf("handler had an empty request, %#v", c) - return - } - - requestBody := c.body(t, c.Request.Body, c.Request.RawBody) - actualQuery := c.handler.RequestReceived.URL.Query() - t.Logf("got query: %v", actualQuery) - t.Logf("path: %v", c.Request.Path) - // We check the query manually, so blank it out so that FakeHandler.ValidateRequest - // won't check it. - c.handler.RequestReceived.URL.RawQuery = "" - c.handler.ValidateRequest(t, path.Join(c.Request.Path), c.Request.Method, requestBody) - for key, values := range c.Request.Query { - validator, ok := c.QueryValidator[key] - if !ok { - switch key { - case unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()): - validator = ValidateLabels - case unversioned.FieldSelectorQueryParam(testapi.Default.GroupVersion().String()): - validator = validateFields - default: - validator = func(a, b string) bool { return a == b } - } - } - observed := actualQuery.Get(key) - wanted := strings.Join(values, "") - if !validator(wanted, observed) { - t.Errorf("Unexpected query arg for key: %s. Expected %s, Received %s", key, wanted, observed) - } - } - if c.Request.Header != "" { - if c.handler.RequestReceived.Header.Get(c.Request.Header) == "" { - t.Errorf("header %q not found in request %#v", c.Request.Header, c.handler.RequestReceived) - } - } - - if expected, received := requestBody, c.handler.RequestBody; expected != nil && *expected != received { - t.Errorf("bad body for request %#v: expected %s, got %s", c.Request, *expected, received) - } -} - -// buildQueryValues is a convenience function for knowing if a namespace should be in a query param or not -func BuildQueryValues(query url.Values) url.Values { - v := url.Values{} - if query != nil { - for key, values := range query { - for _, value := range values { - v.Add(key, value) - } - } - } - return v -} - -func ValidateLabels(a, b string) bool { - sA, eA := labels.Parse(a) - if eA != nil { - return false - } - sB, eB := labels.Parse(b) - if eB != nil { - return false - } - return sA.String() == sB.String() -} - -func validateFields(a, b string) bool { - sA, _ := fields.ParseSelector(a) - sB, _ := fields.ParseSelector(b) - return sA.String() == sB.String() -} - -func (c *Client) body(t *testing.T, obj runtime.Object, raw *string) *string { - if obj != nil { - fqKind, err := api.Scheme.ObjectKind(obj) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - } - groupName := fqKind.GroupVersion().Group - if c.ResourceGroup != "" { - groupName = c.ResourceGroup - } - var bs []byte - g, found := testapi.Groups[groupName] - if !found { - t.Errorf("Group %s is not registered in testapi", groupName) - } - bs, err = runtime.Encode(g.Codec(), obj) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - } - body := string(bs) - return &body - } - return raw -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/testclient.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/testclient.go deleted file mode 100644 index ef962e417..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/testclient.go +++ /dev/null @@ -1,399 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "fmt" - "sync" - - "github.com/emicklei/go-restful/swagger" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/version" - "k8s.io/kubernetes/pkg/watch" -) - -// NewSimpleFake returns a client that will respond with the provided objects -func NewSimpleFake(objects ...runtime.Object) *Fake { - o := NewObjects(api.Scheme, api.Codecs.UniversalDecoder()) - for _, obj := range objects { - if err := o.Add(obj); err != nil { - panic(err) - } - } - - fakeClient := &Fake{} - fakeClient.AddReactor("*", "*", ObjectReaction(o, api.RESTMapper)) - - fakeClient.AddWatchReactor("*", DefaultWatchReactor(watch.NewFake(), nil)) - - return fakeClient -} - -// Fake implements client.Interface. Meant to be embedded into a struct to get a default -// implementation. This makes faking out just the method you want to test easier. -type Fake struct { - sync.RWMutex - actions []Action // these may be castable to other types, but "Action" is the minimum - - // ReactionChain is the list of reactors that will be attempted for every request in the order they are tried - ReactionChain []Reactor - // WatchReactionChain is the list of watch reactors that will be attempted for every request in the order they are tried - WatchReactionChain []WatchReactor - // ProxyReactionChain is the list of proxy reactors that will be attempted for every request in the order they are tried - ProxyReactionChain []ProxyReactor - - Resources map[string]*unversioned.APIResourceList -} - -// Reactor is an interface to allow the composition of reaction functions. -type Reactor interface { - // Handles indicates whether or not this Reactor deals with a given action - Handles(action Action) bool - // React handles the action and returns results. It may choose to delegate by indicated handled=false - React(action Action) (handled bool, ret runtime.Object, err error) -} - -// WatchReactor is an interface to allow the composition of watch functions. -type WatchReactor interface { - // Handles indicates whether or not this Reactor deals with a given action - Handles(action Action) bool - // React handles a watch action and returns results. It may choose to delegate by indicated handled=false - React(action Action) (handled bool, ret watch.Interface, err error) -} - -// ProxyReactor is an interface to allow the composition of proxy get functions. -type ProxyReactor interface { - // Handles indicates whether or not this Reactor deals with a given action - Handles(action Action) bool - // React handles a watch action and returns results. It may choose to delegate by indicated handled=false - React(action Action) (handled bool, ret client.ResponseWrapper, err error) -} - -// ReactionFunc is a function that returns an object or error for a given Action. If "handled" is false, -// then the test client will continue ignore the results and continue to the next ReactionFunc -type ReactionFunc func(action Action) (handled bool, ret runtime.Object, err error) - -// WatchReactionFunc is a function that returns a watch interface. If "handled" is false, -// then the test client will continue ignore the results and continue to the next ReactionFunc -type WatchReactionFunc func(action Action) (handled bool, ret watch.Interface, err error) - -// ProxyReactionFunc is a function that returns a ResponseWrapper interface for a given Action. If "handled" is false, -// then the test client will continue ignore the results and continue to the next ProxyReactionFunc -type ProxyReactionFunc func(action Action) (handled bool, ret client.ResponseWrapper, err error) - -// AddReactor appends a reactor to the end of the chain -func (c *Fake) AddReactor(verb, resource string, reaction ReactionFunc) { - c.ReactionChain = append(c.ReactionChain, &SimpleReactor{verb, resource, reaction}) -} - -// PrependReactor adds a reactor to the beginning of the chain -func (c *Fake) PrependReactor(verb, resource string, reaction ReactionFunc) { - c.ReactionChain = append([]Reactor{&SimpleReactor{verb, resource, reaction}}, c.ReactionChain...) -} - -// AddWatchReactor appends a reactor to the end of the chain -func (c *Fake) AddWatchReactor(resource string, reaction WatchReactionFunc) { - c.WatchReactionChain = append(c.WatchReactionChain, &SimpleWatchReactor{resource, reaction}) -} - -// PrependWatchReactor adds a reactor to the beginning of the chain -func (c *Fake) PrependWatchReactor(resource string, reaction WatchReactionFunc) { - c.WatchReactionChain = append([]WatchReactor{&SimpleWatchReactor{resource, reaction}}, c.WatchReactionChain...) -} - -// AddProxyReactor appends a reactor to the end of the chain -func (c *Fake) AddProxyReactor(resource string, reaction ProxyReactionFunc) { - c.ProxyReactionChain = append(c.ProxyReactionChain, &SimpleProxyReactor{resource, reaction}) -} - -// PrependProxyReactor adds a reactor to the beginning of the chain -func (c *Fake) PrependProxyReactor(resource string, reaction ProxyReactionFunc) { - c.ProxyReactionChain = append([]ProxyReactor{&SimpleProxyReactor{resource, reaction}}, c.ProxyReactionChain...) -} - -// Invokes records the provided Action and then invokes the ReactFn (if provided). -// defaultReturnObj is expected to be of the same type a normal call would return. -func (c *Fake) Invokes(action Action, defaultReturnObj runtime.Object) (runtime.Object, error) { - c.Lock() - defer c.Unlock() - - c.actions = append(c.actions, action) - for _, reactor := range c.ReactionChain { - if !reactor.Handles(action) { - continue - } - - handled, ret, err := reactor.React(action) - if !handled { - continue - } - - return ret, err - } - - return defaultReturnObj, nil -} - -// InvokesWatch records the provided Action and then invokes the ReactFn (if provided). -func (c *Fake) InvokesWatch(action Action) (watch.Interface, error) { - c.Lock() - defer c.Unlock() - - c.actions = append(c.actions, action) - for _, reactor := range c.WatchReactionChain { - if !reactor.Handles(action) { - continue - } - - handled, ret, err := reactor.React(action) - if !handled { - continue - } - - return ret, err - } - - return nil, fmt.Errorf("unhandled watch: %#v", action) -} - -// InvokesProxy records the provided Action and then invokes the ReactFn (if provided). -func (c *Fake) InvokesProxy(action Action) client.ResponseWrapper { - c.Lock() - defer c.Unlock() - - c.actions = append(c.actions, action) - for _, reactor := range c.ProxyReactionChain { - if !reactor.Handles(action) { - continue - } - - handled, ret, err := reactor.React(action) - if !handled || err != nil { - continue - } - - return ret - } - - return nil -} - -// ClearActions clears the history of actions called on the fake client -func (c *Fake) ClearActions() { - c.Lock() - c.Unlock() - - c.actions = make([]Action, 0) -} - -// Actions returns a chronologically ordered slice fake actions called on the fake client -func (c *Fake) Actions() []Action { - c.RLock() - defer c.RUnlock() - fa := make([]Action, len(c.actions)) - copy(fa, c.actions) - return fa -} - -func (c *Fake) LimitRanges(namespace string) client.LimitRangeInterface { - return &FakeLimitRanges{Fake: c, Namespace: namespace} -} - -func (c *Fake) ResourceQuotas(namespace string) client.ResourceQuotaInterface { - return &FakeResourceQuotas{Fake: c, Namespace: namespace} -} - -func (c *Fake) ReplicationControllers(namespace string) client.ReplicationControllerInterface { - return &FakeReplicationControllers{Fake: c, Namespace: namespace} -} - -func (c *Fake) Nodes() client.NodeInterface { - return &FakeNodes{Fake: c} -} - -func (c *Fake) PodSecurityPolicies() client.PodSecurityPolicyInterface { - return &FakePodSecurityPolicy{Fake: c} -} - -func (c *Fake) Events(namespace string) client.EventInterface { - return &FakeEvents{Fake: c, Namespace: namespace} -} - -func (c *Fake) Endpoints(namespace string) client.EndpointsInterface { - return &FakeEndpoints{Fake: c, Namespace: namespace} -} - -func (c *Fake) PersistentVolumes() client.PersistentVolumeInterface { - return &FakePersistentVolumes{Fake: c} -} - -func (c *Fake) PersistentVolumeClaims(namespace string) client.PersistentVolumeClaimInterface { - return &FakePersistentVolumeClaims{Fake: c, Namespace: namespace} -} - -func (c *Fake) Pods(namespace string) client.PodInterface { - return &FakePods{Fake: c, Namespace: namespace} -} - -func (c *Fake) PodTemplates(namespace string) client.PodTemplateInterface { - return &FakePodTemplates{Fake: c, Namespace: namespace} -} - -func (c *Fake) Services(namespace string) client.ServiceInterface { - return &FakeServices{Fake: c, Namespace: namespace} -} - -func (c *Fake) ServiceAccounts(namespace string) client.ServiceAccountsInterface { - return &FakeServiceAccounts{Fake: c, Namespace: namespace} -} - -func (c *Fake) Secrets(namespace string) client.SecretsInterface { - return &FakeSecrets{Fake: c, Namespace: namespace} -} - -func (c *Fake) Namespaces() client.NamespaceInterface { - return &FakeNamespaces{Fake: c} -} - -func (c *Fake) Autoscaling() client.AutoscalingInterface { - return &FakeAutoscaling{c} -} - -func (c *Fake) Extensions() client.ExtensionsInterface { - return &FakeExperimental{c} -} - -func (c *Fake) Discovery() client.DiscoveryInterface { - return &FakeDiscovery{c} -} - -func (c *Fake) ComponentStatuses() client.ComponentStatusInterface { - return &FakeComponentStatuses{Fake: c} -} - -func (c *Fake) ConfigMaps(namespace string) client.ConfigMapsInterface { - return &FakeConfigMaps{Fake: c, Namespace: namespace} -} - -// SwaggerSchema returns an empty swagger.ApiDeclaration for testing -func (c *Fake) SwaggerSchema(version unversioned.GroupVersion) (*swagger.ApiDeclaration, error) { - action := ActionImpl{} - action.Verb = "get" - if version == v1.SchemeGroupVersion { - action.Resource = "/swaggerapi/api/" + version.Version - } else { - action.Resource = "/swaggerapi/apis/" + version.Group + "/" + version.Version - } - - c.Invokes(action, nil) - return &swagger.ApiDeclaration{}, nil -} - -// NewSimpleFakeAutoscaling returns a client that will respond with the provided objects -func NewSimpleFakeAutoscaling(objects ...runtime.Object) *FakeAutoscaling { - return &FakeAutoscaling{Fake: NewSimpleFake(objects...)} -} - -type FakeAutoscaling struct { - *Fake -} - -func (c *FakeAutoscaling) HorizontalPodAutoscalers(namespace string) client.HorizontalPodAutoscalerInterface { - return &FakeHorizontalPodAutoscalersV1{Fake: c, Namespace: namespace} -} - -// NewSimpleFakeExp returns a client that will respond with the provided objects -func NewSimpleFakeExp(objects ...runtime.Object) *FakeExperimental { - return &FakeExperimental{Fake: NewSimpleFake(objects...)} -} - -type FakeExperimental struct { - *Fake -} - -func (c *FakeExperimental) DaemonSets(namespace string) client.DaemonSetInterface { - return &FakeDaemonSets{Fake: c, Namespace: namespace} -} - -func (c *FakeExperimental) HorizontalPodAutoscalers(namespace string) client.HorizontalPodAutoscalerInterface { - return &FakeHorizontalPodAutoscalers{Fake: c, Namespace: namespace} -} - -func (c *FakeExperimental) Deployments(namespace string) client.DeploymentInterface { - return &FakeDeployments{Fake: c, Namespace: namespace} -} - -func (c *FakeExperimental) Scales(namespace string) client.ScaleInterface { - return &FakeScales{Fake: c, Namespace: namespace} -} - -func (c *FakeExperimental) Jobs(namespace string) client.JobInterface { - return &FakeJobs{Fake: c, Namespace: namespace} -} - -func (c *FakeExperimental) Ingress(namespace string) client.IngressInterface { - return &FakeIngress{Fake: c, Namespace: namespace} -} - -func (c *FakeExperimental) ThirdPartyResources(namespace string) client.ThirdPartyResourceInterface { - return &FakeThirdPartyResources{Fake: c, Namespace: namespace} -} - -func (c *FakeExperimental) ReplicaSets(namespace string) client.ReplicaSetInterface { - return &FakeReplicaSets{Fake: c, Namespace: namespace} -} - -type FakeDiscovery struct { - *Fake -} - -func (c *FakeDiscovery) ServerResourcesForGroupVersion(groupVersion string) (*unversioned.APIResourceList, error) { - action := ActionImpl{ - Verb: "get", - Resource: "resource", - } - c.Invokes(action, nil) - return c.Resources[groupVersion], nil -} - -func (c *FakeDiscovery) ServerResources() (map[string]*unversioned.APIResourceList, error) { - action := ActionImpl{ - Verb: "get", - Resource: "resource", - } - c.Invokes(action, nil) - return c.Resources, nil -} - -func (c *FakeDiscovery) ServerGroups() (*unversioned.APIGroupList, error) { - return nil, nil -} - -func (c *FakeDiscovery) ServerVersion() (*version.Info, error) { - action := ActionImpl{} - action.Verb = "get" - action.Resource = "version" - - c.Invokes(action, nil) - versionInfo := version.Get() - return &versionInfo, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/testclient_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/testclient_test.go deleted file mode 100644 index b31bdc213..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/testclient/testclient_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testclient - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestNewClient(t *testing.T) { - o := NewObjects(api.Scheme, api.Codecs.UniversalDecoder()) - if err := AddObjectsFromPath("../../../../examples/guestbook/frontend-service.yaml", o, api.Codecs.UniversalDecoder()); err != nil { - t.Fatal(err) - } - client := &Fake{} - client.AddReactor("*", "*", ObjectReaction(o, testapi.Default.RESTMapper())) - list, err := client.Services("test").List(api.ListOptions{}) - if err != nil { - t.Fatal(err) - } - if len(list.Items) != 1 { - t.Fatalf("unexpected list %#v", list) - } - - // When list is invoked a second time, the same results are returned. - list, err = client.Services("test").List(api.ListOptions{}) - if err != nil { - t.Fatal(err) - } - if len(list.Items) != 1 { - t.Fatalf("unexpected list %#v", list) - } - t.Logf("list: %#v", list) -} - -func TestErrors(t *testing.T) { - o := NewObjects(api.Scheme, api.Codecs.UniversalDecoder()) - o.Add(&api.List{ - Items: []runtime.Object{ - // This first call to List will return this error - &(errors.NewNotFound(api.Resource("ServiceList"), "").(*errors.StatusError).ErrStatus), - // The second call to List will return this error - &(errors.NewForbidden(api.Resource("ServiceList"), "", nil).(*errors.StatusError).ErrStatus), - }, - }) - client := &Fake{} - client.AddReactor("*", "*", ObjectReaction(o, testapi.Default.RESTMapper())) - _, err := client.Services("test").List(api.ListOptions{}) - if !errors.IsNotFound(err) { - t.Fatalf("unexpected error: %v", err) - } - t.Logf("error: %#v", err.(*errors.StatusError).Status()) - _, err = client.Services("test").List(api.ListOptions{}) - if !errors.IsForbidden(err) { - t.Fatalf("unexpected error: %v", err) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/thirdpartyresources_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/thirdpartyresources_test.go deleted file mode 100644 index bf2e9e15c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/thirdpartyresources_test.go +++ /dev/null @@ -1,185 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package unversioned_test - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/extensions" - . "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" -) - -func getThirdPartyResourceName() string { - return "thirdpartyresources" -} - -func TestListThirdPartyResources(t *testing.T) { - ns := api.NamespaceAll - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Extensions.ResourcePath(getThirdPartyResourceName(), ns, ""), - }, - Response: simple.Response{StatusCode: 200, - Body: &extensions.ThirdPartyResourceList{ - Items: []extensions.ThirdPartyResource{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Description: "test third party resource", - }, - }, - }, - }, - } - receivedDSs, err := c.Setup(t).Extensions().ThirdPartyResources(ns).List(api.ListOptions{}) - defer c.Close() - c.Validate(t, receivedDSs, err) - -} - -func TestGetThirdPartyResource(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "GET", Path: testapi.Extensions.ResourcePath(getThirdPartyResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Description: "test third party resource", - }, - }, - } - receivedThirdPartyResource, err := c.Setup(t).Extensions().ThirdPartyResources(ns).Get("foo") - defer c.Close() - c.Validate(t, receivedThirdPartyResource, err) -} - -func TestGetThirdPartyResourceWithNoName(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{Error: true} - receivedPod, err := c.Setup(t).Extensions().ThirdPartyResources(ns).Get("") - defer c.Close() - if (err != nil) && (err.Error() != simple.NameRequiredError) { - t.Errorf("Expected error: %v, but got %v", simple.NameRequiredError, err) - } - - c.Validate(t, receivedPod, err) -} - -func TestUpdateThirdPartyResource(t *testing.T) { - ns := api.NamespaceDefault - requestThirdPartyResource := &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Extensions.ResourcePath(getThirdPartyResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Description: "test third party resource", - }, - }, - } - receivedThirdPartyResource, err := c.Setup(t).Extensions().ThirdPartyResources(ns).Update(requestThirdPartyResource) - defer c.Close() - c.Validate(t, receivedThirdPartyResource, err) -} - -func TestUpdateThirdPartyResourceUpdateStatus(t *testing.T) { - ns := api.NamespaceDefault - requestThirdPartyResource := &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "PUT", Path: testapi.Extensions.ResourcePath(getThirdPartyResourceName(), ns, "foo") + "/status", Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Description: "test third party resource", - }, - }, - } - receivedThirdPartyResource, err := c.Setup(t).Extensions().ThirdPartyResources(ns).UpdateStatus(requestThirdPartyResource) - defer c.Close() - c.Validate(t, receivedThirdPartyResource, err) -} - -func TestDeleteThirdPartyResource(t *testing.T) { - ns := api.NamespaceDefault - c := &simple.Client{ - Request: simple.Request{Method: "DELETE", Path: testapi.Extensions.ResourcePath(getThirdPartyResourceName(), ns, "foo"), Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{StatusCode: 200}, - } - err := c.Setup(t).Extensions().ThirdPartyResources(ns).Delete("foo") - defer c.Close() - c.Validate(t, nil, err) -} - -func TestCreateThirdPartyResource(t *testing.T) { - ns := api.NamespaceDefault - requestThirdPartyResource := &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - } - c := &simple.Client{ - Request: simple.Request{Method: "POST", Path: testapi.Extensions.ResourcePath(getThirdPartyResourceName(), ns, ""), Body: requestThirdPartyResource, Query: simple.BuildQueryValues(nil)}, - Response: simple.Response{ - StatusCode: 200, - Body: &extensions.ThirdPartyResource{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - "name": "baz", - }, - }, - Description: "test third party resource", - }, - }, - } - receivedThirdPartyResource, err := c.Setup(t).Extensions().ThirdPartyResources(ns).Create(requestThirdPartyResource) - defer c.Close() - c.Validate(t, receivedThirdPartyResource, err) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/urlbackoff_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/urlbackoff_test.go deleted file mode 100644 index 8457c977b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/unversioned/urlbackoff_test.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package unversioned - -import ( - "k8s.io/kubernetes/pkg/util" - "net/url" - "testing" - "time" -) - -func parse(raw string) *url.URL { - theUrl, _ := url.Parse(raw) - return theUrl -} - -func TestURLBackoffFunctionalityCollisions(t *testing.T) { - myBackoff := &URLBackoff{ - Backoff: util.NewBackOff(1*time.Second, 60*time.Second), - } - - // Add some noise and make sure backoff for a clean URL is zero. - myBackoff.UpdateBackoff(parse("http://100.200.300.400:8080"), nil, 500) - - myBackoff.UpdateBackoff(parse("http://1.2.3.4:8080"), nil, 500) - - if myBackoff.CalculateBackoff(parse("http://1.2.3.4:100")) > 0 { - t.Errorf("URLs are colliding in the backoff map!") - } -} - -// TestURLBackoffFunctionality generally tests the URLBackoff wrapper. We avoid duplicating tests from backoff and request. -func TestURLBackoffFunctionality(t *testing.T) { - myBackoff := &URLBackoff{ - Backoff: util.NewBackOff(1*time.Second, 60*time.Second), - } - - // Now test that backoff increases, then recovers. - // 200 and 300 should both result in clearing the backoff. - // all others like 429 should result in increased backoff. - seconds := []int{0, - 1, 2, 4, 8, 0, - 1, 2} - returnCodes := []int{ - 429, 500, 501, 502, 300, - 500, 501, 502, - } - - if len(seconds) != len(returnCodes) { - t.Fatalf("responseCode to backoff arrays should be the same length... sanity check failed.") - } - - for i, sec := range seconds { - backoffSec := myBackoff.CalculateBackoff(parse("http://1.2.3.4:100")) - if backoffSec < time.Duration(sec)*time.Second || backoffSec > time.Duration(sec+5)*time.Second { - t.Errorf("Backoff out of range %v: %v %v", i, sec, backoffSec) - } - myBackoff.UpdateBackoff(parse("http://1.2.3.4:100/responseCodeForFuncTest"), nil, returnCodes[i]) - } - - if myBackoff.CalculateBackoff(parse("http://1.2.3.4:100")) == 0 { - t.Errorf("The final return code %v should have resulted in a backoff ! ", returnCodes[7]) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/OWNERS b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/OWNERS new file mode 100644 index 000000000..31a963ed8 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/OWNERS @@ -0,0 +1,3 @@ +assignees: + - davidopp + - mikedanese diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/cloud.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/cloud.go index e145b26de..dd120735e 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/cloud.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/cloud.go @@ -84,7 +84,7 @@ type LoadBalancer interface { // if so, what its status is. GetLoadBalancer(name, region string) (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 - EnsureLoadBalancer(name, region string, loadBalancerIP net.IP, ports []*api.ServicePort, hosts []string, serviceName types.NamespacedName, affinityType api.ServiceAffinity) (*api.LoadBalancerStatus, error) + EnsureLoadBalancer(name, region string, loadBalancerIP net.IP, ports []*api.ServicePort, hosts []string, serviceName types.NamespacedName, affinityType api.ServiceAffinity, annotations map[string]string) (*api.LoadBalancerStatus, error) // UpdateLoadBalancer updates hosts under the specified load balancer. UpdateLoadBalancer(name, region string, hosts []string) error // EnsureLoadBalancerDeleted deletes the specified load balancer if it diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws.go deleted file mode 100644 index 9df66a2b7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws.go +++ /dev/null @@ -1,2380 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws - -import ( - "errors" - "fmt" - "io" - "net" - "net/url" - "os" - "regexp" - "strings" - "sync" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/elb" - "github.com/scalingdata/gcfg" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/cloudprovider" - "k8s.io/kubernetes/pkg/credentialprovider/aws" - "k8s.io/kubernetes/pkg/types" - "k8s.io/kubernetes/pkg/util/sets" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api/unversioned" -) - -const ProviderName = "aws" - -// The tag name we use to differentiate multiple logically independent clusters running in the same AZ -const TagNameKubernetesCluster = "KubernetesCluster" - -// The tag name we use to differentiate multiple services. Used currently for ELBs only. -const TagNameKubernetesService = "kubernetes.io/service-name" - -// We sometimes read to see if something exists; then try to create it if we didn't find it -// This can fail once in a consistent system if done in parallel -// In an eventually consistent system, it could fail unboundedly -// MaxReadThenCreateRetries sets the maximum number of attempts we will make -const MaxReadThenCreateRetries = 30 - -// Default volume type for newly created Volumes -// TODO: Remove when user/admin can configure volume types and thus we don't -// need hardcoded defaults. -const DefaultVolumeType = "gp2" - -// Used to call aws_credentials.Init() just once -var once sync.Once - -// Abstraction over AWS, to allow mocking/other implementations -type AWSServices interface { - Compute(region string) (EC2, error) - LoadBalancing(region string) (ELB, error) - Autoscaling(region string) (ASG, error) - Metadata() (EC2Metadata, error) -} - -// TODO: Should we rename this to AWS (EBS & ELB are not technically part of EC2) -// Abstraction over EC2, to allow mocking/other implementations -// Note that the DescribeX functions return a list, so callers don't need to deal with paging -type EC2 interface { - // Query EC2 for instances matching the filter - DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error) - - // Attach a volume to an instance - AttachVolume(*ec2.AttachVolumeInput) (*ec2.VolumeAttachment, error) - // Detach a volume from an instance it is attached to - DetachVolume(request *ec2.DetachVolumeInput) (resp *ec2.VolumeAttachment, err error) - // Lists volumes - DescribeVolumes(request *ec2.DescribeVolumesInput) ([]*ec2.Volume, error) - // Create an EBS volume - CreateVolume(request *ec2.CreateVolumeInput) (resp *ec2.Volume, err error) - // Delete an EBS volume - DeleteVolume(*ec2.DeleteVolumeInput) (*ec2.DeleteVolumeOutput, error) - - DescribeSecurityGroups(request *ec2.DescribeSecurityGroupsInput) ([]*ec2.SecurityGroup, error) - - CreateSecurityGroup(*ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) - DeleteSecurityGroup(request *ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error) - - AuthorizeSecurityGroupIngress(*ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) - RevokeSecurityGroupIngress(*ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) - - DescribeSubnets(*ec2.DescribeSubnetsInput) ([]*ec2.Subnet, error) - - CreateTags(*ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) - - DescribeRouteTables(request *ec2.DescribeRouteTablesInput) ([]*ec2.RouteTable, error) - CreateRoute(request *ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error) - DeleteRoute(request *ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error) - - ModifyInstanceAttribute(request *ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) -} - -// This is a simple pass-through of the ELB client interface, which allows for testing -type ELB interface { - CreateLoadBalancer(*elb.CreateLoadBalancerInput) (*elb.CreateLoadBalancerOutput, error) - DeleteLoadBalancer(*elb.DeleteLoadBalancerInput) (*elb.DeleteLoadBalancerOutput, error) - DescribeLoadBalancers(*elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error) - RegisterInstancesWithLoadBalancer(*elb.RegisterInstancesWithLoadBalancerInput) (*elb.RegisterInstancesWithLoadBalancerOutput, error) - DeregisterInstancesFromLoadBalancer(*elb.DeregisterInstancesFromLoadBalancerInput) (*elb.DeregisterInstancesFromLoadBalancerOutput, error) - - DetachLoadBalancerFromSubnets(*elb.DetachLoadBalancerFromSubnetsInput) (*elb.DetachLoadBalancerFromSubnetsOutput, error) - AttachLoadBalancerToSubnets(*elb.AttachLoadBalancerToSubnetsInput) (*elb.AttachLoadBalancerToSubnetsOutput, error) - - CreateLoadBalancerListeners(*elb.CreateLoadBalancerListenersInput) (*elb.CreateLoadBalancerListenersOutput, error) - DeleteLoadBalancerListeners(*elb.DeleteLoadBalancerListenersInput) (*elb.DeleteLoadBalancerListenersOutput, error) - - ApplySecurityGroupsToLoadBalancer(*elb.ApplySecurityGroupsToLoadBalancerInput) (*elb.ApplySecurityGroupsToLoadBalancerOutput, error) - - ConfigureHealthCheck(*elb.ConfigureHealthCheckInput) (*elb.ConfigureHealthCheckOutput, error) -} - -// This is a simple pass-through of the Autoscaling client interface, which allows for testing -type ASG interface { - UpdateAutoScalingGroup(*autoscaling.UpdateAutoScalingGroupInput) (*autoscaling.UpdateAutoScalingGroupOutput, error) - DescribeAutoScalingGroups(*autoscaling.DescribeAutoScalingGroupsInput) (*autoscaling.DescribeAutoScalingGroupsOutput, error) -} - -// Abstraction over the AWS metadata service -type EC2Metadata interface { - // Query the EC2 metadata service (used to discover instance-id etc) - GetMetadata(path string) (string, error) -} - -type VolumeOptions struct { - CapacityGB int - Tags *map[string]string -} - -// Volumes is an interface for managing cloud-provisioned volumes -// TODO: Allow other clouds to implement this -type Volumes interface { - // Attach the disk to the specified instance - // instanceName can be empty to mean "the instance on which we are running" - // Returns the device (e.g. /dev/xvdf) where we attached the volume - AttachDisk(diskName string, instanceName string, readOnly bool) (string, error) - // Detach the disk from the specified instance - // instanceName can be empty to mean "the instance on which we are running" - // Returns the device where the volume was attached - DetachDisk(diskName string, instanceName string) (string, error) - - // Create a volume with the specified options - CreateDisk(volumeOptions *VolumeOptions) (volumeName string, err error) - // Delete the specified volume - // Returns true iff the volume was deleted - // If the was not found, returns (false, nil) - DeleteDisk(volumeName string) (bool, error) - - // Get labels to apply to volume on creation - GetVolumeLabels(volumeName string) (map[string]string, error) -} - -// InstanceGroups is an interface for managing cloud-managed instance groups / autoscaling instance groups -// TODO: Allow other clouds to implement this -type InstanceGroups interface { - // Set the size to the fixed size - ResizeInstanceGroup(instanceGroupName string, size int) error - // Queries the cloud provider for information about the specified instance group - DescribeInstanceGroup(instanceGroupName string) (InstanceGroupInfo, error) -} - -// InstanceGroupInfo is returned by InstanceGroups.Describe, and exposes information about the group. -type InstanceGroupInfo interface { - // The number of instances currently running under control of this group - CurrentSize() (int, error) -} - -// AWSCloud is an implementation of Interface, LoadBalancer and Instances for Amazon Web Services. -type AWSCloud struct { - ec2 EC2 - elb ELB - asg ASG - metadata EC2Metadata - cfg *AWSCloudConfig - availabilityZone string - region string - - filterTags map[string]string - - // The AWS instance that we are running on - selfAWSInstance *awsInstance - - mutex sync.Mutex -} - -var _ Volumes = &AWSCloud{} - -type AWSCloudConfig struct { - Global struct { - // TODO: Is there any use for this? We can get it from the instance metadata service - // Maybe if we're not running on AWS, e.g. bootstrap; for now it is not very useful - Zone string - - KubernetesClusterTag string - } -} - -// awsSdkEC2 is an implementation of the EC2 interface, backed by aws-sdk-go -type awsSdkEC2 struct { - ec2 *ec2.EC2 -} - -type awsSDKProvider struct { - creds *credentials.Credentials -} - -func addHandlers(h *request.Handlers) { - h.Sign.PushFrontNamed(request.NamedHandler{ - Name: "k8s/logger", - Fn: awsHandlerLogger, - }) -} - -func (p *awsSDKProvider) Compute(regionName string) (EC2, error) { - service := ec2.New(session.New(&aws.Config{ - Region: ®ionName, - Credentials: p.creds, - })) - - addHandlers(&service.Handlers) - - ec2 := &awsSdkEC2{ - ec2: service, - } - return ec2, nil -} - -func (p *awsSDKProvider) LoadBalancing(regionName string) (ELB, error) { - elbClient := elb.New(session.New(&aws.Config{ - Region: ®ionName, - Credentials: p.creds, - })) - - addHandlers(&elbClient.Handlers) - - return elbClient, nil -} - -func (p *awsSDKProvider) Autoscaling(regionName string) (ASG, error) { - client := autoscaling.New(session.New(&aws.Config{ - Region: ®ionName, - Credentials: p.creds, - })) - - addHandlers(&client.Handlers) - - return client, nil -} - -func (p *awsSDKProvider) Metadata() (EC2Metadata, error) { - client := ec2metadata.New(session.New(&aws.Config{})) - return client, nil -} - -func stringPointerArray(orig []string) []*string { - if orig == nil { - return nil - } - n := make([]*string, len(orig)) - for i := range orig { - n[i] = &orig[i] - } - return n -} - -func isNilOrEmpty(s *string) bool { - return s == nil || *s == "" -} - -func orEmpty(s *string) string { - if s == nil { - return "" - } - return *s -} - -func newEc2Filter(name string, value string) *ec2.Filter { - filter := &ec2.Filter{ - Name: aws.String(name), - Values: []*string{ - aws.String(value), - }, - } - return filter -} - -func (self *AWSCloud) AddSSHKeyToAllInstances(user string, keyData []byte) error { - return errors.New("unimplemented") -} - -func (a *AWSCloud) CurrentNodeName(hostname string) (string, error) { - selfInstance, err := a.getSelfAWSInstance() - if err != nil { - return "", err - } - return selfInstance.nodeName, nil -} - -// Implementation of EC2.Instances -func (self *awsSdkEC2) DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error) { - // Instances are paged - results := []*ec2.Instance{} - var nextToken *string - - for { - response, err := self.ec2.DescribeInstances(request) - if err != nil { - return nil, fmt.Errorf("error listing AWS instances: %v", err) - } - - for _, reservation := range response.Reservations { - results = append(results, reservation.Instances...) - } - - nextToken = response.NextToken - if isNilOrEmpty(nextToken) { - break - } - request.NextToken = nextToken - } - - return results, nil -} - -// Implements EC2.DescribeSecurityGroups -func (s *awsSdkEC2) DescribeSecurityGroups(request *ec2.DescribeSecurityGroupsInput) ([]*ec2.SecurityGroup, error) { - // Security groups are not paged - response, err := s.ec2.DescribeSecurityGroups(request) - if err != nil { - return nil, fmt.Errorf("error listing AWS security groups: %v", err) - } - return response.SecurityGroups, nil -} - -func (s *awsSdkEC2) AttachVolume(request *ec2.AttachVolumeInput) (*ec2.VolumeAttachment, error) { - return s.ec2.AttachVolume(request) -} - -func (s *awsSdkEC2) DetachVolume(request *ec2.DetachVolumeInput) (*ec2.VolumeAttachment, error) { - return s.ec2.DetachVolume(request) -} - -func (s *awsSdkEC2) DescribeVolumes(request *ec2.DescribeVolumesInput) ([]*ec2.Volume, error) { - // Volumes are paged - results := []*ec2.Volume{} - var nextToken *string - - for { - response, err := s.ec2.DescribeVolumes(request) - - if err != nil { - return nil, fmt.Errorf("error listing AWS volumes: %v", err) - } - - results = append(results, response.Volumes...) - - nextToken = response.NextToken - if isNilOrEmpty(nextToken) { - break - } - request.NextToken = nextToken - } - - return results, nil -} - -func (s *awsSdkEC2) CreateVolume(request *ec2.CreateVolumeInput) (resp *ec2.Volume, err error) { - return s.ec2.CreateVolume(request) -} - -func (s *awsSdkEC2) DeleteVolume(request *ec2.DeleteVolumeInput) (*ec2.DeleteVolumeOutput, error) { - return s.ec2.DeleteVolume(request) -} - -func (s *awsSdkEC2) DescribeSubnets(request *ec2.DescribeSubnetsInput) ([]*ec2.Subnet, error) { - // Subnets are not paged - response, err := s.ec2.DescribeSubnets(request) - if err != nil { - return nil, fmt.Errorf("error listing AWS subnets: %v", err) - } - return response.Subnets, nil -} - -func (s *awsSdkEC2) CreateSecurityGroup(request *ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) { - return s.ec2.CreateSecurityGroup(request) -} - -func (s *awsSdkEC2) DeleteSecurityGroup(request *ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error) { - return s.ec2.DeleteSecurityGroup(request) -} - -func (s *awsSdkEC2) AuthorizeSecurityGroupIngress(request *ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) { - return s.ec2.AuthorizeSecurityGroupIngress(request) -} - -func (s *awsSdkEC2) RevokeSecurityGroupIngress(request *ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) { - return s.ec2.RevokeSecurityGroupIngress(request) -} - -func (s *awsSdkEC2) CreateTags(request *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) { - return s.ec2.CreateTags(request) -} - -func (s *awsSdkEC2) DescribeRouteTables(request *ec2.DescribeRouteTablesInput) ([]*ec2.RouteTable, error) { - // Not paged - response, err := s.ec2.DescribeRouteTables(request) - if err != nil { - return nil, fmt.Errorf("error listing AWS route tables: %v", err) - } - return response.RouteTables, nil -} - -func (s *awsSdkEC2) CreateRoute(request *ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error) { - return s.ec2.CreateRoute(request) -} - -func (s *awsSdkEC2) DeleteRoute(request *ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error) { - return s.ec2.DeleteRoute(request) -} - -func (s *awsSdkEC2) ModifyInstanceAttribute(request *ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) { - return s.ec2.ModifyInstanceAttribute(request) -} - -func init() { - cloudprovider.RegisterCloudProvider(ProviderName, func(config io.Reader) (cloudprovider.Interface, error) { - creds := credentials.NewChainCredentials( - []credentials.Provider{ - &credentials.EnvProvider{}, - &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.New(session.New(&aws.Config{})), - }, - &credentials.SharedCredentialsProvider{}, - }) - aws := &awsSDKProvider{creds: creds} - return newAWSCloud(config, aws) - }) -} - -// readAWSCloudConfig reads an instance of AWSCloudConfig from config reader. -func readAWSCloudConfig(config io.Reader, metadata EC2Metadata) (*AWSCloudConfig, error) { - var cfg AWSCloudConfig - var err error - - if config != nil { - err = gcfg.ReadInto(&cfg, config) - if err != nil { - return nil, err - } - } - - if cfg.Global.Zone == "" { - if metadata != nil { - glog.Info("Zone not specified in configuration file; querying AWS metadata service") - cfg.Global.Zone, err = getAvailabilityZone(metadata) - if err != nil { - return nil, err - } - } - if cfg.Global.Zone == "" { - return nil, fmt.Errorf("no zone specified in configuration file") - } - } - - return &cfg, nil -} - -func getInstanceType(metadata EC2Metadata) (string, error) { - return metadata.GetMetadata("instance-type") -} - -func getAvailabilityZone(metadata EC2Metadata) (string, error) { - return metadata.GetMetadata("placement/availability-zone") -} - -func isRegionValid(region string) bool { - regions := [...]string{ - "us-east-1", - "us-west-1", - "us-west-2", - "eu-west-1", - "eu-central-1", - "ap-southeast-1", - "ap-southeast-2", - "ap-northeast-1", - "cn-north-1", - "us-gov-west-1", - "sa-east-1", - } - for _, r := range regions { - if r == region { - return true - } - } - return false -} - -// Derives the region from a valid az name. -// Returns an error if the az is known invalid (empty) -func azToRegion(az string) (string, error) { - if len(az) < 1 { - return "", fmt.Errorf("invalid (empty) AZ") - } - region := az[:len(az)-1] - return region, nil -} - -// newAWSCloud creates a new instance of AWSCloud. -// AWSProvider and instanceId are primarily for tests -func newAWSCloud(config io.Reader, awsServices AWSServices) (*AWSCloud, error) { - metadata, err := awsServices.Metadata() - if err != nil { - return nil, fmt.Errorf("error creating AWS metadata client: %v", err) - } - - cfg, err := readAWSCloudConfig(config, metadata) - if err != nil { - return nil, fmt.Errorf("unable to read AWS cloud provider config file: %v", err) - } - - zone := cfg.Global.Zone - if len(zone) <= 1 { - return nil, fmt.Errorf("invalid AWS zone in config file: %s", zone) - } - regionName, err := azToRegion(zone) - if err != nil { - return nil, err - } - - valid := isRegionValid(regionName) - if !valid { - return nil, fmt.Errorf("not a valid AWS zone (unknown region): %s", zone) - } - - ec2, err := awsServices.Compute(regionName) - if err != nil { - return nil, fmt.Errorf("error creating AWS EC2 client: %v", err) - } - - elb, err := awsServices.LoadBalancing(regionName) - if err != nil { - return nil, fmt.Errorf("error creating AWS ELB client: %v", err) - } - - asg, err := awsServices.Autoscaling(regionName) - if err != nil { - return nil, fmt.Errorf("error creating AWS autoscaling client: %v", err) - } - - awsCloud := &AWSCloud{ - ec2: ec2, - elb: elb, - asg: asg, - metadata: metadata, - cfg: cfg, - region: regionName, - availabilityZone: zone, - } - - filterTags := map[string]string{} - if cfg.Global.KubernetesClusterTag != "" { - filterTags[TagNameKubernetesCluster] = cfg.Global.KubernetesClusterTag - } else { - selfInstance, err := awsCloud.getSelfAWSInstance() - if err != nil { - return nil, err - } - selfInstanceInfo, err := selfInstance.getInfo() - if err != nil { - return nil, err - } - for _, tag := range selfInstanceInfo.Tags { - if orEmpty(tag.Key) == TagNameKubernetesCluster { - filterTags[TagNameKubernetesCluster] = orEmpty(tag.Value) - } - } - } - - awsCloud.filterTags = filterTags - if len(filterTags) > 0 { - glog.Infof("AWS cloud filtering on tags: %v", filterTags) - } else { - glog.Infof("AWS cloud - no tag filtering") - } - - // Register handler for ECR credentials - once.Do(func() { - aws_credentials.Init() - }) - - return awsCloud, nil -} - -func (aws *AWSCloud) Clusters() (cloudprovider.Clusters, bool) { - return nil, false -} - -// ProviderName returns the cloud provider ID. -func (aws *AWSCloud) ProviderName() string { - return ProviderName -} - -// ScrubDNS filters DNS settings for pods. -func (aws *AWSCloud) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) { - return nameservers, searches -} - -// LoadBalancer returns an implementation of LoadBalancer for Amazon Web Services. -func (s *AWSCloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) { - return s, true -} - -// Instances returns an implementation of Instances for Amazon Web Services. -func (aws *AWSCloud) Instances() (cloudprovider.Instances, bool) { - return aws, true -} - -// Zones returns an implementation of Zones for Amazon Web Services. -func (aws *AWSCloud) Zones() (cloudprovider.Zones, bool) { - return aws, true -} - -// Routes returns an implementation of Routes for Amazon Web Services. -func (aws *AWSCloud) Routes() (cloudprovider.Routes, bool) { - return aws, true -} - -// NodeAddresses is an implementation of Instances.NodeAddresses. -func (aws *AWSCloud) NodeAddresses(name string) ([]api.NodeAddress, error) { - self, err := aws.getSelfAWSInstance() - if err != nil { - return nil, err - } - if self.nodeName == name || len(name) == 0 { - addresses := []api.NodeAddress{} - - internalIP, err := aws.metadata.GetMetadata("local-ipv4") - if err != nil { - return nil, err - } - addresses = append(addresses, api.NodeAddress{Type: api.NodeInternalIP, Address: internalIP}) - // Legacy compatibility: the private ip was the legacy host ip - addresses = append(addresses, api.NodeAddress{Type: api.NodeLegacyHostIP, Address: internalIP}) - - externalIP, err := aws.metadata.GetMetadata("public-ipv4") - if err != nil { - //TODO: It would be nice to be able to determine the reason for the failure, - // but the AWS client masks all failures with the same error description. - glog.V(2).Info("Could not determine public IP from AWS metadata.") - } else { - addresses = append(addresses, api.NodeAddress{Type: api.NodeExternalIP, Address: externalIP}) - } - - return addresses, nil - } - instance, err := aws.getInstanceByNodeName(name) - if err != nil { - return nil, err - } - - addresses := []api.NodeAddress{} - - if !isNilOrEmpty(instance.PrivateIpAddress) { - ipAddress := *instance.PrivateIpAddress - ip := net.ParseIP(ipAddress) - if ip == nil { - return nil, fmt.Errorf("EC2 instance had invalid private address: %s (%s)", orEmpty(instance.InstanceId), ipAddress) - } - addresses = append(addresses, api.NodeAddress{Type: api.NodeInternalIP, Address: ip.String()}) - - // Legacy compatibility: the private ip was the legacy host ip - addresses = append(addresses, api.NodeAddress{Type: api.NodeLegacyHostIP, Address: ip.String()}) - } - - // TODO: Other IP addresses (multiple ips)? - if !isNilOrEmpty(instance.PublicIpAddress) { - ipAddress := *instance.PublicIpAddress - ip := net.ParseIP(ipAddress) - if ip == nil { - return nil, fmt.Errorf("EC2 instance had invalid public address: %s (%s)", orEmpty(instance.InstanceId), ipAddress) - } - addresses = append(addresses, api.NodeAddress{Type: api.NodeExternalIP, Address: ip.String()}) - } - - return addresses, nil -} - -// ExternalID returns the cloud provider ID of the specified instance (deprecated). -func (aws *AWSCloud) ExternalID(name string) (string, error) { - awsInstance, err := aws.getSelfAWSInstance() - if err != nil { - return "", err - } - - if awsInstance.nodeName == name { - // We assume that if this is run on the instance itself, the instance exists and is alive - return awsInstance.awsID, nil - } else { - // We must verify that the instance still exists - // Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) - instance, err := aws.findInstanceByNodeName(name) - if err != nil { - return "", err - } - if instance == nil || !isAlive(instance) { - return "", cloudprovider.InstanceNotFound - } - return orEmpty(instance.InstanceId), nil - } -} - -// InstanceID returns the cloud provider ID of the specified instance. -func (aws *AWSCloud) InstanceID(name string) (string, error) { - awsInstance, err := aws.getSelfAWSInstance() - if err != nil { - return "", err - } - - // In the future it is possible to also return an endpoint as: - // // - if awsInstance.nodeName == name { - return "/" + awsInstance.availabilityZone + "/" + awsInstance.awsID, nil - } else { - inst, err := aws.getInstanceByNodeName(name) - if err != nil { - return "", err - } - return "/" + orEmpty(inst.Placement.AvailabilityZone) + "/" + orEmpty(inst.InstanceId), nil - } -} - -// InstanceType returns the type of the specified instance. -func (aws *AWSCloud) InstanceType(name string) (string, error) { - awsInstance, err := aws.getSelfAWSInstance() - if err != nil { - return "", err - } - - if awsInstance.nodeName == name { - return awsInstance.instanceType, nil - } else { - inst, err := aws.getInstanceByNodeName(name) - if err != nil { - return "", err - } - return orEmpty(inst.InstanceType), nil - } -} - -// Check if the instance is alive (running or pending) -// We typically ignore instances that are not alive -func isAlive(instance *ec2.Instance) bool { - if instance.State == nil { - glog.Warning("Instance state was unexpectedly nil: ", instance) - return false - } - stateName := orEmpty(instance.State.Name) - switch stateName { - case "shutting-down", "terminated", "stopping", "stopped": - return false - case "pending", "running": - return true - default: - glog.Errorf("Unknown EC2 instance state: %s", stateName) - return false - } -} - -// Return a list of instances matching regex string. -func (s *AWSCloud) getInstancesByRegex(regex string) ([]string, error) { - filters := []*ec2.Filter{} - filters = s.addFilters(filters) - request := &ec2.DescribeInstancesInput{ - Filters: filters, - } - - instances, err := s.ec2.DescribeInstances(request) - if err != nil { - return []string{}, err - } - if len(instances) == 0 { - return []string{}, fmt.Errorf("no instances returned") - } - - if strings.HasPrefix(regex, "'") && strings.HasSuffix(regex, "'") { - glog.Infof("Stripping quotes around regex (%s)", regex) - regex = regex[1 : len(regex)-1] - } - - re, err := regexp.Compile(regex) - if err != nil { - return []string{}, err - } - - matchingInstances := []string{} - for _, instance := range instances { - // TODO: Push filtering down into EC2 API filter? - if !isAlive(instance) { - continue - } - - // Only return fully-ready instances when listing instances - // (vs a query by name, where we will return it if we find it) - if orEmpty(instance.State.Name) == "pending" { - glog.V(2).Infof("Skipping EC2 instance (pending): %s", *instance.InstanceId) - continue - } - - privateDNSName := orEmpty(instance.PrivateDnsName) - if privateDNSName == "" { - glog.V(2).Infof("Skipping EC2 instance (no PrivateDNSName): %s", - orEmpty(instance.InstanceId)) - continue - } - - for _, tag := range instance.Tags { - if orEmpty(tag.Key) == "Name" && re.MatchString(orEmpty(tag.Value)) { - matchingInstances = append(matchingInstances, privateDNSName) - break - } - } - } - glog.V(2).Infof("Matched EC2 instances: %s", matchingInstances) - return matchingInstances, nil -} - -// List is an implementation of Instances.List. -func (aws *AWSCloud) List(filter string) ([]string, error) { - // TODO: Should really use tag query. No need to go regexp. - return aws.getInstancesByRegex(filter) -} - -// GetZone implements Zones.GetZone -func (self *AWSCloud) GetZone() (cloudprovider.Zone, error) { - return cloudprovider.Zone{ - FailureDomain: self.availabilityZone, - Region: self.region, - }, nil -} - -// Abstraction around AWS Instance Types -// There isn't an API to get information for a particular instance type (that I know of) -type awsInstanceType struct { -} - -// Used to represent a mount device for attaching an EBS volume -// This should be stored as a single letter (i.e. c, not sdc or /dev/sdc) -type mountDevice string - -// TODO: Also return number of mounts allowed? -func (self *awsInstanceType) getEBSMountDevices() []mountDevice { - // See: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html - devices := []mountDevice{} - for c := 'f'; c <= 'p'; c++ { - devices = append(devices, mountDevice(fmt.Sprintf("%c", c))) - } - return devices -} - -type awsInstance struct { - ec2 EC2 - - // id in AWS - awsID string - - // node name in k8s - nodeName string - - // availability zone the instance resides in - availabilityZone string - - // instance type - instanceType string - - mutex sync.Mutex - - // We must cache because otherwise there is a race condition, - // where we assign a device mapping and then get a second request before we attach the volume - deviceMappings map[mountDevice]string -} - -func newAWSInstance(ec2 EC2, awsID, nodeName, availabilityZone, instanceType string) *awsInstance { - self := &awsInstance{ec2: ec2, awsID: awsID, nodeName: nodeName, availabilityZone: availabilityZone, instanceType: instanceType} - - // We lazy-init deviceMappings - self.deviceMappings = nil - - return self -} - -// Gets the awsInstanceType that models the instance type of this instance -func (self *awsInstance) getInstanceType() *awsInstanceType { - // TODO: Make this real - awsInstanceType := &awsInstanceType{} - return awsInstanceType -} - -// Gets the full information about this instance from the EC2 API -func (self *awsInstance) getInfo() (*ec2.Instance, error) { - instanceID := self.awsID - request := &ec2.DescribeInstancesInput{ - InstanceIds: []*string{&instanceID}, - } - - instances, err := self.ec2.DescribeInstances(request) - if err != nil { - return nil, err - } - if len(instances) == 0 { - return nil, fmt.Errorf("no instances found for instance: %s", self.awsID) - } - if len(instances) > 1 { - return nil, fmt.Errorf("multiple instances found for instance: %s", self.awsID) - } - return instances[0], nil -} - -// Gets the mountDevice already assigned to the volume, or assigns an unused mountDevice. -// If the volume is already assigned, this will return the existing mountDevice with alreadyAttached=true. -// Otherwise the mountDevice is assigned by finding the first available mountDevice, and it is returned with alreadyAttached=false. -func (self *awsInstance) getMountDevice(volumeID string, assign bool) (assigned mountDevice, alreadyAttached bool, err error) { - instanceType := self.getInstanceType() - if instanceType == nil { - return "", false, fmt.Errorf("could not get instance type for instance: %s", self.awsID) - } - - // We lock to prevent concurrent mounts from conflicting - // We may still conflict if someone calls the API concurrently, - // but the AWS API will then fail one of the two attach operations - self.mutex.Lock() - defer self.mutex.Unlock() - - // We cache both for efficiency and correctness - if self.deviceMappings == nil { - info, err := self.getInfo() - if err != nil { - return "", false, err - } - deviceMappings := map[mountDevice]string{} - for _, blockDevice := range info.BlockDeviceMappings { - name := aws.StringValue(blockDevice.DeviceName) - if strings.HasPrefix(name, "/dev/sd") { - name = name[7:] - } - if strings.HasPrefix(name, "/dev/xvd") { - name = name[8:] - } - if len(name) != 1 { - glog.Warningf("Unexpected EBS DeviceName: %q", aws.StringValue(blockDevice.DeviceName)) - } - deviceMappings[mountDevice(name)] = aws.StringValue(blockDevice.Ebs.VolumeId) - } - self.deviceMappings = deviceMappings - } - - // Check to see if this volume is already assigned a device on this machine - for mountDevice, mappingVolumeID := range self.deviceMappings { - if volumeID == mappingVolumeID { - if assign { - glog.Warningf("Got assignment call for already-assigned volume: %s@%s", mountDevice, mappingVolumeID) - } - return mountDevice, true, nil - } - } - - if !assign { - return mountDevice(""), false, nil - } - - // Check all the valid mountpoints to see if any of them are free - valid := instanceType.getEBSMountDevices() - chosen := mountDevice("") - for _, mountDevice := range valid { - _, found := self.deviceMappings[mountDevice] - if !found { - chosen = mountDevice - break - } - } - - if chosen == "" { - glog.Warningf("Could not assign a mount device (all in use?). mappings=%v, valid=%v", self.deviceMappings, valid) - return "", false, nil - } - - self.deviceMappings[chosen] = volumeID - glog.V(2).Infof("Assigned mount device %s -> volume %s", chosen, volumeID) - - return chosen, false, nil -} - -func (self *awsInstance) releaseMountDevice(volumeID string, mountDevice mountDevice) { - self.mutex.Lock() - defer self.mutex.Unlock() - - existingVolumeID, found := self.deviceMappings[mountDevice] - if !found { - glog.Errorf("releaseMountDevice on non-allocated device") - return - } - if volumeID != existingVolumeID { - glog.Errorf("releaseMountDevice on device assigned to different volume") - return - } - glog.V(2).Infof("Releasing mount device mapping: %s -> volume %s", mountDevice, volumeID) - delete(self.deviceMappings, mountDevice) -} - -type awsDisk struct { - ec2 EC2 - - // Name in k8s - name string - // id in AWS - awsID string - // az which holds the volume - az string -} - -func newAWSDisk(aws *AWSCloud, name string) (*awsDisk, error) { - if !strings.HasPrefix(name, "aws://") { - name = "aws://" + aws.availabilityZone + "/" + name - } - // name looks like aws://availability-zone/id - url, err := url.Parse(name) - if err != nil { - // TODO: Maybe we should pass a URL into the Volume functions - return nil, fmt.Errorf("Invalid disk name (%s): %v", name, err) - } - if url.Scheme != "aws" { - return nil, fmt.Errorf("Invalid scheme for AWS volume (%s)", name) - } - - awsID := url.Path - if len(awsID) > 1 && awsID[0] == '/' { - awsID = awsID[1:] - } - - // TODO: Regex match? - if strings.Contains(awsID, "/") || !strings.HasPrefix(awsID, "vol-") { - return nil, fmt.Errorf("Invalid format for AWS volume (%s)", name) - } - az := url.Host - // TODO: Better validation? - // TODO: Default to our AZ? Look it up? - // TODO: Should this be a region or an AZ? - if az == "" { - return nil, fmt.Errorf("Invalid format for AWS volume (%s)", name) - } - disk := &awsDisk{ec2: aws.ec2, name: name, awsID: awsID, az: az} - return disk, nil -} - -// Gets the full information about this volume from the EC2 API -func (self *awsDisk) getInfo() (*ec2.Volume, error) { - volumeID := self.awsID - - request := &ec2.DescribeVolumesInput{ - VolumeIds: []*string{&volumeID}, - } - - volumes, err := self.ec2.DescribeVolumes(request) - if err != nil { - return nil, fmt.Errorf("error querying ec2 for volume info: %v", err) - } - if len(volumes) == 0 { - return nil, fmt.Errorf("no volumes found for volume: %s", self.awsID) - } - if len(volumes) > 1 { - return nil, fmt.Errorf("multiple volumes found for volume: %s", self.awsID) - } - return volumes[0], nil -} - -func (self *awsDisk) waitForAttachmentStatus(status string) error { - // TODO: There may be a faster way to get this when we're attaching locally - attempt := 0 - maxAttempts := 60 - - for { - info, err := self.getInfo() - if err != nil { - return err - } - if len(info.Attachments) > 1 { - glog.Warningf("Found multiple attachments for volume: %v", info) - } - attachmentStatus := "" - for _, attachment := range info.Attachments { - if attachmentStatus != "" { - glog.Warning("Found multiple attachments: ", info) - } - if attachment.State != nil { - attachmentStatus = *attachment.State - } else { - // Shouldn't happen, but don't panic... - glog.Warning("Ignoring nil attachment state: ", attachment) - } - } - if attachmentStatus == "" { - attachmentStatus = "detached" - } - if attachmentStatus == status { - return nil - } - - glog.V(2).Infof("Waiting for volume state: actual=%s, desired=%s", attachmentStatus, status) - - attempt++ - if attempt > maxAttempts { - glog.Warningf("Timeout waiting for volume state: actual=%s, desired=%s", attachmentStatus, status) - return errors.New("Timeout waiting for volume state") - } - - time.Sleep(1 * time.Second) - } -} - -// Deletes the EBS disk -func (self *awsDisk) deleteVolume() (bool, error) { - request := &ec2.DeleteVolumeInput{VolumeId: aws.String(self.awsID)} - _, err := self.ec2.DeleteVolume(request) - if err != nil { - if awsError, ok := err.(awserr.Error); ok { - if awsError.Code() == "InvalidVolume.NotFound" { - return false, nil - } - } - return false, fmt.Errorf("error deleting EBS volumes: %v", err) - } - return true, nil -} - -// Gets the awsInstance for the EC2 instance on which we are running -// may return nil in case of error -func (s *AWSCloud) getSelfAWSInstance() (*awsInstance, error) { - // Note that we cache some state in awsInstance (mountpoints), so we must preserve the instance - - s.mutex.Lock() - defer s.mutex.Unlock() - - i := s.selfAWSInstance - if i == nil { - instanceId, err := s.metadata.GetMetadata("instance-id") - if err != nil { - return nil, fmt.Errorf("error fetching instance-id from ec2 metadata service: %v", err) - } - // privateDnsName, err := s.metadata.GetMetadata("local-hostname") - // See #11543 - need to use ec2 API to get the privateDnsName in case of private dns zone e.g. mydomain.io - instance, err := s.getInstanceByID(instanceId) - if err != nil { - return nil, fmt.Errorf("error finding instance %s: %v", instanceId, err) - } - privateDnsName := aws.StringValue(instance.PrivateDnsName) - availabilityZone, err := getAvailabilityZone(s.metadata) - if err != nil { - return nil, fmt.Errorf("error fetching availability zone from ec2 metadata service: %v", err) - } - instanceType, err := getInstanceType(s.metadata) - if err != nil { - return nil, fmt.Errorf("error fetching instance type from ec2 metadata service: %v", err) - } - - i = newAWSInstance(s.ec2, instanceId, privateDnsName, availabilityZone, instanceType) - s.selfAWSInstance = i - } - - return i, nil -} - -// Gets the awsInstance with node-name nodeName, or the 'self' instance if nodeName == "" -func (aws *AWSCloud) getAwsInstance(nodeName string) (*awsInstance, error) { - var awsInstance *awsInstance - var err error - if nodeName == "" { - awsInstance, err = aws.getSelfAWSInstance() - if err != nil { - return nil, fmt.Errorf("error getting self-instance: %v", err) - } - } else { - instance, err := aws.getInstanceByNodeName(nodeName) - if err != nil { - return nil, fmt.Errorf("error finding instance %s: %v", nodeName, err) - } - - awsInstance = newAWSInstance(aws.ec2, orEmpty(instance.InstanceId), orEmpty(instance.PrivateDnsName), orEmpty(instance.Placement.AvailabilityZone), orEmpty(instance.InstanceType)) - } - - return awsInstance, nil -} - -// Implements Volumes.AttachDisk -func (c *AWSCloud) AttachDisk(diskName string, instanceName string, readOnly bool) (string, error) { - disk, err := newAWSDisk(c, diskName) - if err != nil { - return "", err - } - - awsInstance, err := c.getAwsInstance(instanceName) - if err != nil { - return "", err - } - - if readOnly { - // TODO: We could enforce this when we mount the volume (?) - // TODO: We could also snapshot the volume and attach copies of it - return "", errors.New("AWS volumes cannot be mounted read-only") - } - - mountDevice, alreadyAttached, err := awsInstance.getMountDevice(disk.awsID, true) - if err != nil { - return "", err - } - - // Inside the instance, the mountpoint always looks like /dev/xvdX (?) - hostDevice := "/dev/xvd" + string(mountDevice) - // In the EC2 API, it is sometimes is /dev/sdX and sometimes /dev/xvdX - // We are running on the node here, so we check if /dev/xvda exists to determine this - ec2Device := "/dev/xvd" + string(mountDevice) - if _, err := os.Stat("/dev/xvda"); os.IsNotExist(err) { - ec2Device = "/dev/sd" + string(mountDevice) - } - - attached := false - defer func() { - if !attached { - awsInstance.releaseMountDevice(disk.awsID, mountDevice) - } - }() - - if !alreadyAttached { - request := &ec2.AttachVolumeInput{ - Device: aws.String(ec2Device), - InstanceId: aws.String(awsInstance.awsID), - VolumeId: aws.String(disk.awsID), - } - - attachResponse, err := c.ec2.AttachVolume(request) - if err != nil { - // TODO: Check if the volume was concurrently attached? - return "", fmt.Errorf("Error attaching EBS volume: %v", err) - } - - glog.V(2).Infof("AttachVolume request returned %v", attachResponse) - } - - err = disk.waitForAttachmentStatus("attached") - if err != nil { - return "", err - } - - attached = true - - return hostDevice, nil -} - -// Implements Volumes.DetachDisk -func (aws *AWSCloud) DetachDisk(diskName string, instanceName string) (string, error) { - disk, err := newAWSDisk(aws, diskName) - if err != nil { - return "", err - } - - awsInstance, err := aws.getAwsInstance(instanceName) - if err != nil { - return "", err - } - - mountDevice, alreadyAttached, err := awsInstance.getMountDevice(disk.awsID, false) - if err != nil { - return "", err - } - - if !alreadyAttached { - glog.Warning("DetachDisk called on non-attached disk: ", diskName) - // TODO: Continue? Tolerate non-attached error in DetachVolume? - } - - request := ec2.DetachVolumeInput{ - InstanceId: &awsInstance.awsID, - VolumeId: &disk.awsID, - } - - response, err := aws.ec2.DetachVolume(&request) - if err != nil { - return "", fmt.Errorf("error detaching EBS volume: %v", err) - } - if response == nil { - return "", errors.New("no response from DetachVolume") - } - - // TODO: Fix this - just remove the cache? - // If we don't have a cache; we don't have to wait any more (the driver does it for us) - // Also, maybe we could get the locally connected drivers from the AWS metadata service? - - // At this point we are waiting for the volume being detached. This - // releases the volume and invalidates the cache even when there is a timeout. - // - // TODO: A timeout leaves the cache in an inconsistent state. The volume is still - // detaching though the cache shows it as ready to be attached again. Subsequent - // attach operations will fail. The attach is being retried and eventually - // works though. An option would be to completely flush the cache upon timeouts. - // - defer func() { - // TODO: Not thread safe? - for mountDevice, existingVolumeID := range awsInstance.deviceMappings { - if existingVolumeID == disk.awsID { - awsInstance.releaseMountDevice(disk.awsID, mountDevice) - return - } - } - }() - - err = disk.waitForAttachmentStatus("detached") - if err != nil { - return "", err - } - - hostDevicePath := "/dev/xvd" + string(mountDevice) - return hostDevicePath, err -} - -// Implements Volumes.CreateVolume -func (s *AWSCloud) CreateDisk(volumeOptions *VolumeOptions) (string, error) { - // TODO: Should we tag this with the cluster id (so it gets deleted when the cluster does?) - - request := &ec2.CreateVolumeInput{} - request.AvailabilityZone = &s.availabilityZone - volSize := int64(volumeOptions.CapacityGB) - request.Size = &volSize - request.VolumeType = aws.String(DefaultVolumeType) - response, err := s.ec2.CreateVolume(request) - if err != nil { - return "", err - } - - az := orEmpty(response.AvailabilityZone) - awsID := orEmpty(response.VolumeId) - - volumeName := "aws://" + az + "/" + awsID - - // apply tags - if volumeOptions.Tags != nil { - tags := []*ec2.Tag{} - for k, v := range *volumeOptions.Tags { - tag := &ec2.Tag{} - tag.Key = aws.String(k) - tag.Value = aws.String(v) - tags = append(tags, tag) - } - tagRequest := &ec2.CreateTagsInput{} - tagRequest.Resources = []*string{&awsID} - tagRequest.Tags = tags - if _, err := s.createTags(tagRequest); err != nil { - // delete the volume and hope it succeeds - _, delerr := s.DeleteDisk(volumeName) - if delerr != nil { - // delete did not succeed, we have a stray volume! - return "", fmt.Errorf("error tagging volume %s, could not delete the volume: %v", volumeName, delerr) - } - return "", fmt.Errorf("error tagging volume %s: %v", volumeName, err) - } - } - return volumeName, nil -} - -// Implements Volumes.DeleteDisk -func (aws *AWSCloud) DeleteDisk(volumeName string) (bool, error) { - awsDisk, err := newAWSDisk(aws, volumeName) - if err != nil { - return false, err - } - return awsDisk.deleteVolume() -} - -// Implements Volumes.GetVolumeLabels -func (c *AWSCloud) GetVolumeLabels(volumeName string) (map[string]string, error) { - awsDisk, err := newAWSDisk(c, volumeName) - if err != nil { - return nil, err - } - info, err := awsDisk.getInfo() - if err != nil { - return nil, err - } - labels := make(map[string]string) - az := aws.StringValue(info.AvailabilityZone) - if az == "" { - return nil, fmt.Errorf("volume did not have AZ information: %q", info.VolumeId) - } - - labels[unversioned.LabelZoneFailureDomain] = az - region, err := azToRegion(az) - if err != nil { - return nil, err - } - labels[unversioned.LabelZoneRegion] = region - - return labels, nil -} - -// Gets the current load balancer state -func (s *AWSCloud) describeLoadBalancer(name string) (*elb.LoadBalancerDescription, error) { - request := &elb.DescribeLoadBalancersInput{} - request.LoadBalancerNames = []*string{&name} - - response, err := s.elb.DescribeLoadBalancers(request) - if err != nil { - if awsError, ok := err.(awserr.Error); ok { - if awsError.Code() == "LoadBalancerNotFound" { - return nil, nil - } - } - return nil, err - } - - var ret *elb.LoadBalancerDescription - for _, loadBalancer := range response.LoadBalancerDescriptions { - if ret != nil { - glog.Errorf("Found multiple load balancers with name: %s", name) - } - ret = loadBalancer - } - return ret, nil -} - -// Retrieves instance's vpc id from metadata -func (self *AWSCloud) findVPCID() (string, error) { - macs, err := self.metadata.GetMetadata("network/interfaces/macs/") - if err != nil { - return "", fmt.Errorf("Could not list interfaces of the instance", err) - } - - // loop over interfaces, first vpc id returned wins - for _, macPath := range strings.Split(macs, "\n") { - if len(macPath) == 0 { - continue - } - url := fmt.Sprintf("network/interfaces/macs/%svpc-id", macPath) - vpcID, err := self.metadata.GetMetadata(url) - if err != nil { - continue - } - return vpcID, nil - } - return "", fmt.Errorf("Could not find VPC ID in instance metadata") -} - -// Retrieves the specified security group from the AWS API, or returns nil if not found -func (s *AWSCloud) findSecurityGroup(securityGroupId string) (*ec2.SecurityGroup, error) { - describeSecurityGroupsRequest := &ec2.DescribeSecurityGroupsInput{ - GroupIds: []*string{&securityGroupId}, - } - - groups, err := s.ec2.DescribeSecurityGroups(describeSecurityGroupsRequest) - if err != nil { - glog.Warning("Error retrieving security group", err) - return nil, err - } - - if len(groups) == 0 { - return nil, nil - } - if len(groups) != 1 { - // This should not be possible - ids should be unique - return nil, fmt.Errorf("multiple security groups found with same id") - } - group := groups[0] - return group, nil -} - -func isEqualIntPointer(l, r *int64) bool { - if l == nil { - return r == nil - } - if r == nil { - return l == nil - } - return *l == *r -} - -func isEqualStringPointer(l, r *string) bool { - if l == nil { - return r == nil - } - if r == nil { - return l == nil - } - return *l == *r -} - -func ipPermissionExists(newPermission, existing *ec2.IpPermission, compareGroupUserIDs bool) bool { - if !isEqualIntPointer(newPermission.FromPort, existing.FromPort) { - return false - } - if !isEqualIntPointer(newPermission.ToPort, existing.ToPort) { - return false - } - if !isEqualStringPointer(newPermission.IpProtocol, existing.IpProtocol) { - return false - } - // Check only if newPermission is a subset of existing. Usually it has zero or one elements. - // Not doing actual CIDR math yet; not clear it's needed, either. - glog.V(4).Infof("Comparing %v to %v", newPermission, existing) - if len(newPermission.IpRanges) > len(existing.IpRanges) { - return false - } - - for j := range newPermission.IpRanges { - found := false - for k := range existing.IpRanges { - if isEqualStringPointer(newPermission.IpRanges[j].CidrIp, existing.IpRanges[k].CidrIp) { - found = true - break - } - } - if found == false { - return false - } - } - for _, leftPair := range newPermission.UserIdGroupPairs { - for _, rightPair := range existing.UserIdGroupPairs { - if isEqualUserGroupPair(leftPair, rightPair, compareGroupUserIDs) { - return true - } - } - return false - } - - return true -} - -func isEqualUserGroupPair(l, r *ec2.UserIdGroupPair, compareGroupUserIDs bool) bool { - glog.V(2).Infof("Comparing %v to %v", *l.GroupId, *r.GroupId) - if isEqualStringPointer(l.GroupId, r.GroupId) { - if compareGroupUserIDs { - if isEqualStringPointer(l.UserId, r.UserId) { - return true - } - } else { - return true - } - } - - return false -} - -// Makes sure the security group includes the specified permissions -// Returns true if and only if changes were made -// The security group must already exist -func (s *AWSCloud) ensureSecurityGroupIngress(securityGroupId string, addPermissions []*ec2.IpPermission) (bool, error) { - group, err := s.findSecurityGroup(securityGroupId) - if err != nil { - glog.Warning("Error retrieving security group", err) - return false, err - } - - if group == nil { - return false, fmt.Errorf("security group not found: %s", securityGroupId) - } - - glog.V(2).Infof("Existing security group ingress: %s %v", securityGroupId, group.IpPermissions) - - changes := []*ec2.IpPermission{} - for _, addPermission := range addPermissions { - hasUserID := false - for i := range addPermission.UserIdGroupPairs { - if addPermission.UserIdGroupPairs[i].UserId != nil { - hasUserID = true - } - } - - found := false - for _, groupPermission := range group.IpPermissions { - if ipPermissionExists(addPermission, groupPermission, hasUserID) { - found = true - break - } - } - - if !found { - changes = append(changes, addPermission) - } - } - - if len(changes) == 0 { - return false, nil - } - - glog.V(2).Infof("Adding security group ingress: %s %v", securityGroupId, changes) - - request := &ec2.AuthorizeSecurityGroupIngressInput{} - request.GroupId = &securityGroupId - request.IpPermissions = changes - _, err = s.ec2.AuthorizeSecurityGroupIngress(request) - if err != nil { - glog.Warning("Error authorizing security group ingress", err) - return false, err - } - - return true, nil -} - -// Makes sure the security group no longer includes the specified permissions -// Returns true if and only if changes were made -// If the security group no longer exists, will return (false, nil) -func (s *AWSCloud) removeSecurityGroupIngress(securityGroupId string, removePermissions []*ec2.IpPermission) (bool, error) { - group, err := s.findSecurityGroup(securityGroupId) - if err != nil { - glog.Warning("Error retrieving security group", err) - return false, err - } - - if group == nil { - glog.Warning("Security group not found: ", securityGroupId) - return false, nil - } - - changes := []*ec2.IpPermission{} - for _, removePermission := range removePermissions { - hasUserID := false - for i := range removePermission.UserIdGroupPairs { - if removePermission.UserIdGroupPairs[i].UserId != nil { - hasUserID = true - } - } - - var found *ec2.IpPermission - for _, groupPermission := range group.IpPermissions { - if ipPermissionExists(removePermission, groupPermission, hasUserID) { - found = removePermission - break - } - } - - if found != nil { - changes = append(changes, found) - } - } - - if len(changes) == 0 { - return false, nil - } - - glog.V(2).Infof("Removing security group ingress: %s %v", securityGroupId, changes) - - request := &ec2.RevokeSecurityGroupIngressInput{} - request.GroupId = &securityGroupId - request.IpPermissions = changes - _, err = s.ec2.RevokeSecurityGroupIngress(request) - if err != nil { - glog.Warning("Error revoking security group ingress", err) - return false, err - } - - return true, nil -} - -// Makes sure the security group exists -// Returns the security group id or error -func (s *AWSCloud) ensureSecurityGroup(name string, description string, vpcID string) (string, error) { - groupID := "" - attempt := 0 - for { - attempt++ - - request := &ec2.DescribeSecurityGroupsInput{} - filters := []*ec2.Filter{ - newEc2Filter("group-name", name), - newEc2Filter("vpc-id", vpcID), - } - request.Filters = s.addFilters(filters) - - securityGroups, err := s.ec2.DescribeSecurityGroups(request) - if err != nil { - return "", err - } - - if len(securityGroups) >= 1 { - if len(securityGroups) > 1 { - glog.Warning("Found multiple security groups with name:", name) - } - return orEmpty(securityGroups[0].GroupId), nil - } - - createRequest := &ec2.CreateSecurityGroupInput{} - createRequest.VpcId = &vpcID - createRequest.GroupName = &name - createRequest.Description = &description - - createResponse, err := s.ec2.CreateSecurityGroup(createRequest) - if err != nil { - ignore := false - switch err := err.(type) { - case awserr.Error: - if err.Code() == "InvalidGroup.Duplicate" && attempt < MaxReadThenCreateRetries { - glog.V(2).Infof("Got InvalidGroup.Duplicate while creating security group (race?); will retry") - ignore = true - } - } - if !ignore { - glog.Error("Error creating security group: ", err) - return "", err - } - time.Sleep(1 * time.Second) - } else { - groupID = orEmpty(createResponse.GroupId) - break - } - } - if groupID == "" { - return "", fmt.Errorf("created security group, but id was not returned: %s", name) - } - - tags := []*ec2.Tag{} - for k, v := range s.filterTags { - tag := &ec2.Tag{} - tag.Key = aws.String(k) - tag.Value = aws.String(v) - tags = append(tags, tag) - } - - if len(tags) > 0 { - tagRequest := &ec2.CreateTagsInput{} - tagRequest.Resources = []*string{&groupID} - tagRequest.Tags = tags - if _, err := s.createTags(tagRequest); err != nil { - // Not clear how to recover fully from this; we're OK because we don't match on tags, but that is a little odd - return "", fmt.Errorf("error tagging security group: %v", err) - } - } - return groupID, nil -} - -// createTags calls EC2 CreateTags, but adds retry-on-failure logic -// We retry mainly because if we create an object, we cannot tag it until it is "fully created" (eventual consistency) -// The error code varies though (depending on what we are tagging), so we simply retry on all errors -func (s *AWSCloud) createTags(request *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) { - // TODO: We really should do exponential backoff here - attempt := 0 - maxAttempts := 60 - - for { - response, err := s.ec2.CreateTags(request) - if err == nil { - return response, err - } - - // We could check that the error is retryable, but the error code changes based on what we are tagging - // SecurityGroup: InvalidGroup.NotFound - attempt++ - if attempt > maxAttempts { - glog.Warningf("Failed to create tags (too many attempts): %v", err) - return response, err - } - glog.V(2).Infof("Failed to create tags; will retry. Error was %v", err) - time.Sleep(1 * time.Second) - } -} - -func (s *AWSCloud) listSubnetIDsinVPC(vpcId string) ([]string, error) { - - subnetIds := []string{} - - request := &ec2.DescribeSubnetsInput{} - filters := []*ec2.Filter{} - filters = append(filters, newEc2Filter("vpc-id", vpcId)) - // Note, this will only return subnets tagged with the cluster identifier for this Kubernetes cluster. - // In the case where an AZ has public & private subnets per AWS best practices, the deployment should ensure - // only the public subnet (where the ELB will go) is so tagged. - filters = s.addFilters(filters) - request.Filters = filters - - subnets, err := s.ec2.DescribeSubnets(request) - if err != nil { - glog.Error("Error describing subnets: ", err) - return nil, err - } - - availabilityZones := sets.NewString() - for _, subnet := range subnets { - az := orEmpty(subnet.AvailabilityZone) - id := orEmpty(subnet.SubnetId) - if availabilityZones.Has(az) { - glog.Warning("Found multiple subnets per AZ '", az, "', ignoring subnet '", id, "'") - continue - } - subnetIds = append(subnetIds, id) - availabilityZones.Insert(az) - } - - return subnetIds, nil -} - -// EnsureLoadBalancer implements LoadBalancer.EnsureLoadBalancer -// TODO(justinsb) It is weird that these take a region. I suspect it won't work cross-region anyway. -func (s *AWSCloud) EnsureLoadBalancer(name, region string, publicIP net.IP, ports []*api.ServicePort, hosts []string, serviceName types.NamespacedName, affinity api.ServiceAffinity) (*api.LoadBalancerStatus, error) { - glog.V(2).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", name, region, publicIP, ports, hosts, serviceName) - - if region != s.region { - return nil, fmt.Errorf("requested load balancer region '%s' does not match cluster region '%s'", region, s.region) - } - - if affinity != api.ServiceAffinityNone { - // ELB supports sticky sessions, but only when configured for HTTP/HTTPS - return nil, fmt.Errorf("unsupported load balancer affinity: %v", affinity) - } - - if len(ports) == 0 { - return nil, fmt.Errorf("requested load balancer with no ports") - } - - for _, port := range ports { - if port.Protocol != api.ProtocolTCP { - return nil, fmt.Errorf("Only TCP LoadBalancer is supported for AWS ELB") - } - } - - if publicIP != nil { - return nil, fmt.Errorf("publicIP cannot be specified for AWS ELB") - } - - instances, err := s.getInstancesByNodeNames(hosts) - if err != nil { - return nil, err - } - - vpcId, err := s.findVPCID() - if err != nil { - glog.Error("Error finding VPC", err) - return nil, err - } - - // Construct list of configured subnets - subnetIDs, err := s.listSubnetIDsinVPC(vpcId) - if err != nil { - glog.Error("Error listing subnets in VPC", err) - return nil, err - } - - // Create a security group for the load balancer - var securityGroupID string - { - sgName := "k8s-elb-" + name - sgDescription := fmt.Sprintf("Security group for Kubernetes ELB %s (%v)", name, serviceName) - securityGroupID, err = s.ensureSecurityGroup(sgName, sgDescription, vpcId) - if err != nil { - glog.Error("Error creating load balancer security group: ", err) - return nil, err - } - - permissions := []*ec2.IpPermission{} - for _, port := range ports { - portInt64 := int64(port.Port) - protocol := strings.ToLower(string(port.Protocol)) - sourceIp := "0.0.0.0/0" - - permission := &ec2.IpPermission{} - permission.FromPort = &portInt64 - permission.ToPort = &portInt64 - permission.IpRanges = []*ec2.IpRange{{CidrIp: &sourceIp}} - permission.IpProtocol = &protocol - - permissions = append(permissions, permission) - } - _, err = s.ensureSecurityGroupIngress(securityGroupID, permissions) - if err != nil { - return nil, err - } - } - securityGroupIDs := []string{securityGroupID} - - // Figure out what mappings we want on the load balancer - listeners := []*elb.Listener{} - for _, port := range ports { - if port.NodePort == 0 { - glog.Errorf("Ignoring port without NodePort defined: %v", port) - continue - } - instancePort := int64(port.NodePort) - loadBalancerPort := int64(port.Port) - protocol := strings.ToLower(string(port.Protocol)) - - listener := &elb.Listener{} - listener.InstancePort = &instancePort - listener.LoadBalancerPort = &loadBalancerPort - listener.Protocol = &protocol - listener.InstanceProtocol = &protocol - - listeners = append(listeners, listener) - } - - // Build the load balancer itself - loadBalancer, err := s.ensureLoadBalancer(serviceName, name, listeners, subnetIDs, securityGroupIDs) - if err != nil { - return nil, err - } - - err = s.ensureLoadBalancerHealthCheck(loadBalancer, listeners) - if err != nil { - return nil, err - } - - err = s.updateInstanceSecurityGroupsForLoadBalancer(loadBalancer, instances) - if err != nil { - glog.Warning("Error opening ingress rules for the load balancer to the instances: ", err) - return nil, err - } - - err = s.ensureLoadBalancerInstances(orEmpty(loadBalancer.LoadBalancerName), loadBalancer.Instances, instances) - if err != nil { - glog.Warningf("Error registering instances with the load balancer: %v", err) - return nil, err - } - - glog.V(1).Infof("Loadbalancer %s (%v) has DNS name %s", name, serviceName, orEmpty(loadBalancer.DNSName)) - - // TODO: Wait for creation? - - status := toStatus(loadBalancer) - return status, nil -} - -// GetLoadBalancer is an implementation of LoadBalancer.GetLoadBalancer -func (s *AWSCloud) GetLoadBalancer(name, region string) (*api.LoadBalancerStatus, bool, error) { - if region != s.region { - return nil, false, fmt.Errorf("requested load balancer region '%s' does not match cluster region '%s'", region, s.region) - } - - lb, err := s.describeLoadBalancer(name) - if err != nil { - return nil, false, err - } - - if lb == nil { - return nil, false, nil - } - - status := toStatus(lb) - return status, true, nil -} - -func toStatus(lb *elb.LoadBalancerDescription) *api.LoadBalancerStatus { - status := &api.LoadBalancerStatus{} - - if !isNilOrEmpty(lb.DNSName) { - var ingress api.LoadBalancerIngress - ingress.Hostname = orEmpty(lb.DNSName) - status.Ingress = []api.LoadBalancerIngress{ingress} - } - - return status -} - -// Returns the first security group for an instance, or nil -// We only create instances with one security group, so we warn if there are multiple or none -func findSecurityGroupForInstance(instance *ec2.Instance) *string { - var securityGroupId *string - for _, securityGroup := range instance.SecurityGroups { - if securityGroup == nil || securityGroup.GroupId == nil { - // Not expected, but avoid panic - glog.Warning("Unexpected empty security group for instance: ", orEmpty(instance.InstanceId)) - continue - } - - if securityGroupId != nil { - // We create instances with one SG - glog.Warningf("Multiple security groups found for instance (%s); will use first group (%s)", orEmpty(instance.InstanceId), *securityGroupId) - continue - } else { - securityGroupId = securityGroup.GroupId - } - } - - if securityGroupId == nil { - glog.Warning("No security group found for instance ", orEmpty(instance.InstanceId)) - } - - return securityGroupId -} - -// Open security group ingress rules on the instances so that the load balancer can talk to them -// Will also remove any security groups ingress rules for the load balancer that are _not_ needed for allInstances -func (s *AWSCloud) updateInstanceSecurityGroupsForLoadBalancer(lb *elb.LoadBalancerDescription, allInstances []*ec2.Instance) error { - // Determine the load balancer security group id - loadBalancerSecurityGroupId := "" - for _, securityGroup := range lb.SecurityGroups { - if isNilOrEmpty(securityGroup) { - continue - } - if loadBalancerSecurityGroupId != "" { - // We create LBs with one SG - glog.Warning("Multiple security groups for load balancer: ", orEmpty(lb.LoadBalancerName)) - } - loadBalancerSecurityGroupId = *securityGroup - } - if loadBalancerSecurityGroupId == "" { - return fmt.Errorf("Could not determine security group for load balancer: %s", orEmpty(lb.LoadBalancerName)) - } - - // Get the actual list of groups that allow ingress from the load-balancer - describeRequest := &ec2.DescribeSecurityGroupsInput{} - filters := []*ec2.Filter{} - filters = append(filters, newEc2Filter("ip-permission.group-id", loadBalancerSecurityGroupId)) - describeRequest.Filters = s.addFilters(filters) - actualGroups, err := s.ec2.DescribeSecurityGroups(describeRequest) - if err != nil { - return fmt.Errorf("error querying security groups: %v", err) - } - - // Open the firewall from the load balancer to the instance - // We don't actually have a trivial way to know in advance which security group the instance is in - // (it is probably the minion security group, but we don't easily have that). - // However, we _do_ have the list of security groups on the instance records. - - // Map containing the changes we want to make; true to add, false to remove - instanceSecurityGroupIds := map[string]bool{} - - // Scan instances for groups we want open - for _, instance := range allInstances { - securityGroupId := findSecurityGroupForInstance(instance) - if isNilOrEmpty(securityGroupId) { - glog.Warning("Ignoring instance without security group: ", orEmpty(instance.InstanceId)) - continue - } - - instanceSecurityGroupIds[*securityGroupId] = true - } - - // Compare to actual groups - for _, actualGroup := range actualGroups { - if isNilOrEmpty(actualGroup.GroupId) { - glog.Warning("Ignoring group without ID: ", actualGroup) - continue - } - - actualGroupID := *actualGroup.GroupId - - adding, found := instanceSecurityGroupIds[actualGroupID] - if found && adding { - // We don't need to make a change; the permission is already in place - delete(instanceSecurityGroupIds, actualGroupID) - } else { - // This group is not needed by allInstances; delete it - instanceSecurityGroupIds[actualGroupID] = false - } - } - - for instanceSecurityGroupId, add := range instanceSecurityGroupIds { - if add { - glog.V(2).Infof("Adding rule for traffic from the load balancer (%s) to instances (%s)", loadBalancerSecurityGroupId, instanceSecurityGroupId) - } else { - glog.V(2).Infof("Removing rule for traffic from the load balancer (%s) to instance (%s)", loadBalancerSecurityGroupId, instanceSecurityGroupId) - } - sourceGroupId := &ec2.UserIdGroupPair{} - sourceGroupId.GroupId = &loadBalancerSecurityGroupId - - allProtocols := "-1" - - permission := &ec2.IpPermission{} - permission.IpProtocol = &allProtocols - permission.UserIdGroupPairs = []*ec2.UserIdGroupPair{sourceGroupId} - - permissions := []*ec2.IpPermission{permission} - - if add { - changed, err := s.ensureSecurityGroupIngress(instanceSecurityGroupId, permissions) - if err != nil { - return err - } - if !changed { - glog.Warning("Allowing ingress was not needed; concurrent change? groupId=", instanceSecurityGroupId) - } - } else { - changed, err := s.removeSecurityGroupIngress(instanceSecurityGroupId, permissions) - if err != nil { - return err - } - if !changed { - glog.Warning("Revoking ingress was not needed; concurrent change? groupId=", instanceSecurityGroupId) - } - } - } - - return nil -} - -// EnsureLoadBalancerDeleted implements LoadBalancer.EnsureLoadBalancerDeleted. -func (s *AWSCloud) EnsureLoadBalancerDeleted(name, region string) error { - if region != s.region { - return fmt.Errorf("requested load balancer region '%s' does not match cluster region '%s'", region, s.region) - } - - lb, err := s.describeLoadBalancer(name) - if err != nil { - return err - } - - if lb == nil { - glog.Info("Load balancer already deleted: ", name) - return nil - } - - { - // De-authorize the load balancer security group from the instances security group - err = s.updateInstanceSecurityGroupsForLoadBalancer(lb, nil) - if err != nil { - glog.Error("Error deregistering load balancer from instance security groups: ", err) - return err - } - } - - { - // Delete the load balancer itself - request := &elb.DeleteLoadBalancerInput{} - request.LoadBalancerName = lb.LoadBalancerName - - _, err = s.elb.DeleteLoadBalancer(request) - if err != nil { - // TODO: Check if error was because load balancer was concurrently deleted - glog.Error("Error deleting load balancer: ", err) - return err - } - } - - { - // Delete the security group(s) for the load balancer - // Note that this is annoying: the load balancer disappears from the API immediately, but it is still - // deleting in the background. We get a DependencyViolation until the load balancer has deleted itself - - // Collect the security groups to delete - securityGroupIDs := map[string]struct{}{} - for _, securityGroupID := range lb.SecurityGroups { - if isNilOrEmpty(securityGroupID) { - glog.Warning("Ignoring empty security group in ", name) - continue - } - securityGroupIDs[*securityGroupID] = struct{}{} - } - - // Loop through and try to delete them - timeoutAt := time.Now().Add(time.Second * 300) - for { - for securityGroupID := range securityGroupIDs { - request := &ec2.DeleteSecurityGroupInput{} - request.GroupId = &securityGroupID - _, err := s.ec2.DeleteSecurityGroup(request) - if err == nil { - delete(securityGroupIDs, securityGroupID) - } else { - ignore := false - if awsError, ok := err.(awserr.Error); ok { - if awsError.Code() == "DependencyViolation" { - glog.V(2).Infof("Ignoring DependencyViolation while deleting load-balancer security group (%s), assuming because LB is in process of deleting", securityGroupID) - ignore = true - } - } - if !ignore { - return fmt.Errorf("error while deleting load balancer security group (%s): %v", securityGroupID, err) - } - } - } - - if len(securityGroupIDs) == 0 { - glog.V(2).Info("Deleted all security groups for load balancer: ", name) - break - } - - if time.Now().After(timeoutAt) { - return fmt.Errorf("timed out waiting for load-balancer deletion: %s", name) - } - - glog.V(2).Info("Waiting for load-balancer to delete so we can delete security groups: ", name) - - time.Sleep(5 * time.Second) - } - } - - return nil -} - -// UpdateLoadBalancer implements LoadBalancer.UpdateLoadBalancer -func (s *AWSCloud) UpdateLoadBalancer(name, region string, hosts []string) error { - if region != s.region { - return fmt.Errorf("requested load balancer region '%s' does not match cluster region '%s'", region, s.region) - } - - instances, err := s.getInstancesByNodeNames(hosts) - if err != nil { - return err - } - - lb, err := s.describeLoadBalancer(name) - if err != nil { - return err - } - - if lb == nil { - return fmt.Errorf("Load balancer not found") - } - - err = s.ensureLoadBalancerInstances(orEmpty(lb.LoadBalancerName), lb.Instances, instances) - if err != nil { - return nil - } - - err = s.updateInstanceSecurityGroupsForLoadBalancer(lb, instances) - if err != nil { - return err - } - - return nil -} - -// Returns the instance with the specified ID -func (a *AWSCloud) getInstanceByID(instanceID string) (*ec2.Instance, error) { - instances, err := a.getInstancesByIDs([]*string{&instanceID}) - if err != nil { - return nil, err - } - - if len(instances) == 0 { - return nil, fmt.Errorf("no instances found for instance: %s", instanceID) - } - if len(instances) > 1 { - return nil, fmt.Errorf("multiple instances found for instance: %s", instanceID) - } - - return instances[instanceID], nil -} - -func (a *AWSCloud) getInstancesByIDs(instanceIDs []*string) (map[string]*ec2.Instance, error) { - instancesByID := make(map[string]*ec2.Instance) - if len(instanceIDs) == 0 { - return instancesByID, nil - } - - request := &ec2.DescribeInstancesInput{ - InstanceIds: instanceIDs, - } - - instances, err := a.ec2.DescribeInstances(request) - if err != nil { - return nil, err - } - - for _, instance := range instances { - instanceID := orEmpty(instance.InstanceId) - if instanceID == "" { - continue - } - - instancesByID[instanceID] = instance - } - - return instancesByID, nil -} - -// Fetches instances by node names; returns an error if any cannot be found. -// This is currently implemented by fetching all the instances, because this is currently called for all nodes (i.e. the majority) -// In practice, the breakeven vs looping through and calling getInstanceByNodeName is probably around N=2. -func (a *AWSCloud) getInstancesByNodeNames(nodeNames []string) ([]*ec2.Instance, error) { - allInstances, err := a.getAllInstances() - if err != nil { - return nil, err - } - - nodeNamesMap := make(map[string]int, len(nodeNames)) - for i, nodeName := range nodeNames { - nodeNamesMap[nodeName] = i - } - - instances := make([]*ec2.Instance, len(nodeNames)) - for _, instance := range allInstances { - nodeName := aws.StringValue(instance.PrivateDnsName) - if nodeName == "" { - glog.V(2).Infof("ignoring ec2 instance with no PrivateDnsName: %q", aws.StringValue(instance.InstanceId)) - continue - } - i, found := nodeNamesMap[nodeName] - if !found { - continue - } - instances[i] = instance - } - - for i, instance := range instances { - if instance == nil { - nodeName := nodeNames[i] - return nil, fmt.Errorf("unable to find instance %q", nodeName) - } - } - - return instances, nil -} - -// Returns all instances that are tagged as being in this cluster. -func (a *AWSCloud) getAllInstances() ([]*ec2.Instance, error) { - filters := []*ec2.Filter{} - filters = a.addFilters(filters) - request := &ec2.DescribeInstancesInput{ - Filters: filters, - } - - return a.ec2.DescribeInstances(request) -} - -// Returns the instance with the specified node name -// Returns nil if it does not exist -func (a *AWSCloud) findInstanceByNodeName(nodeName string) (*ec2.Instance, error) { - filters := []*ec2.Filter{ - newEc2Filter("private-dns-name", nodeName), - } - filters = a.addFilters(filters) - request := &ec2.DescribeInstancesInput{ - Filters: filters, - } - - instances, err := a.ec2.DescribeInstances(request) - if err != nil { - return nil, err - } - if len(instances) == 0 { - return nil, nil - } - if len(instances) > 1 { - return nil, fmt.Errorf("multiple instances found for name: %s", nodeName) - } - return instances[0], nil -} - -// Returns the instance with the specified node name -// Like findInstanceByNodeName, but returns error if node not found -func (a *AWSCloud) getInstanceByNodeName(nodeName string) (*ec2.Instance, error) { - instance, err := a.findInstanceByNodeName(nodeName) - if err == nil && instance == nil { - return nil, fmt.Errorf("no instances found for name: %s", nodeName) - } - return instance, err -} - -// Add additional filters, to match on our tags -// This lets us run multiple k8s clusters in a single EC2 AZ -func (s *AWSCloud) addFilters(filters []*ec2.Filter) []*ec2.Filter { - for k, v := range s.filterTags { - filters = append(filters, newEc2Filter("tag:"+k, v)) - } - return filters -} - -// Returns the cluster name or an empty string -func (s *AWSCloud) getClusterName() string { - return s.filterTags[TagNameKubernetesCluster] -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_instancegroups.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_instancegroups.go deleted file mode 100644 index d870b04db..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_instancegroups.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/golang/glog" -) - -// AWSCloud implements InstanceGroups -var _ InstanceGroups = &AWSCloud{} - -// Implement InstanceGroups.ResizeInstanceGroup -// Set the size to the fixed size -func (a *AWSCloud) ResizeInstanceGroup(instanceGroupName string, size int) error { - request := &autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String(instanceGroupName), - MinSize: aws.Int64(int64(size)), - MaxSize: aws.Int64(int64(size)), - } - if _, err := a.asg.UpdateAutoScalingGroup(request); err != nil { - return fmt.Errorf("error resizing AWS autoscaling group: %v", err) - } - return nil -} - -// Implement InstanceGroups.DescribeInstanceGroup -// Queries the cloud provider for information about the specified instance group -func (a *AWSCloud) DescribeInstanceGroup(instanceGroupName string) (InstanceGroupInfo, error) { - request := &autoscaling.DescribeAutoScalingGroupsInput{ - AutoScalingGroupNames: []*string{aws.String(instanceGroupName)}, - } - response, err := a.asg.DescribeAutoScalingGroups(request) - if err != nil { - return nil, fmt.Errorf("error listing AWS autoscaling group (%s): %v", instanceGroupName, err) - } - - if len(response.AutoScalingGroups) == 0 { - return nil, nil - } - if len(response.AutoScalingGroups) > 1 { - glog.Warning("AWS returned multiple autoscaling groups with name ", instanceGroupName) - } - group := response.AutoScalingGroups[0] - return &awsInstanceGroup{group: group}, nil -} - -// awsInstanceGroup implements InstanceGroupInfo -var _ InstanceGroupInfo = &awsInstanceGroup{} - -type awsInstanceGroup struct { - group *autoscaling.Group -} - -// Implement InstanceGroupInfo.CurrentSize -// The number of instances currently running under control of this group -func (g *awsInstanceGroup) CurrentSize() (int, error) { - return len(g.group.Instances), nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_loadbalancer.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_loadbalancer.go deleted file mode 100644 index 83b299df8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_loadbalancer.go +++ /dev/null @@ -1,304 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws - -import ( - "fmt" - "strconv" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/elb" - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/types" - "k8s.io/kubernetes/pkg/util/sets" -) - -func (s *AWSCloud) ensureLoadBalancer(namespacedName types.NamespacedName, name string, listeners []*elb.Listener, subnetIDs []string, securityGroupIDs []string) (*elb.LoadBalancerDescription, error) { - loadBalancer, err := s.describeLoadBalancer(name) - if err != nil { - return nil, err - } - - dirty := false - - if loadBalancer == nil { - createRequest := &elb.CreateLoadBalancerInput{} - createRequest.LoadBalancerName = aws.String(name) - - createRequest.Listeners = listeners - - // We are supposed to specify one subnet per AZ. - // TODO: What happens if we have more than one subnet per AZ? - createRequest.Subnets = stringPointerArray(subnetIDs) - - createRequest.SecurityGroups = stringPointerArray(securityGroupIDs) - - createRequest.Tags = []*elb.Tag{ - {Key: aws.String(TagNameKubernetesCluster), Value: aws.String(s.getClusterName())}, - {Key: aws.String(TagNameKubernetesService), Value: aws.String(namespacedName.String())}, - } - - glog.Infof("Creating load balancer for %v with name: ", namespacedName, name) - _, err := s.elb.CreateLoadBalancer(createRequest) - if err != nil { - return nil, err - } - dirty = true - } else { - { - // Sync subnets - expected := sets.NewString(subnetIDs...) - actual := stringSetFromPointers(loadBalancer.Subnets) - - additions := expected.Difference(actual) - removals := actual.Difference(expected) - - if removals.Len() != 0 { - request := &elb.DetachLoadBalancerFromSubnetsInput{} - request.LoadBalancerName = aws.String(name) - request.Subnets = stringSetToPointers(removals) - glog.V(2).Info("Detaching load balancer from removed subnets") - _, err := s.elb.DetachLoadBalancerFromSubnets(request) - if err != nil { - return nil, fmt.Errorf("error detaching AWS loadbalancer from subnets: %v", err) - } - dirty = true - } - - if additions.Len() != 0 { - request := &elb.AttachLoadBalancerToSubnetsInput{} - request.LoadBalancerName = aws.String(name) - request.Subnets = stringSetToPointers(additions) - glog.V(2).Info("Attaching load balancer to added subnets") - _, err := s.elb.AttachLoadBalancerToSubnets(request) - if err != nil { - return nil, fmt.Errorf("error attaching AWS loadbalancer to subnets: %v", err) - } - dirty = true - } - } - - { - // Sync security groups - expected := sets.NewString(securityGroupIDs...) - actual := stringSetFromPointers(loadBalancer.SecurityGroups) - - if !expected.Equal(actual) { - // This call just replaces the security groups, unlike e.g. subnets (!) - request := &elb.ApplySecurityGroupsToLoadBalancerInput{} - request.LoadBalancerName = aws.String(name) - request.SecurityGroups = stringPointerArray(securityGroupIDs) - glog.V(2).Info("Applying updated security groups to load balancer") - _, err := s.elb.ApplySecurityGroupsToLoadBalancer(request) - if err != nil { - return nil, fmt.Errorf("error applying AWS loadbalancer security groups: %v", err) - } - dirty = true - } - } - - { - // Sync listeners - listenerDescriptions := loadBalancer.ListenerDescriptions - - foundSet := make(map[int]bool) - removals := []*int64{} - for _, listenerDescription := range listenerDescriptions { - actual := listenerDescription.Listener - if actual == nil { - glog.Warning("Ignoring empty listener in AWS loadbalancer: ", name) - continue - } - - found := -1 - for i, expected := range listeners { - if orEmpty(actual.Protocol) != orEmpty(expected.Protocol) { - continue - } - if orEmpty(actual.InstanceProtocol) != orEmpty(expected.InstanceProtocol) { - continue - } - if orZero(actual.InstancePort) != orZero(expected.InstancePort) { - continue - } - if orZero(actual.LoadBalancerPort) != orZero(expected.LoadBalancerPort) { - continue - } - if orEmpty(actual.SSLCertificateId) != orEmpty(expected.SSLCertificateId) { - continue - } - found = i - } - if found != -1 { - foundSet[found] = true - } else { - removals = append(removals, actual.LoadBalancerPort) - } - } - - additions := []*elb.Listener{} - for i := range listeners { - if foundSet[i] { - continue - } - additions = append(additions, listeners[i]) - } - - if len(removals) != 0 { - request := &elb.DeleteLoadBalancerListenersInput{} - request.LoadBalancerName = aws.String(name) - request.LoadBalancerPorts = removals - glog.V(2).Info("Deleting removed load balancer listeners") - _, err := s.elb.DeleteLoadBalancerListeners(request) - if err != nil { - return nil, fmt.Errorf("error deleting AWS loadbalancer listeners: %v", err) - } - dirty = true - } - - if len(additions) != 0 { - request := &elb.CreateLoadBalancerListenersInput{} - request.LoadBalancerName = aws.String(name) - request.Listeners = additions - glog.V(2).Info("Creating added load balancer listeners") - _, err := s.elb.CreateLoadBalancerListeners(request) - if err != nil { - return nil, fmt.Errorf("error creating AWS loadbalancer listeners: %v", err) - } - dirty = true - } - } - } - - if dirty { - loadBalancer, err = s.describeLoadBalancer(name) - if err != nil { - glog.Warning("Unable to retrieve load balancer after creation/update") - return nil, err - } - } - - return loadBalancer, nil -} - -// Makes sure that the health check for an ELB matches the configured listeners -func (s *AWSCloud) ensureLoadBalancerHealthCheck(loadBalancer *elb.LoadBalancerDescription, listeners []*elb.Listener) error { - actual := loadBalancer.HealthCheck - - // Default AWS settings - expectedHealthyThreshold := int64(2) - expectedUnhealthyThreshold := int64(6) - expectedTimeout := int64(5) - expectedInterval := int64(10) - - // We only configure a TCP health-check on the first port - expectedTarget := "" - for _, listener := range listeners { - if listener.InstancePort == nil { - continue - } - expectedTarget = "TCP:" + strconv.FormatInt(*listener.InstancePort, 10) - break - } - - if expectedTarget == "" { - return fmt.Errorf("unable to determine health check port (no valid listeners)") - } - - if expectedTarget == orEmpty(actual.Target) && - expectedHealthyThreshold == orZero(actual.HealthyThreshold) && - expectedUnhealthyThreshold == orZero(actual.UnhealthyThreshold) && - expectedTimeout == orZero(actual.Timeout) && - expectedInterval == orZero(actual.Interval) { - return nil - } - - glog.V(2).Info("Updating load-balancer health-check") - - healthCheck := &elb.HealthCheck{} - healthCheck.HealthyThreshold = &expectedHealthyThreshold - healthCheck.UnhealthyThreshold = &expectedUnhealthyThreshold - healthCheck.Timeout = &expectedTimeout - healthCheck.Interval = &expectedInterval - healthCheck.Target = &expectedTarget - - request := &elb.ConfigureHealthCheckInput{} - request.HealthCheck = healthCheck - request.LoadBalancerName = loadBalancer.LoadBalancerName - - _, err := s.elb.ConfigureHealthCheck(request) - if err != nil { - return fmt.Errorf("error configuring load-balancer health-check: %v", err) - } - - return nil -} - -// Makes sure that exactly the specified hosts are registered as instances with the load balancer -func (s *AWSCloud) ensureLoadBalancerInstances(loadBalancerName string, lbInstances []*elb.Instance, instances []*ec2.Instance) error { - expected := sets.NewString() - for _, instance := range instances { - expected.Insert(orEmpty(instance.InstanceId)) - } - - actual := sets.NewString() - for _, lbInstance := range lbInstances { - actual.Insert(orEmpty(lbInstance.InstanceId)) - } - - additions := expected.Difference(actual) - removals := actual.Difference(expected) - - addInstances := []*elb.Instance{} - for _, instanceId := range additions.List() { - addInstance := &elb.Instance{} - addInstance.InstanceId = aws.String(instanceId) - addInstances = append(addInstances, addInstance) - } - - removeInstances := []*elb.Instance{} - for _, instanceId := range removals.List() { - removeInstance := &elb.Instance{} - removeInstance.InstanceId = aws.String(instanceId) - removeInstances = append(removeInstances, removeInstance) - } - - if len(addInstances) > 0 { - registerRequest := &elb.RegisterInstancesWithLoadBalancerInput{} - registerRequest.Instances = addInstances - registerRequest.LoadBalancerName = aws.String(loadBalancerName) - _, err := s.elb.RegisterInstancesWithLoadBalancer(registerRequest) - if err != nil { - return err - } - glog.V(1).Infof("Instances added to load-balancer %s", loadBalancerName) - } - - if len(removeInstances) > 0 { - deregisterRequest := &elb.DeregisterInstancesFromLoadBalancerInput{} - deregisterRequest.Instances = removeInstances - deregisterRequest.LoadBalancerName = aws.String(loadBalancerName) - _, err := s.elb.DeregisterInstancesFromLoadBalancer(deregisterRequest) - if err != nil { - return err - } - glog.V(1).Infof("Instances removed from load-balancer %s", loadBalancerName) - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_routes.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_routes.go deleted file mode 100644 index c1ffddc3a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_routes.go +++ /dev/null @@ -1,188 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/cloudprovider" -) - -func (s *AWSCloud) findRouteTable(clusterName string) (*ec2.RouteTable, error) { - // This should be unnecessary (we already filter on TagNameKubernetesCluster, - // and something is broken if cluster name doesn't match, but anyway... - // TODO: All clouds should be cluster-aware by default - filters := []*ec2.Filter{newEc2Filter("tag:"+TagNameKubernetesCluster, clusterName)} - request := &ec2.DescribeRouteTablesInput{Filters: s.addFilters(filters)} - - tables, err := s.ec2.DescribeRouteTables(request) - if err != nil { - return nil, err - } - - if len(tables) == 0 { - return nil, fmt.Errorf("unable to find route table for AWS cluster: %s", clusterName) - } - - if len(tables) != 1 { - return nil, fmt.Errorf("found multiple matching AWS route tables for AWS cluster: %s", clusterName) - } - return tables[0], nil -} - -// ListRoutes implements Routes.ListRoutes -// List all routes that match the filter -func (s *AWSCloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error) { - table, err := s.findRouteTable(clusterName) - if err != nil { - return nil, err - } - - var routes []*cloudprovider.Route - var instanceIDs []*string - - for _, r := range table.Routes { - instanceID := orEmpty(r.InstanceId) - - if instanceID == "" { - continue - } - - instanceIDs = append(instanceIDs, &instanceID) - } - - instances, err := s.getInstancesByIDs(instanceIDs) - if err != nil { - return nil, err - } - - for _, r := range table.Routes { - instanceID := orEmpty(r.InstanceId) - destinationCIDR := orEmpty(r.DestinationCidrBlock) - - if instanceID == "" || destinationCIDR == "" { - continue - } - - instance, found := instances[instanceID] - if !found { - glog.Warningf("unable to find instance ID %s in the list of instances being routed to", instanceID) - continue - } - instanceName := orEmpty(instance.PrivateDnsName) - routeName := clusterName + "-" + destinationCIDR - routes = append(routes, &cloudprovider.Route{Name: routeName, TargetInstance: instanceName, DestinationCIDR: destinationCIDR}) - } - - return routes, nil -} - -// Sets the instance attribute "source-dest-check" to the specified value -func (s *AWSCloud) configureInstanceSourceDestCheck(instanceID string, sourceDestCheck bool) error { - request := &ec2.ModifyInstanceAttributeInput{} - request.InstanceId = aws.String(instanceID) - request.SourceDestCheck = &ec2.AttributeBooleanValue{Value: aws.Bool(sourceDestCheck)} - - _, err := s.ec2.ModifyInstanceAttribute(request) - if err != nil { - return fmt.Errorf("error configuring source-dest-check on instance %s: %v", instanceID, err) - } - return nil -} - -// CreateRoute implements Routes.CreateRoute -// Create the described route -func (s *AWSCloud) CreateRoute(clusterName string, nameHint string, route *cloudprovider.Route) error { - instance, err := s.getInstanceByNodeName(route.TargetInstance) - if err != nil { - return err - } - - // In addition to configuring the route itself, we also need to configure the instance to accept that traffic - // On AWS, this requires turning source-dest checks off - err = s.configureInstanceSourceDestCheck(orEmpty(instance.InstanceId), false) - if err != nil { - return err - } - - table, err := s.findRouteTable(clusterName) - if err != nil { - return err - } - - var deleteRoute *ec2.Route - for _, r := range table.Routes { - destinationCIDR := aws.StringValue(r.DestinationCidrBlock) - - if destinationCIDR != route.DestinationCIDR { - continue - } - - if aws.StringValue(r.State) == ec2.RouteStateBlackhole { - deleteRoute = r - } - } - - if deleteRoute != nil { - glog.Infof("deleting blackholed route: %s", aws.StringValue(deleteRoute.DestinationCidrBlock)) - - request := &ec2.DeleteRouteInput{} - request.DestinationCidrBlock = deleteRoute.DestinationCidrBlock - request.RouteTableId = table.RouteTableId - - _, err = s.ec2.DeleteRoute(request) - if err != nil { - return fmt.Errorf("error deleting blackholed AWS route (%s): %v", deleteRoute.DestinationCidrBlock, err) - } - } - - request := &ec2.CreateRouteInput{} - // TODO: use ClientToken for idempotency? - request.DestinationCidrBlock = aws.String(route.DestinationCIDR) - request.InstanceId = instance.InstanceId - request.RouteTableId = table.RouteTableId - - _, err = s.ec2.CreateRoute(request) - if err != nil { - return fmt.Errorf("error creating AWS route (%s): %v", route.DestinationCIDR, err) - } - - return nil -} - -// DeleteRoute implements Routes.DeleteRoute -// Delete the specified route -func (s *AWSCloud) DeleteRoute(clusterName string, route *cloudprovider.Route) error { - table, err := s.findRouteTable(clusterName) - if err != nil { - return err - } - - request := &ec2.DeleteRouteInput{} - request.DestinationCidrBlock = aws.String(route.DestinationCIDR) - request.RouteTableId = table.RouteTableId - - _, err = s.ec2.DeleteRoute(request) - if err != nil { - return fmt.Errorf("error deleting AWS route (%s): %v", route.DestinationCIDR, err) - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_test.go deleted file mode 100644 index 3151c1246..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_test.go +++ /dev/null @@ -1,939 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws - -import ( - "fmt" - "io" - "reflect" - "strings" - "testing" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/elb" - - "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/types" -) - -const TestClusterId = "clusterid.test" - -func TestReadAWSCloudConfig(t *testing.T) { - tests := []struct { - name string - - reader io.Reader - aws AWSServices - - expectError bool - zone string - }{ - { - "No config reader", - nil, nil, - true, "", - }, - { - "Empty config, no metadata", - strings.NewReader(""), nil, - true, "", - }, - { - "No zone in config, no metadata", - strings.NewReader("[global]\n"), nil, - true, "", - }, - { - "Zone in config, no metadata", - strings.NewReader("[global]\nzone = eu-west-1a"), nil, - false, "eu-west-1a", - }, - { - "No zone in config, metadata does not have zone", - strings.NewReader("[global]\n"), NewFakeAWSServices().withAz(""), - true, "", - }, - { - "No zone in config, metadata has zone", - strings.NewReader("[global]\n"), NewFakeAWSServices(), - false, "us-east-1a", - }, - { - "Zone in config should take precedence over metadata", - strings.NewReader("[global]\nzone = eu-west-1a"), NewFakeAWSServices(), - false, "eu-west-1a", - }, - } - - for _, test := range tests { - t.Logf("Running test case %s", test.name) - var metadata EC2Metadata - if test.aws != nil { - metadata, _ = test.aws.Metadata() - } - cfg, err := readAWSCloudConfig(test.reader, metadata) - if test.expectError { - if err == nil { - t.Errorf("Should error for case %s (cfg=%v)", test.name, cfg) - } - } else { - if err != nil { - t.Errorf("Should succeed for case: %s", test.name) - } - if cfg.Global.Zone != test.zone { - t.Errorf("Incorrect zone value (%s vs %s) for case: %s", - cfg.Global.Zone, test.zone, test.name) - } - } - } -} - -type FakeAWSServices struct { - availabilityZone string - instances []*ec2.Instance - instanceId string - privateDnsName string - networkInterfacesMacs []string - networkInterfacesVpcIDs []string - internalIP string - externalIP string - - ec2 *FakeEC2 - elb *FakeELB - asg *FakeASG - metadata *FakeMetadata -} - -func NewFakeAWSServices() *FakeAWSServices { - s := &FakeAWSServices{} - s.availabilityZone = "us-east-1a" - s.ec2 = &FakeEC2{aws: s} - s.elb = &FakeELB{aws: s} - s.asg = &FakeASG{aws: s} - s.metadata = &FakeMetadata{aws: s} - - s.networkInterfacesMacs = []string{"aa:bb:cc:dd:ee:00", "aa:bb:cc:dd:ee:01"} - s.networkInterfacesVpcIDs = []string{"vpc-mac0", "vpc-mac1"} - - s.instanceId = "i-self" - s.privateDnsName = "ip-172-20-0-100.ec2.internal" - s.internalIP = "192.168.0.1" - s.externalIP = "1.2.3.4" - var selfInstance ec2.Instance - selfInstance.InstanceId = &s.instanceId - selfInstance.PrivateDnsName = &s.privateDnsName - s.instances = []*ec2.Instance{&selfInstance} - - var tag ec2.Tag - tag.Key = aws.String(TagNameKubernetesCluster) - tag.Value = aws.String(TestClusterId) - selfInstance.Tags = []*ec2.Tag{&tag} - - return s -} - -func (s *FakeAWSServices) withAz(az string) *FakeAWSServices { - s.availabilityZone = az - return s -} - -func (s *FakeAWSServices) withInstances(instances []*ec2.Instance) *FakeAWSServices { - s.instances = instances - return s -} - -func (s *FakeAWSServices) Compute(region string) (EC2, error) { - return s.ec2, nil -} - -func (s *FakeAWSServices) LoadBalancing(region string) (ELB, error) { - return s.elb, nil -} - -func (s *FakeAWSServices) Autoscaling(region string) (ASG, error) { - return s.asg, nil -} - -func (s *FakeAWSServices) Metadata() (EC2Metadata, error) { - return s.metadata, nil -} - -func TestFilterTags(t *testing.T) { - awsServices := NewFakeAWSServices() - c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) - if err != nil { - t.Errorf("Error building aws cloud: %v", err) - return - } - - if len(c.filterTags) != 1 { - t.Errorf("unexpected filter tags: %v", c.filterTags) - return - } - - if c.filterTags[TagNameKubernetesCluster] != TestClusterId { - t.Errorf("unexpected filter tags: %v", c.filterTags) - } -} - -func TestNewAWSCloud(t *testing.T) { - tests := []struct { - name string - - reader io.Reader - awsServices AWSServices - - expectError bool - zone string - }{ - { - "No config reader", - nil, NewFakeAWSServices().withAz(""), - true, "", - }, - { - "Config specified invalid zone", - strings.NewReader("[global]\nzone = blahonga"), NewFakeAWSServices(), - true, "", - }, - { - "Config specifies valid zone", - strings.NewReader("[global]\nzone = eu-west-1a"), NewFakeAWSServices(), - false, "eu-west-1a", - }, - { - "Gets zone from metadata when not in config", - - strings.NewReader("[global]\n"), - NewFakeAWSServices(), - false, "us-east-1a", - }, - { - "No zone in config or metadata", - strings.NewReader("[global]\n"), - NewFakeAWSServices().withAz(""), - true, "", - }, - } - - for _, test := range tests { - t.Logf("Running test case %s", test.name) - c, err := newAWSCloud(test.reader, test.awsServices) - if test.expectError { - if err == nil { - t.Errorf("Should error for case %s", test.name) - } - } else { - if err != nil { - t.Errorf("Should succeed for case: %s, got %v", test.name, err) - } else if c.availabilityZone != test.zone { - t.Errorf("Incorrect zone value (%s vs %s) for case: %s", - c.availabilityZone, test.zone, test.name) - } - } - } -} - -type FakeEC2 struct { - aws *FakeAWSServices - Subnets []*ec2.Subnet - DescribeSubnetsInput *ec2.DescribeSubnetsInput -} - -func contains(haystack []*string, needle string) bool { - for _, s := range haystack { - // (deliberately panic if s == nil) - if needle == *s { - return true - } - } - return false -} - -func instanceMatchesFilter(instance *ec2.Instance, filter *ec2.Filter) bool { - name := *filter.Name - if name == "private-dns-name" { - if instance.PrivateDnsName == nil { - return false - } - return contains(filter.Values, *instance.PrivateDnsName) - } - panic("Unknown filter name: " + name) -} - -func (self *FakeEC2) DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error) { - matches := []*ec2.Instance{} - for _, instance := range self.aws.instances { - if request.InstanceIds != nil { - if instance.InstanceId == nil { - glog.Warning("Instance with no instance id: ", instance) - continue - } - - found := false - for _, instanceId := range request.InstanceIds { - if *instanceId == *instance.InstanceId { - found = true - break - } - } - if !found { - continue - } - } - if request.Filters != nil { - allMatch := true - for _, filter := range request.Filters { - if !instanceMatchesFilter(instance, filter) { - allMatch = false - break - } - } - if !allMatch { - continue - } - } - matches = append(matches, instance) - } - - return matches, nil -} - -type FakeMetadata struct { - aws *FakeAWSServices -} - -func (self *FakeMetadata) GetMetadata(key string) (string, error) { - networkInterfacesPrefix := "network/interfaces/macs/" - if key == "placement/availability-zone" { - return self.aws.availabilityZone, nil - } else if key == "instance-id" { - return self.aws.instanceId, nil - } else if key == "local-hostname" { - return self.aws.privateDnsName, nil - } else if key == "local-ipv4" { - return self.aws.internalIP, nil - } else if key == "public-ipv4" { - return self.aws.externalIP, nil - } else if strings.HasPrefix(key, networkInterfacesPrefix) { - if key == networkInterfacesPrefix { - return strings.Join(self.aws.networkInterfacesMacs, "/\n") + "/\n", nil - } else { - keySplit := strings.Split(key, "/") - macParam := keySplit[3] - if len(keySplit) == 5 && keySplit[4] == "vpc-id" { - for i, macElem := range self.aws.networkInterfacesMacs { - if macParam == macElem { - return self.aws.networkInterfacesVpcIDs[i], nil - } - } - } - return "", nil - } - } else { - return "", nil - } -} - -func (ec2 *FakeEC2) AttachVolume(request *ec2.AttachVolumeInput) (resp *ec2.VolumeAttachment, err error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) DetachVolume(request *ec2.DetachVolumeInput) (resp *ec2.VolumeAttachment, err error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) DescribeVolumes(request *ec2.DescribeVolumesInput) ([]*ec2.Volume, error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) CreateVolume(request *ec2.CreateVolumeInput) (resp *ec2.Volume, err error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) DeleteVolume(request *ec2.DeleteVolumeInput) (resp *ec2.DeleteVolumeOutput, err error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) DescribeSecurityGroups(request *ec2.DescribeSecurityGroupsInput) ([]*ec2.SecurityGroup, error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) CreateSecurityGroup(*ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) DeleteSecurityGroup(*ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) AuthorizeSecurityGroupIngress(*ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) RevokeSecurityGroupIngress(*ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeEC2) DescribeSubnets(request *ec2.DescribeSubnetsInput) ([]*ec2.Subnet, error) { - ec2.DescribeSubnetsInput = request - return ec2.Subnets, nil -} - -func (ec2 *FakeEC2) CreateTags(*ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) { - panic("Not implemented") -} - -func (s *FakeEC2) DescribeRouteTables(request *ec2.DescribeRouteTablesInput) ([]*ec2.RouteTable, error) { - panic("Not implemented") -} - -func (s *FakeEC2) CreateRoute(request *ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error) { - panic("Not implemented") -} - -func (s *FakeEC2) DeleteRoute(request *ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error) { - panic("Not implemented") -} - -func (s *FakeEC2) ModifyInstanceAttribute(request *ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) { - panic("Not implemented") -} - -type FakeELB struct { - aws *FakeAWSServices -} - -func (ec2 *FakeELB) CreateLoadBalancer(*elb.CreateLoadBalancerInput) (*elb.CreateLoadBalancerOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) DeleteLoadBalancer(*elb.DeleteLoadBalancerInput) (*elb.DeleteLoadBalancerOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) DescribeLoadBalancers(*elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error) { - panic("Not implemented") -} -func (ec2 *FakeELB) RegisterInstancesWithLoadBalancer(*elb.RegisterInstancesWithLoadBalancerInput) (*elb.RegisterInstancesWithLoadBalancerOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) DeregisterInstancesFromLoadBalancer(*elb.DeregisterInstancesFromLoadBalancerInput) (*elb.DeregisterInstancesFromLoadBalancerOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) DetachLoadBalancerFromSubnets(*elb.DetachLoadBalancerFromSubnetsInput) (*elb.DetachLoadBalancerFromSubnetsOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) AttachLoadBalancerToSubnets(*elb.AttachLoadBalancerToSubnetsInput) (*elb.AttachLoadBalancerToSubnetsOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) CreateLoadBalancerListeners(*elb.CreateLoadBalancerListenersInput) (*elb.CreateLoadBalancerListenersOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) DeleteLoadBalancerListeners(*elb.DeleteLoadBalancerListenersInput) (*elb.DeleteLoadBalancerListenersOutput, error) { - panic("Not implemented") -} - -func (ec2 *FakeELB) ApplySecurityGroupsToLoadBalancer(*elb.ApplySecurityGroupsToLoadBalancerInput) (*elb.ApplySecurityGroupsToLoadBalancerOutput, error) { - panic("Not implemented") -} - -func (elb *FakeELB) ConfigureHealthCheck(*elb.ConfigureHealthCheckInput) (*elb.ConfigureHealthCheckOutput, error) { - panic("Not implemented") -} - -type FakeASG struct { - aws *FakeAWSServices -} - -func (a *FakeASG) UpdateAutoScalingGroup(*autoscaling.UpdateAutoScalingGroupInput) (*autoscaling.UpdateAutoScalingGroupOutput, error) { - panic("Not implemented") -} - -func (a *FakeASG) DescribeAutoScalingGroups(*autoscaling.DescribeAutoScalingGroupsInput) (*autoscaling.DescribeAutoScalingGroupsOutput, error) { - panic("Not implemented") -} - -func mockInstancesResp(instances []*ec2.Instance) (*AWSCloud, *FakeAWSServices) { - awsServices := NewFakeAWSServices().withInstances(instances) - return &AWSCloud{ - ec2: awsServices.ec2, - availabilityZone: awsServices.availabilityZone, - metadata: &FakeMetadata{aws: awsServices}, - }, awsServices -} - -func mockAvailabilityZone(region string, availabilityZone string) *AWSCloud { - awsServices := NewFakeAWSServices().withAz(availabilityZone) - return &AWSCloud{ - ec2: awsServices.ec2, - availabilityZone: awsServices.availabilityZone, - region: region, - } -} - -func TestList(t *testing.T) { - // TODO this setup is not very clean and could probably be improved - var instance0 ec2.Instance - var instance1 ec2.Instance - var instance2 ec2.Instance - var instance3 ec2.Instance - - //0 - tag0 := ec2.Tag{ - Key: aws.String("Name"), - Value: aws.String("foo"), - } - instance0.Tags = []*ec2.Tag{&tag0} - instance0.InstanceId = aws.String("instance0") - instance0.PrivateDnsName = aws.String("instance0.ec2.internal") - state0 := ec2.InstanceState{ - Name: aws.String("running"), - } - instance0.State = &state0 - - //1 - tag1 := ec2.Tag{ - Key: aws.String("Name"), - Value: aws.String("bar"), - } - instance1.Tags = []*ec2.Tag{&tag1} - instance1.InstanceId = aws.String("instance1") - instance1.PrivateDnsName = aws.String("instance1.ec2.internal") - state1 := ec2.InstanceState{ - Name: aws.String("running"), - } - instance1.State = &state1 - - //2 - tag2 := ec2.Tag{ - Key: aws.String("Name"), - Value: aws.String("baz"), - } - instance2.Tags = []*ec2.Tag{&tag2} - instance2.InstanceId = aws.String("instance2") - instance2.PrivateDnsName = aws.String("instance2.ec2.internal") - state2 := ec2.InstanceState{ - Name: aws.String("running"), - } - instance2.State = &state2 - - //3 - tag3 := ec2.Tag{ - Key: aws.String("Name"), - Value: aws.String("quux"), - } - instance3.Tags = []*ec2.Tag{&tag3} - instance3.InstanceId = aws.String("instance3") - instance3.PrivateDnsName = aws.String("instance3.ec2.internal") - state3 := ec2.InstanceState{ - Name: aws.String("running"), - } - instance3.State = &state3 - - instances := []*ec2.Instance{&instance0, &instance1, &instance2, &instance3} - aws, _ := mockInstancesResp(instances) - - table := []struct { - input string - expect []string - }{ - {"blahonga", []string{}}, - {"quux", []string{"instance3.ec2.internal"}}, - {"a", []string{"instance1.ec2.internal", "instance2.ec2.internal"}}, - } - - for _, item := range table { - result, err := aws.List(item.input) - if err != nil { - t.Errorf("Expected call with %v to succeed, failed with %s", item.input, err) - } - if e, a := item.expect, result; !reflect.DeepEqual(e, a) { - t.Errorf("Expected %v, got %v", e, a) - } - } -} - -func testHasNodeAddress(t *testing.T, addrs []api.NodeAddress, addressType api.NodeAddressType, address string) { - for _, addr := range addrs { - if addr.Type == addressType && addr.Address == address { - return - } - } - t.Errorf("Did not find expected address: %s:%s in %v", addressType, address, addrs) -} - -func TestNodeAddresses(t *testing.T) { - // Note these instances have the same name - // (we test that this produces an error) - var instance0 ec2.Instance - var instance1 ec2.Instance - var instance2 ec2.Instance - - //0 - instance0.InstanceId = aws.String("i-self") - instance0.PrivateDnsName = aws.String("instance-same.ec2.internal") - instance0.PrivateIpAddress = aws.String("192.168.0.1") - instance0.PublicIpAddress = aws.String("1.2.3.4") - instance0.InstanceType = aws.String("c3.large") - state0 := ec2.InstanceState{ - Name: aws.String("running"), - } - instance0.State = &state0 - - //1 - instance1.InstanceId = aws.String("i-self") - instance1.PrivateDnsName = aws.String("instance-same.ec2.internal") - instance1.PrivateIpAddress = aws.String("192.168.0.2") - instance1.InstanceType = aws.String("c3.large") - state1 := ec2.InstanceState{ - Name: aws.String("running"), - } - instance1.State = &state1 - - //2 - instance2.InstanceId = aws.String("i-self") - instance2.PrivateDnsName = aws.String("instance-other.ec2.internal") - instance2.PrivateIpAddress = aws.String("192.168.0.1") - instance2.PublicIpAddress = aws.String("1.2.3.4") - instance2.InstanceType = aws.String("c3.large") - state2 := ec2.InstanceState{ - Name: aws.String("running"), - } - instance2.State = &state2 - - instances := []*ec2.Instance{&instance0, &instance1, &instance2} - - aws1, _ := mockInstancesResp([]*ec2.Instance{}) - _, err1 := aws1.NodeAddresses("instance-mismatch.ec2.internal") - if err1 == nil { - t.Errorf("Should error when no instance found") - } - - aws2, _ := mockInstancesResp(instances) - _, err2 := aws2.NodeAddresses("instance-same.ec2.internal") - if err2 == nil { - t.Errorf("Should error when multiple instances found") - } - - aws3, _ := mockInstancesResp(instances[0:1]) - addrs3, err3 := aws3.NodeAddresses("instance-same.ec2.internal") - if err3 != nil { - t.Errorf("Should not error when instance found") - } - if len(addrs3) != 3 { - t.Errorf("Should return exactly 3 NodeAddresses") - } - testHasNodeAddress(t, addrs3, api.NodeInternalIP, "192.168.0.1") - testHasNodeAddress(t, addrs3, api.NodeLegacyHostIP, "192.168.0.1") - testHasNodeAddress(t, addrs3, api.NodeExternalIP, "1.2.3.4") - - aws4, fakeServices := mockInstancesResp([]*ec2.Instance{}) - fakeServices.externalIP = "2.3.4.5" - fakeServices.internalIP = "192.168.0.2" - aws4.selfAWSInstance = &awsInstance{nodeName: fakeServices.instanceId} - - addrs4, err4 := aws4.NodeAddresses(fakeServices.instanceId) - if err4 != nil { - t.Errorf("unexpected error: %v", err4) - } - testHasNodeAddress(t, addrs4, api.NodeInternalIP, "192.168.0.2") - testHasNodeAddress(t, addrs4, api.NodeExternalIP, "2.3.4.5") -} - -func TestGetRegion(t *testing.T) { - aws := mockAvailabilityZone("us-west-2", "us-west-2e") - zones, ok := aws.Zones() - if !ok { - t.Fatalf("Unexpected missing zones impl") - } - zone, err := zones.GetZone() - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if zone.Region != "us-west-2" { - t.Errorf("Unexpected region: %s", zone.Region) - } - if zone.FailureDomain != "us-west-2e" { - t.Errorf("Unexpected FailureDomain: %s", zone.FailureDomain) - } -} - -func TestFindVPCID(t *testing.T) { - awsServices := NewFakeAWSServices() - c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) - if err != nil { - t.Errorf("Error building aws cloud: %v", err) - return - } - vpcID, err := c.findVPCID() - if err != nil { - t.Errorf("Unexpected error:", err) - } - if vpcID != "vpc-mac0" { - t.Errorf("Unexpected vpcID: %s", vpcID) - } -} - -func TestLoadBalancerMatchesClusterRegion(t *testing.T) { - awsServices := NewFakeAWSServices() - c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) - if err != nil { - t.Errorf("Error building aws cloud: %v", err) - return - } - - badELBRegion := "bad-elb-region" - errorMessage := fmt.Sprintf("requested load balancer region '%s' does not match cluster region '%s'", badELBRegion, c.region) - - _, _, err = c.GetLoadBalancer("elb-name", badELBRegion) - if err == nil || err.Error() != errorMessage { - t.Errorf("Expected GetLoadBalancer region mismatch error.") - } - - serviceName := types.NamespacedName{Namespace: "foo", Name: "bar"} - - _, err = c.EnsureLoadBalancer("elb-name", badELBRegion, nil, nil, nil, serviceName, api.ServiceAffinityNone) - if err == nil || err.Error() != errorMessage { - t.Errorf("Expected EnsureLoadBalancer region mismatch error.") - } - - err = c.EnsureLoadBalancerDeleted("elb-name", badELBRegion) - if err == nil || err.Error() != errorMessage { - t.Errorf("Expected EnsureLoadBalancerDeleted region mismatch error.") - } - - err = c.UpdateLoadBalancer("elb-name", badELBRegion, nil) - if err == nil || err.Error() != errorMessage { - t.Errorf("Expected UpdateLoadBalancer region mismatch error.") - } -} - -func constructSubnets(subnetsIn map[int]map[string]string) (subnetsOut []*ec2.Subnet) { - for i := range subnetsIn { - subnetsOut = append( - subnetsOut, - constructSubnet( - subnetsIn[i]["id"], - subnetsIn[i]["az"], - ), - ) - } - return -} - -func constructSubnet(id string, az string) *ec2.Subnet { - return &ec2.Subnet{ - SubnetId: &id, - AvailabilityZone: &az, - } -} - -func TestSubnetIDsinVPC(t *testing.T) { - awsServices := NewFakeAWSServices() - c, err := newAWSCloud(strings.NewReader("[global]"), awsServices) - if err != nil { - t.Errorf("Error building aws cloud: %v", err) - return - } - - vpcID := "vpc-deadbeef" - - // test with 3 subnets from 3 different AZs - subnets := make(map[int]map[string]string) - subnets[0] = make(map[string]string) - subnets[0]["id"] = "subnet-a0000001" - subnets[0]["az"] = "af-south-1a" - subnets[1] = make(map[string]string) - subnets[1]["id"] = "subnet-b0000001" - subnets[1]["az"] = "af-south-1b" - subnets[2] = make(map[string]string) - subnets[2]["id"] = "subnet-c0000001" - subnets[2]["az"] = "af-south-1c" - awsServices.ec2.Subnets = constructSubnets(subnets) - - result, err := c.listSubnetIDsinVPC(vpcID) - if err != nil { - t.Errorf("Error listing subnets: %v", err) - return - } - - if len(result) != 3 { - t.Errorf("Expected 3 subnets but got %d", len(result)) - return - } - - result_set := make(map[string]bool) - for _, v := range result { - result_set[v] = true - } - - for i := range subnets { - if !result_set[subnets[i]["id"]] { - t.Errorf("Expected subnet%d '%s' in result: %v", i, subnets[i]["id"], result) - return - } - } - - // test with 4 subnets from 3 different AZs - // add duplicate az subnet - subnets[3] = make(map[string]string) - subnets[3]["id"] = "subnet-c0000002" - subnets[3]["az"] = "af-south-1c" - awsServices.ec2.Subnets = constructSubnets(subnets) - - result, err = c.listSubnetIDsinVPC(vpcID) - if err != nil { - t.Errorf("Error listing subnets: %v", err) - return - } - - if len(result) != 3 { - t.Errorf("Expected 3 subnets but got %d", len(result)) - return - } - -} - -func TestIpPermissionExistsHandlesMultipleGroupIds(t *testing.T) { - oldIpPermission := ec2.IpPermission{ - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: aws.String("firstGroupId")}, - {GroupId: aws.String("secondGroupId")}, - {GroupId: aws.String("thirdGroupId")}, - }, - } - - existingIpPermission := ec2.IpPermission{ - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: aws.String("secondGroupId")}, - }, - } - - newIpPermission := ec2.IpPermission{ - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: aws.String("fourthGroupId")}, - }, - } - - equals := ipPermissionExists(&existingIpPermission, &oldIpPermission, false) - if !equals { - t.Errorf("Should have been considered equal since first is in the second array of groups") - } - - equals = ipPermissionExists(&newIpPermission, &oldIpPermission, false) - if equals { - t.Errorf("Should have not been considered equal since first is not in the second array of groups") - } -} - -func TestIpPermissionExistsHandlesRangeSubsets(t *testing.T) { - // Two existing scenarios we'll test against - emptyIpPermission := ec2.IpPermission{} - - oldIpPermission := ec2.IpPermission{ - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("10.0.0.0/8")}, - {CidrIp: aws.String("192.168.1.0/24")}, - }, - } - - // Two already existing ranges and a new one - existingIpPermission := ec2.IpPermission{ - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("10.0.0.0/8")}, - }, - } - existingIpPermission2 := ec2.IpPermission{ - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("192.168.1.0/24")}, - }, - } - - newIpPermission := ec2.IpPermission{ - IpRanges: []*ec2.IpRange{ - {CidrIp: aws.String("172.16.0.0/16")}, - }, - } - - exists := ipPermissionExists(&emptyIpPermission, &emptyIpPermission, false) - if !exists { - t.Errorf("Should have been considered existing since we're comparing a range array against itself") - } - exists = ipPermissionExists(&oldIpPermission, &oldIpPermission, false) - if !exists { - t.Errorf("Should have been considered existing since we're comparing a range array against itself") - } - - exists = ipPermissionExists(&existingIpPermission, &oldIpPermission, false) - if !exists { - t.Errorf("Should have been considered existing since 10.* is in oldIpPermission's array of ranges") - } - exists = ipPermissionExists(&existingIpPermission2, &oldIpPermission, false) - if !exists { - t.Errorf("Should have been considered existing since 192.* is in oldIpPermission2's array of ranges") - } - - exists = ipPermissionExists(&newIpPermission, &emptyIpPermission, false) - if exists { - t.Errorf("Should have not been considered existing since we compared against a missing array of ranges") - } - exists = ipPermissionExists(&newIpPermission, &oldIpPermission, false) - if exists { - t.Errorf("Should have not been considered existing since 172.* is not in oldIpPermission's array of ranges") - } -} - -func TestIpPermissionExistsHandlesMultipleGroupIdsWithUserIds(t *testing.T) { - oldIpPermission := ec2.IpPermission{ - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: aws.String("firstGroupId"), UserId: aws.String("firstUserId")}, - {GroupId: aws.String("secondGroupId"), UserId: aws.String("secondUserId")}, - {GroupId: aws.String("thirdGroupId"), UserId: aws.String("thirdUserId")}, - }, - } - - existingIpPermission := ec2.IpPermission{ - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: aws.String("secondGroupId"), UserId: aws.String("secondUserId")}, - }, - } - - newIpPermission := ec2.IpPermission{ - UserIdGroupPairs: []*ec2.UserIdGroupPair{ - {GroupId: aws.String("secondGroupId"), UserId: aws.String("anotherUserId")}, - }, - } - - equals := ipPermissionExists(&existingIpPermission, &oldIpPermission, true) - if !equals { - t.Errorf("Should have been considered equal since first is in the second array of groups") - } - - equals = ipPermissionExists(&newIpPermission, &oldIpPermission, true) - if equals { - t.Errorf("Should have not been considered equal since first is not in the second array of groups") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_utils.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_utils.go deleted file mode 100644 index 310b4898e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_utils.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws - -import ( - "github.com/aws/aws-sdk-go/aws" - "k8s.io/kubernetes/pkg/util/sets" -) - -func stringSetToPointers(in sets.String) []*string { - if in == nil { - return nil - } - out := make([]*string, len(in)) - for k := range in { - out = append(out, aws.String(k)) - } - return out -} - -func stringSetFromPointers(in []*string) sets.String { - if in == nil { - return nil - } - out := sets.NewString() - for i := range in { - out.Insert(orEmpty(in[i])) - } - return out -} - -func orZero(v *int64) int64 { - if v == nil { - return 0 - } - return *v -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/log_handler.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/log_handler.go deleted file mode 100644 index 177c7074a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/log_handler.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package aws - -import ( - "github.com/aws/aws-sdk-go/aws/request" - "github.com/golang/glog" -) - -// Handler for aws-sdk-go that logs all requests -func awsHandlerLogger(req *request.Request) { - service := req.ClientInfo.ServiceName - - name := "?" - if req.Operation != nil { - name = req.Operation.Name - } - - glog.V(4).Infof("AWS request: %s %s", service, name) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/fake/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/fake/doc.go deleted file mode 100644 index ff22d568f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/fake/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package fake is a test-double implementation of cloudprovider -// Interface, LoadBalancer and Instances. It is useful for testing. -package fake diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/fake/fake.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/fake/fake.go deleted file mode 100644 index 498dce53c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/fake/fake.go +++ /dev/null @@ -1,259 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package fake - -import ( - "errors" - "fmt" - "net" - "regexp" - "sync" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/cloudprovider" - "k8s.io/kubernetes/pkg/types" -) - -const ProviderName = "fake" - -// FakeBalancer is a fake storage of balancer information -type FakeBalancer struct { - Name string - Region string - ExternalIP net.IP - Ports []*api.ServicePort - Hosts []string -} - -type FakeUpdateBalancerCall struct { - Name string - Region string - Hosts []string -} - -// FakeCloud is a test-double implementation of Interface, LoadBalancer, Instances, and Routes. It is useful for testing. -type FakeCloud struct { - Exists bool - Err error - Calls []string - Addresses []api.NodeAddress - ExtID map[string]string - InstanceTypes map[string]string - Machines []string - NodeResources *api.NodeResources - ClusterList []string - MasterName string - ExternalIP net.IP - Balancers map[string]FakeBalancer - UpdateCalls []FakeUpdateBalancerCall - RouteMap map[string]*FakeRoute - Lock sync.Mutex - cloudprovider.Zone -} - -type FakeRoute struct { - ClusterName string - Route cloudprovider.Route -} - -func (f *FakeCloud) addCall(desc string) { - f.Calls = append(f.Calls, desc) -} - -// ClearCalls clears internal record of method calls to this FakeCloud. -func (f *FakeCloud) ClearCalls() { - f.Calls = []string{} -} - -func (f *FakeCloud) ListClusters() ([]string, error) { - return f.ClusterList, f.Err -} - -func (f *FakeCloud) Master(name string) (string, error) { - return f.MasterName, f.Err -} - -func (f *FakeCloud) Clusters() (cloudprovider.Clusters, bool) { - return f, true -} - -// ProviderName returns the cloud provider ID. -func (f *FakeCloud) ProviderName() string { - return ProviderName -} - -// ScrubDNS filters DNS settings for pods. -func (f *FakeCloud) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) { - return nameservers, searches -} - -// LoadBalancer returns a fake implementation of LoadBalancer. -// Actually it just returns f itself. -func (f *FakeCloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) { - return f, true -} - -// Instances returns a fake implementation of Instances. -// -// Actually it just returns f itself. -func (f *FakeCloud) Instances() (cloudprovider.Instances, bool) { - return f, true -} - -func (f *FakeCloud) Zones() (cloudprovider.Zones, bool) { - return f, true -} - -func (f *FakeCloud) Routes() (cloudprovider.Routes, bool) { - return f, true -} - -// GetLoadBalancer is a stub implementation of LoadBalancer.GetLoadBalancer. -func (f *FakeCloud) GetLoadBalancer(name, region string) (*api.LoadBalancerStatus, bool, error) { - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: f.ExternalIP.String()}} - - return status, f.Exists, f.Err -} - -// EnsureLoadBalancer is a test-spy implementation of LoadBalancer.EnsureLoadBalancer. -// It adds an entry "create" into the internal method call record. -func (f *FakeCloud) EnsureLoadBalancer(name, region string, externalIP net.IP, ports []*api.ServicePort, hosts []string, serviceName types.NamespacedName, affinityType api.ServiceAffinity) (*api.LoadBalancerStatus, error) { - f.addCall("create") - if f.Balancers == nil { - f.Balancers = make(map[string]FakeBalancer) - } - f.Balancers[name] = FakeBalancer{name, region, externalIP, ports, hosts} - - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: f.ExternalIP.String()}} - - return status, f.Err -} - -// UpdateLoadBalancer is a test-spy implementation of LoadBalancer.UpdateLoadBalancer. -// It adds an entry "update" into the internal method call record. -func (f *FakeCloud) UpdateLoadBalancer(name, region string, hosts []string) error { - f.addCall("update") - f.UpdateCalls = append(f.UpdateCalls, FakeUpdateBalancerCall{name, region, hosts}) - return f.Err -} - -// EnsureLoadBalancerDeleted is a test-spy implementation of LoadBalancer.EnsureLoadBalancerDeleted. -// It adds an entry "delete" into the internal method call record. -func (f *FakeCloud) EnsureLoadBalancerDeleted(name, region string) error { - f.addCall("delete") - return f.Err -} - -func (f *FakeCloud) AddSSHKeyToAllInstances(user string, keyData []byte) error { - return errors.New("unimplemented") -} - -// Implementation of Instances.CurrentNodeName -func (f *FakeCloud) CurrentNodeName(hostname string) (string, error) { - return hostname, nil -} - -// NodeAddresses is a test-spy implementation of Instances.NodeAddresses. -// It adds an entry "node-addresses" into the internal method call record. -func (f *FakeCloud) NodeAddresses(instance string) ([]api.NodeAddress, error) { - f.addCall("node-addresses") - return f.Addresses, f.Err -} - -// ExternalID is a test-spy implementation of Instances.ExternalID. -// It adds an entry "external-id" into the internal method call record. -// It returns an external id to the mapped instance name, if not found, it will return "ext-{instance}" -func (f *FakeCloud) ExternalID(instance string) (string, error) { - f.addCall("external-id") - return f.ExtID[instance], f.Err -} - -// InstanceID returns the cloud provider ID of the specified instance. -func (f *FakeCloud) InstanceID(instance string) (string, error) { - f.addCall("instance-id") - return f.ExtID[instance], nil -} - -// InstanceType returns the type of the specified instance. -func (f *FakeCloud) InstanceType(instance string) (string, error) { - f.addCall("instance-type") - return f.InstanceTypes[instance], nil -} - -// List is a test-spy implementation of Instances.List. -// It adds an entry "list" into the internal method call record. -func (f *FakeCloud) List(filter string) ([]string, error) { - f.addCall("list") - result := []string{} - for _, machine := range f.Machines { - if match, _ := regexp.MatchString(filter, machine); match { - result = append(result, machine) - } - } - return result, f.Err -} - -func (f *FakeCloud) GetZone() (cloudprovider.Zone, error) { - f.addCall("get-zone") - return f.Zone, f.Err -} - -func (f *FakeCloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error) { - f.Lock.Lock() - defer f.Lock.Unlock() - f.addCall("list-routes") - var routes []*cloudprovider.Route - for _, fakeRoute := range f.RouteMap { - if clusterName == fakeRoute.ClusterName { - routeCopy := fakeRoute.Route - routes = append(routes, &routeCopy) - } - } - return routes, f.Err -} - -func (f *FakeCloud) CreateRoute(clusterName string, nameHint string, route *cloudprovider.Route) error { - f.Lock.Lock() - defer f.Lock.Unlock() - f.addCall("create-route") - name := clusterName + "-" + nameHint - if _, exists := f.RouteMap[name]; exists { - f.Err = fmt.Errorf("route %q already exists", name) - return f.Err - } - fakeRoute := FakeRoute{} - fakeRoute.Route = *route - fakeRoute.Route.Name = name - fakeRoute.ClusterName = clusterName - f.RouteMap[name] = &fakeRoute - return nil -} - -func (f *FakeCloud) DeleteRoute(clusterName string, route *cloudprovider.Route) error { - f.Lock.Lock() - defer f.Lock.Unlock() - f.addCall("delete-route") - name := route.Name - if _, exists := f.RouteMap[name]; !exists { - f.Err = fmt.Errorf("no route found with name %q", name) - return f.Err - } - delete(f.RouteMap, name) - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go index f7bd672fb..bf458ce8e 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go @@ -30,10 +30,12 @@ import ( "time" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/service" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" + netsets "k8s.io/kubernetes/pkg/util/net/sets" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" @@ -61,6 +63,11 @@ const ( operationPollInterval = 3 * time.Second operationPollTimeoutDuration = 30 * time.Minute + + // Each page can have 500 results, but we cap how many pages + // are iterated through to prevent infinite loops if the API + // were to continuously return a nextPageToken. + maxPages = 25 ) // GCECloud is an implementation of Interface, LoadBalancer and Instances for Google Compute Engine. @@ -69,7 +76,7 @@ type GCECloud struct { containerService *container.Service projectID string region string - localZone string // The zone in which we are runniing + 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) networkURL string useMetadataServer bool @@ -131,6 +138,19 @@ func getCurrentExternalIDViaMetadata() (string, error) { return externalID, nil } +func getCurrentMachineTypeViaMetadata() (string, error) { + mType, err := metadata.Get("instance/machine-type") + if err != nil { + return "", fmt.Errorf("couldn't get machine type: %v", err) + } + parts := strings.Split(mType, "/") + if len(parts) != 4 { + return "", fmt.Errorf("unexpected response for machine type: %s", mType) + } + + return parts[3], nil +} + func getNetworkNameViaMetadata() (string, error) { result, err := metadata.Get("instance/network-interfaces/0/network") if err != nil { @@ -144,6 +164,7 @@ func getNetworkNameViaMetadata() (string, error) { } func getNetworkNameViaAPICall(svc *compute.Service, projectID string) (string, error) { + // TODO: use PageToken to list all not just the first 500 networkList, err := svc.Networks.List(projectID).Do() if err != nil { return "", err @@ -157,6 +178,7 @@ func getNetworkNameViaAPICall(svc *compute.Service, projectID string) (string, e } func getZonesForRegion(svc *compute.Service, projectID, region string) ([]string, error) { + // TODO: use PageToken to list all not just the first 500 listCall := svc.Zones.List(projectID) // Filtering by region doesn't seem to work @@ -432,12 +454,13 @@ 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(name, region string, requestedIP net.IP, ports []*api.ServicePort, hostNames []string, serviceName types.NamespacedName, affinityType api.ServiceAffinity) (*api.LoadBalancerStatus, error) { +func (gce *GCECloud) EnsureLoadBalancer(name, region string, requestedIP net.IP, ports []*api.ServicePort, hostNames []string, svc types.NamespacedName, affinityType api.ServiceAffinity, annotations map[string]string) (*api.LoadBalancerStatus, error) { portStr := []string{} for _, p := range ports { portStr = append(portStr, fmt.Sprintf("%s/%d", p.Protocol, p.Port)) } - glog.V(2).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", name, region, requestedIP, portStr, hostNames, serviceName) + serviceName := svc.String() + glog.V(2).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", name, region, requestedIP, portStr, hostNames, serviceName, annotations) if len(hostNames) == 0 { return nil, fmt.Errorf("Cannot EnsureLoadBalancer() with no hosts") @@ -511,7 +534,7 @@ func (gce *GCECloud) EnsureLoadBalancer(name, region string, requestedIP net.IP, // to this forwarding rule, so we can keep it. isUserOwnedIP = false isSafeToReleaseIP = true - ipAddress, _, err = gce.ensureStaticIP(name, region, fwdRuleIP) + ipAddress, _, err = gce.ensureStaticIP(name, serviceName, region, fwdRuleIP) if err != nil { return nil, fmt.Errorf("failed to ensure static IP %s: %v", fwdRuleIP, err) } @@ -532,7 +555,7 @@ func (gce *GCECloud) EnsureLoadBalancer(name, region string, requestedIP net.IP, // IP from ephemeral to static, or it will just get the IP if it is // already static. existed := false - ipAddress, existed, err = gce.ensureStaticIP(name, region, fwdRuleIP) + ipAddress, existed, err = gce.ensureStaticIP(name, serviceName, region, fwdRuleIP) if err != nil { return nil, fmt.Errorf("failed to ensure static IP %s: %v", fwdRuleIP, err) } @@ -555,22 +578,28 @@ func (gce *GCECloud) EnsureLoadBalancer(name, region string, requestedIP net.IP, // Deal with the firewall next. The reason we do this here rather than last // is because the forwarding rule is used as the indicator that the load // balancer is fully created - it's what getLoadBalancer checks for. - firewallExists, firewallNeedsUpdate, err := gce.firewallNeedsUpdate(name, region, ipAddress, ports) + // Check if user specified the allow source range + sourceRanges, err := service.GetLoadBalancerSourceRanges(annotations) + if err != nil { + return nil, err + } + + firewallExists, firewallNeedsUpdate, err := gce.firewallNeedsUpdate(name, serviceName, region, ipAddress, ports, sourceRanges) if err != nil { return nil, err } if firewallNeedsUpdate { - desc := makeFirewallDescription(ipAddress) + desc := makeFirewallDescription(serviceName, ipAddress) // Unlike forwarding rules and target pools, firewalls can be updated // without needing to be deleted and recreated. if firewallExists { - if err := gce.updateFirewall(name, region, desc, "0.0.0.0/0", ports, hosts); err != nil { + if err := gce.updateFirewall(name, region, desc, sourceRanges, ports, hosts); err != nil { return nil, err } glog.V(4).Infof("EnsureLoadBalancer(%v(%v)): updated firewall", name, serviceName) } else { - if err := gce.createFirewall(name, region, desc, "0.0.0.0/0", ports, hosts); err != nil { + if err := gce.createFirewall(name, region, desc, sourceRanges, ports, hosts); err != nil { return nil, err } glog.V(4).Infof("EnsureLoadBalancer(%v(%v)): created firewall", name, serviceName) @@ -609,13 +638,13 @@ func (gce *GCECloud) EnsureLoadBalancer(name, region string, requestedIP net.IP, // Once we've deleted the resources (if necessary), build them back up (or for // the first time if they're new). if tpNeedsUpdate { - if err := gce.createTargetPool(name, region, hosts, affinityType); err != nil { + if err := gce.createTargetPool(name, serviceName, region, hosts, affinityType); err != nil { return nil, fmt.Errorf("failed to create target pool %s: %v", name, err) } glog.V(4).Infof("EnsureLoadBalancer(%v(%v)): created target pool", name, serviceName) } if tpNeedsUpdate || fwdRuleNeedsUpdate { - if err := gce.createForwardingRule(name, region, ipAddress, ports); err != nil { + if err := gce.createForwardingRule(name, serviceName, region, ipAddress, ports); err != nil { return nil, fmt.Errorf("failed to create forwarding rule %s: %v", name, err) } // End critical section. It is safe to release the static IP (which @@ -713,7 +742,7 @@ func translateAffinityType(affinityType api.ServiceAffinity) string { } } -func (gce *GCECloud) firewallNeedsUpdate(name, region, ipAddress string, ports []*api.ServicePort) (exists bool, needsUpdate bool, err error) { +func (gce *GCECloud) firewallNeedsUpdate(name, serviceName, region, ipAddress string, ports []*api.ServicePort, sourceRanges netsets.IPNet) (exists bool, needsUpdate bool, err error) { fw, err := gce.service.Firewalls.Get(gce.projectID, makeFirewallName(name)).Do() if err != nil { if isHTTPErrorCode(err, http.StatusNotFound) { @@ -721,7 +750,7 @@ func (gce *GCECloud) firewallNeedsUpdate(name, region, ipAddress string, ports [ } return false, false, fmt.Errorf("error getting load balancer's target pool: %v", err) } - if fw.Description != makeFirewallDescription(ipAddress) { + if fw.Description != makeFirewallDescription(serviceName, ipAddress) { return true, true, nil } if len(fw.Allowed) != 1 || (fw.Allowed[0].IPProtocol != "tcp" && fw.Allowed[0].IPProtocol != "udp") { @@ -737,6 +766,17 @@ func (gce *GCECloud) firewallNeedsUpdate(name, region, ipAddress string, ports [ } // The service controller already verified that the protocol matches on all ports, no need to check. + actualSourceRanges, err := netsets.ParseIPNets(fw.SourceRanges...) + if err != nil { + // This really shouldn't happen... GCE has returned something unexpected + glog.Warningf("Error parsing firewall SourceRanges: %v", fw.SourceRanges) + // We don't return the error, because we can hopefully recover from this by reconfiguring the firewall + return true, true, nil + } + + if !sourceRanges.Equal(actualSourceRanges) { + return true, true, nil + } return true, false, nil } @@ -744,8 +784,9 @@ func makeFirewallName(name string) string { return fmt.Sprintf("k8s-fw-%s", name) } -func makeFirewallDescription(ipAddress string) string { - return fmt.Sprintf("KubernetesAutoGenerated_OnlyAllowTrafficForDestinationIP_%s", ipAddress) +func makeFirewallDescription(serviceName, ipAddress string) string { + return fmt.Sprintf(`{"kubernetes.io/service-ip":"%s", "kubernetes.io/service-name":"%s"}`, + ipAddress, serviceName) } func slicesEqual(x, y []string) bool { @@ -762,16 +803,18 @@ func slicesEqual(x, y []string) bool { return true } -func (gce *GCECloud) createForwardingRule(name, region, ipAddress string, ports []*api.ServicePort) error { +func (gce *GCECloud) createForwardingRule(name, serviceName, region, ipAddress string, ports []*api.ServicePort) error { portRange, err := loadBalancerPortRange(ports) if err != nil { return err } req := &compute.ForwardingRule{ - Name: name, - IPAddress: ipAddress, IPProtocol: string(ports[0].Protocol), - PortRange: portRange, - Target: gce.targetPoolURL(name, region), + Name: name, + Description: fmt.Sprintf(`{"kubernetes.io/service-name":"%s"}`, serviceName), + IPAddress: ipAddress, + IPProtocol: string(ports[0].Protocol), + PortRange: portRange, + Target: gce.targetPoolURL(name, region), } op, err := gce.service.ForwardingRules.Insert(gce.projectID, region, req).Do() @@ -787,13 +830,14 @@ func (gce *GCECloud) createForwardingRule(name, region, ipAddress string, ports return nil } -func (gce *GCECloud) createTargetPool(name, region string, hosts []*gceInstance, affinityType api.ServiceAffinity) error { +func (gce *GCECloud) createTargetPool(name, serviceName, region string, hosts []*gceInstance, affinityType api.ServiceAffinity) error { var instances []string for _, host := range hosts { instances = append(instances, makeHostURL(gce.projectID, host.Zone, host.Name)) } pool := &compute.TargetPool{ Name: name, + Description: fmt.Sprintf(`{"kubernetes.io/service-name":"%s"}`, serviceName), Instances: instances, SessionAffinity: translateAffinityType(affinityType), } @@ -810,8 +854,8 @@ func (gce *GCECloud) createTargetPool(name, region string, hosts []*gceInstance, return nil } -func (gce *GCECloud) createFirewall(name, region, desc, srcRange string, ports []*api.ServicePort, hosts []*gceInstance) error { - firewall, err := gce.firewallObject(name, region, desc, srcRange, ports, hosts) +func (gce *GCECloud) createFirewall(name, region, desc string, sourceRanges netsets.IPNet, ports []*api.ServicePort, hosts []*gceInstance) error { + firewall, err := gce.firewallObject(name, region, desc, sourceRanges, ports, hosts) if err != nil { return err } @@ -828,8 +872,8 @@ func (gce *GCECloud) createFirewall(name, region, desc, srcRange string, ports [ return nil } -func (gce *GCECloud) updateFirewall(name, region, desc, srcRange string, ports []*api.ServicePort, hosts []*gceInstance) error { - firewall, err := gce.firewallObject(name, region, desc, srcRange, ports, hosts) +func (gce *GCECloud) updateFirewall(name, region, desc string, sourceRanges netsets.IPNet, ports []*api.ServicePort, hosts []*gceInstance) error { + firewall, err := gce.firewallObject(name, region, desc, sourceRanges, ports, hosts) if err != nil { return err } @@ -846,7 +890,7 @@ func (gce *GCECloud) updateFirewall(name, region, desc, srcRange string, ports [ return nil } -func (gce *GCECloud) firewallObject(name, region, desc, srcRange string, ports []*api.ServicePort, hosts []*gceInstance) (*compute.Firewall, error) { +func (gce *GCECloud) firewallObject(name, region, desc string, sourceRanges netsets.IPNet, ports []*api.ServicePort, hosts []*gceInstance) (*compute.Firewall, error) { allowedPorts := make([]string, len(ports)) for ix := range ports { allowedPorts[ix] = strconv.Itoa(ports[ix].Port) @@ -859,7 +903,7 @@ func (gce *GCECloud) firewallObject(name, region, desc, srcRange string, ports [ Name: makeFirewallName(name), Description: desc, Network: gce.networkURL, - SourceRanges: []string{srcRange}, + SourceRanges: sourceRanges.StringSlice(), TargetTags: hostTags, Allowed: []*compute.FirewallAllowed{ { @@ -885,31 +929,42 @@ func (gce *GCECloud) computeHostTags(hosts []*gceInstance) ([]string, error) { tags := sets.NewString() for zone, hostNames := range hostNamesByZone { - listCall := gce.service.Instances.List(gce.projectID, zone) + pageToken := "" + page := 0 + for ; page == 0 || (pageToken != "" && page < maxPages); page++ { + listCall := gce.service.Instances.List(gce.projectID, zone) - // Add the filter for hosts - listCall = listCall.Filter("name eq (" + strings.Join(hostNames, "|") + ")") + // Add the filter for hosts + listCall = listCall.Filter("name eq (" + strings.Join(hostNames, "|") + ")") - // Add the fields we want - listCall = listCall.Fields("items(name,tags)") + // Add the fields we want + listCall = listCall.Fields("items(name,tags)") - res, err := listCall.Do() - if err != nil { - return nil, err - } + if pageToken != "" { + listCall = listCall.PageToken(pageToken) + } - for _, instance := range res.Items { - longest_tag := "" - for _, tag := range instance.Tags.Items { - if strings.HasPrefix(instance.Name, tag) && len(tag) > len(longest_tag) { - longest_tag = tag + res, err := listCall.Do() + if err != nil { + return nil, err + } + pageToken = res.NextPageToken + for _, instance := range res.Items { + longest_tag := "" + for _, tag := range instance.Tags.Items { + if strings.HasPrefix(instance.Name, tag) && len(tag) > len(longest_tag) { + longest_tag = tag + } + } + if len(longest_tag) > 0 { + tags.Insert(longest_tag) + } else if len(tags) > 0 { + return nil, fmt.Errorf("Some, but not all, instances have prefix tags (%s is missing)", instance.Name) } } - if len(longest_tag) > 0 { - tags.Insert(longest_tag) - } else if len(tags) > 0 { - return nil, fmt.Errorf("Some, but not all, instances have prefix tags (%s is missing)", instance.Name) - } + } + if page >= maxPages { + glog.Errorf("computeHostTags exceeded maxPages=%d for Instances.List: truncating.", maxPages) } } @@ -921,26 +976,41 @@ func (gce *GCECloud) computeHostTags(hosts []*gceInstance) ([]string, error) { } func (gce *GCECloud) projectOwnsStaticIP(name, region string, ipAddress string) (bool, error) { - addresses, err := gce.service.Addresses.List(gce.projectID, region).Do() - if err != nil { - return false, fmt.Errorf("failed to list gce IP addresses: %v", err) - } - for _, addr := range addresses.Items { - if addr.Address == ipAddress { - // This project does own the address, so return success. - return true, nil + pageToken := "" + page := 0 + for ; page == 0 || (pageToken != "" && page < maxPages); page++ { + listCall := gce.service.Addresses.List(gce.projectID, region) + if pageToken != "" { + listCall = listCall.PageToken(pageToken) } + addresses, err := listCall.Do() + if err != nil { + return false, fmt.Errorf("failed to list gce IP addresses: %v", err) + } + pageToken = addresses.NextPageToken + for _, addr := range addresses.Items { + if addr.Address == ipAddress { + // This project does own the address, so return success. + return true, nil + } + } + } + if page >= maxPages { + glog.Errorf("projectOwnsStaticIP exceeded maxPages=%d for Addresses.List; truncating.", maxPages) } return false, nil } -func (gce *GCECloud) ensureStaticIP(name, region, existingIP string) (ipAddress string, created bool, err error) { +func (gce *GCECloud) ensureStaticIP(name, serviceName, region, existingIP string) (ipAddress string, created bool, err error) { // If the address doesn't exist, this will create it. // If the existingIP exists but is ephemeral, this will promote it to static. // If the address already exists, this will harmlessly return a StatusConflict // and we'll grab the IP before returning. existed := false - addressObj := &compute.Address{Name: name} + addressObj := &compute.Address{ + Name: name, + Description: fmt.Sprintf(`{"kubernetes.io/service-name":"%s"}`, serviceName), + } if existingIP != "" { addressObj.Address = existingIP } @@ -1138,7 +1208,7 @@ func (gce *GCECloud) GetFirewall(name string) (*compute.Firewall, error) { } // CreateFirewall creates the given firewall rule. -func (gce *GCECloud) CreateFirewall(name, desc, srcRange string, ports []int64, hostNames []string) error { +func (gce *GCECloud) CreateFirewall(name, desc string, sourceRanges netsets.IPNet, ports []int64, hostNames []string) error { region, err := GetGCERegion(gce.localZone) if err != nil { return err @@ -1153,7 +1223,7 @@ func (gce *GCECloud) CreateFirewall(name, desc, srcRange string, ports []int64, if err != nil { return err } - return gce.createFirewall(name, region, desc, srcRange, svcPorts, hosts) + return gce.createFirewall(name, region, desc, sourceRanges, svcPorts, hosts) } // DeleteFirewall deletes the given firewall rule. @@ -1167,7 +1237,7 @@ func (gce *GCECloud) DeleteFirewall(name string) error { // UpdateFirewall applies the given firewall rule as an update to an existing // firewall rule with the same name. -func (gce *GCECloud) UpdateFirewall(name, desc, srcRange string, ports []int64, hostNames []string) error { +func (gce *GCECloud) UpdateFirewall(name, desc string, sourceRanges netsets.IPNet, ports []int64, hostNames []string) error { region, err := GetGCERegion(gce.localZone) if err != nil { return err @@ -1182,7 +1252,7 @@ func (gce *GCECloud) UpdateFirewall(name, desc, srcRange string, ports []int64, if err != nil { return err } - return gce.updateFirewall(name, region, desc, srcRange, svcPorts, hosts) + return gce.updateFirewall(name, region, desc, sourceRanges, svcPorts, hosts) } // Global static IP management @@ -1266,6 +1336,7 @@ func (gce *GCECloud) DeleteUrlMap(name string) error { // ListUrlMaps lists all UrlMaps in the project. func (gce *GCECloud) ListUrlMaps() (*compute.UrlMapList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.UrlMaps.List(gce.projectID).Do() } @@ -1315,6 +1386,7 @@ func (gce *GCECloud) DeleteTargetHttpProxy(name string) error { // ListTargetHttpProxies lists all TargetHttpProxies in the project. func (gce *GCECloud) ListTargetHttpProxies() (*compute.TargetHttpProxyList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.TargetHttpProxies.List(gce.projectID).Do() } @@ -1374,6 +1446,7 @@ func (gce *GCECloud) DeleteTargetHttpsProxy(name string) error { // ListTargetHttpsProxies lists all TargetHttpsProxies in the project. func (gce *GCECloud) ListTargetHttpsProxies() (*compute.TargetHttpsProxyList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.TargetHttpsProxies.List(gce.projectID).Do() } @@ -1410,6 +1483,7 @@ func (gce *GCECloud) DeleteSslCertificate(name string) error { // ListSslCertificates lists all SslCertificates in the project. func (gce *GCECloud) ListSslCertificates() (*compute.SslCertificateList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.SslCertificates.List(gce.projectID).Do() } @@ -1464,6 +1538,7 @@ func (gce *GCECloud) GetGlobalForwardingRule(name string) (*compute.ForwardingRu // ListGlobalForwardingRules lists all GlobalForwardingRules in the project. func (gce *GCECloud) ListGlobalForwardingRules() (*compute.ForwardingRuleList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.GlobalForwardingRules.List(gce.projectID).Do() } @@ -1506,6 +1581,7 @@ func (gce *GCECloud) CreateBackendService(bg *compute.BackendService) error { // ListBackendServices lists all backend services in the project. func (gce *GCECloud) ListBackendServices() (*compute.BackendServiceList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.BackendServices.List(gce.projectID).Do() } @@ -1556,6 +1632,7 @@ func (gce *GCECloud) CreateHttpHealthCheck(hc *compute.HttpHealthCheck) error { // ListHttpHealthCheck lists all HttpHealthChecks in the project. func (gce *GCECloud) ListHttpHealthChecks() (*compute.HttpHealthCheckList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.HttpHealthChecks.List(gce.projectID).Do() } @@ -1586,11 +1663,13 @@ func (gce *GCECloud) DeleteInstanceGroup(name string, zone string) error { // ListInstanceGroups lists all InstanceGroups in the project and zone. func (gce *GCECloud) ListInstanceGroups(zone string) (*compute.InstanceGroupList, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.InstanceGroups.List(gce.projectID, zone).Do() } // ListInstancesInInstanceGroup lists all the instances in a given instance group and state. func (gce *GCECloud) ListInstancesInInstanceGroup(name string, zone string, state string) (*compute.InstanceGroupsListInstances, error) { + // TODO: use PageToken to list all not just the first 500 return gce.service.InstanceGroups.ListInstances( gce.projectID, zone, name, &compute.InstanceGroupsListInstancesRequest{InstanceState: state}).Do() @@ -1790,6 +1869,15 @@ func (gce *GCECloud) ExternalID(instance string) (string, error) { // InstanceID returns the cloud provider ID of the specified instance. func (gce *GCECloud) InstanceID(instanceName string) (string, error) { + if gce.useMetadataServer { + // Use metadata, if possible, to fetch ID. See issue #12000 + if gce.isCurrentInstance(instanceName) { + projectID, zone, err := getProjectAndZone() + if err == nil { + return projectID + "/" + zone + "/" + canonicalizeInstanceName(instanceName), nil + } + } + } instance, err := gce.getInstanceByName(instanceName) if err != nil { return "", err @@ -1799,6 +1887,15 @@ func (gce *GCECloud) InstanceID(instanceName string) (string, error) { // InstanceType returns the type of the specified instance. func (gce *GCECloud) InstanceType(instanceName string) (string, error) { + if gce.useMetadataServer { + // Use metadata, if possible, to fetch ID. See issue #12000 + if gce.isCurrentInstance(instanceName) { + mType, err := getCurrentMachineTypeViaMetadata() + if err == nil { + return mType, nil + } + } + } instance, err := gce.getInstanceByName(instanceName) if err != nil { return "", err @@ -1811,16 +1908,27 @@ func (gce *GCECloud) List(filter string) ([]string, error) { var instances []string // TODO: Parallelize, although O(zones) so not too bad (N <= 3 typically) for _, zone := range gce.managedZones { - listCall := gce.service.Instances.List(gce.projectID, zone) - if len(filter) > 0 { - listCall = listCall.Filter("name eq " + filter) + pageToken := "" + page := 0 + for ; page == 0 || (pageToken != "" && page < maxPages); page++ { + listCall := gce.service.Instances.List(gce.projectID, zone) + if len(filter) > 0 { + listCall = listCall.Filter("name eq " + filter) + } + if pageToken != "" { + listCall = listCall.PageToken(pageToken) + } + res, err := listCall.Do() + if err != nil { + return nil, err + } + pageToken = res.NextPageToken + for _, instance := range res.Items { + instances = append(instances, instance.Name) + } } - res, err := listCall.Do() - if err != nil { - return nil, err - } - for _, instance := range res.Items { - instances = append(instances, instance.Name) + if page >= maxPages { + glog.Errorf("List exceeded maxPages=%d for Instances.List: truncating.", maxPages) } } return instances, nil @@ -1843,31 +1951,42 @@ func truncateClusterName(clusterName string) string { } func (gce *GCECloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error) { - listCall := gce.service.Routes.List(gce.projectID) - - prefix := truncateClusterName(clusterName) - listCall = listCall.Filter("name eq " + prefix + "-.*") - - res, err := listCall.Do() - if err != nil { - return nil, err - } var routes []*cloudprovider.Route - for _, r := range res.Items { - if r.Network != gce.networkURL { - continue - } - // Not managed if route description != "k8s-node-route" - if r.Description != k8sNodeRouteTag { - continue - } - // Not managed if route name doesn't start with - if !strings.HasPrefix(r.Name, prefix) { - continue - } + pageToken := "" + page := 0 + for ; page == 0 || (pageToken != "" && page < maxPages); page++ { + listCall := gce.service.Routes.List(gce.projectID) - target := path.Base(r.NextHopInstance) - routes = append(routes, &cloudprovider.Route{Name: r.Name, TargetInstance: target, DestinationCIDR: r.DestRange}) + prefix := truncateClusterName(clusterName) + listCall = listCall.Filter("name eq " + prefix + "-.*") + if pageToken != "" { + listCall = listCall.PageToken(pageToken) + } + res, err := listCall.Do() + if err != nil { + glog.Errorf("Error getting routes from GCE: %v", err) + return nil, err + } + pageToken = res.NextPageToken + for _, r := range res.Items { + if r.Network != gce.networkURL { + continue + } + // Not managed if route description != "k8s-node-route" + if r.Description != k8sNodeRouteTag { + continue + } + // Not managed if route name doesn't start with + if !strings.HasPrefix(r.Name, prefix) { + continue + } + + target := path.Base(r.NextHopInstance) + routes = append(routes, &cloudprovider.Route{Name: r.Name, TargetInstance: target, DestinationCIDR: r.DestRange}) + } + } + if page >= maxPages { + glog.Errorf("ListRoutes exceeded maxPages=%d for Routes.List; truncating.", maxPages) } return routes, nil } @@ -2125,6 +2244,7 @@ func (gce *GCECloud) convertDiskToAttachedDisk(disk *gceDisk, readWrite string) } func (gce *GCECloud) listClustersInZone(zone string) ([]string, error) { + // TODO: use PageToken to list all not just the first 500 list, err := gce.containerService.Projects.Zones.Clusters.List(gce.projectID, zone).Do() if err != nil { return nil, err @@ -2190,28 +2310,38 @@ func (gce *GCECloud) getInstancesByNames(names []string) ([]*gceInstance, error) break } - listCall := gce.service.Instances.List(gce.projectID, zone) + pageToken := "" + page := 0 + for ; page == 0 || (pageToken != "" && page < maxPages); page++ { + listCall := gce.service.Instances.List(gce.projectID, zone) - // Add the filter for hosts - listCall = listCall.Filter("name eq (" + strings.Join(remaining, "|") + ")") + // Add the filter for hosts + listCall = listCall.Filter("name eq (" + strings.Join(remaining, "|") + ")") - listCall = listCall.Fields("items(name,id,disks,machineType)") - - res, err := listCall.Do() - if err != nil { - return nil, err - } - - for _, i := range res.Items { - name := i.Name - instance := &gceInstance{ - Zone: zone, - Name: name, - ID: i.Id, - Disks: i.Disks, - Type: lastComponent(i.MachineType), + listCall = listCall.Fields("items(name,id,disks,machineType)") + if pageToken != "" { + listCall.PageToken(pageToken) } - instances[name] = instance + + res, err := listCall.Do() + if err != nil { + return nil, err + } + pageToken = res.NextPageToken + for _, i := range res.Items { + name := i.Name + instance := &gceInstance{ + Zone: zone, + Name: name, + ID: i.Id, + Disks: i.Disks, + Type: lastComponent(i.MachineType), + } + instances[name] = instance + } + } + if page >= maxPages { + glog.Errorf("getInstancesByNames exceeded maxPages=%d for Instances.List: truncating.", maxPages) } } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce_test.go deleted file mode 100644 index f1633d889..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce_test.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package gce - -import ( - "reflect" - "testing" -) - -func TestGetRegion(t *testing.T) { - zoneName := "us-central1-b" - regionName, err := GetGCERegion(zoneName) - if err != nil { - t.Fatalf("unexpected error from GetGCERegion: %v", err) - } - if regionName != "us-central1" { - t.Errorf("Unexpected region from GetGCERegion: %s", regionName) - } - gce := &GCECloud{ - localZone: zoneName, - region: regionName, - } - zones, ok := gce.Zones() - if !ok { - t.Fatalf("Unexpected missing zones impl") - } - zone, err := zones.GetZone() - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if zone.Region != "us-central1" { - t.Errorf("Unexpected region: %s", zone.Region) - } -} - -func TestComparingHostURLs(t *testing.T) { - tests := []struct { - host1 string - zone string - name string - expectEqual bool - }{ - { - host1: "https://www.googleapis.com/compute/v1/projects/1234567/zones/us-central1-f/instances/kubernetes-node-fhx1", - zone: "us-central1-f", - name: "kubernetes-node-fhx1", - expectEqual: true, - }, - { - host1: "https://www.googleapis.com/compute/v1/projects/cool-project/zones/us-central1-f/instances/kubernetes-node-fhx1", - zone: "us-central1-f", - name: "kubernetes-node-fhx1", - expectEqual: true, - }, - { - host1: "https://www.googleapis.com/compute/v23/projects/1234567/zones/us-central1-f/instances/kubernetes-node-fhx1", - zone: "us-central1-f", - name: "kubernetes-node-fhx1", - expectEqual: true, - }, - { - host1: "https://www.googleapis.com/compute/v24/projects/1234567/regions/us-central1/zones/us-central1-f/instances/kubernetes-node-fhx1", - zone: "us-central1-f", - name: "kubernetes-node-fhx1", - expectEqual: true, - }, - { - host1: "https://www.googleapis.com/compute/v1/projects/1234567/zones/us-central1-f/instances/kubernetes-node-fhx1", - zone: "us-central1-c", - name: "kubernetes-node-fhx1", - expectEqual: false, - }, - { - host1: "https://www.googleapis.com/compute/v1/projects/1234567/zones/us-central1-f/instances/kubernetes-node-fhx", - zone: "us-central1-f", - name: "kubernetes-node-fhx1", - expectEqual: false, - }, - { - host1: "https://www.googleapis.com/compute/v1/projects/1234567/zones/us-central1-f/instances/kubernetes-node-fhx1", - zone: "us-central1-f", - name: "kubernetes-node-fhx", - expectEqual: false, - }, - } - - for _, test := range tests { - link1 := hostURLToComparablePath(test.host1) - testInstance := &gceInstance{ - Name: canonicalizeInstanceName(test.name), - Zone: test.zone, - } - link2 := testInstance.makeComparableHostPath() - if test.expectEqual && link1 != link2 { - t.Errorf("expected link1 and link2 to be equal, got %s and %s", link1, link2) - } else if !test.expectEqual && link1 == link2 { - t.Errorf("expected link1 and link2 not to be equal, got %s and %s", link1, link2) - } - } -} - -func TestScrubDNS(t *testing.T) { - tcs := []struct { - nameserversIn []string - searchesIn []string - nameserversOut []string - searchesOut []string - }{ - { - nameserversIn: []string{"1.2.3.4", "5.6.7.8"}, - nameserversOut: []string{"1.2.3.4", "5.6.7.8"}, - }, - { - searchesIn: []string{"c.prj.internal.", "12345678910.google.internal.", "google.internal."}, - searchesOut: []string{"c.prj.internal.", "google.internal."}, - }, - { - searchesIn: []string{"c.prj.internal.", "12345678910.google.internal.", "zone.c.prj.internal.", "google.internal."}, - searchesOut: []string{"c.prj.internal.", "zone.c.prj.internal.", "google.internal."}, - }, - { - searchesIn: []string{"c.prj.internal.", "12345678910.google.internal.", "zone.c.prj.internal.", "google.internal.", "unexpected"}, - searchesOut: []string{"c.prj.internal.", "zone.c.prj.internal.", "google.internal.", "unexpected"}, - }, - } - gce := &GCECloud{} - for i := range tcs { - n, s := gce.ScrubDNS(tcs[i].nameserversIn, tcs[i].searchesIn) - if !reflect.DeepEqual(n, tcs[i].nameserversOut) { - t.Errorf("Expected %v, got %v", tcs[i].nameserversOut, n) - } - if !reflect.DeepEqual(s, tcs[i].searchesOut) { - t.Errorf("Expected %v, got %v", tcs[i].searchesOut, s) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client.go deleted file mode 100644 index 1b488bc62..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client.go +++ /dev/null @@ -1,376 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mesos - -import ( - "encoding/binary" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "sync" - "time" - - log "github.com/golang/glog" - "github.com/mesos/mesos-go/detector" - mesos "github.com/mesos/mesos-go/mesosproto" - "golang.org/x/net/context" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - utilnet "k8s.io/kubernetes/pkg/util/net" -) - -const defaultClusterName = "mesos" - -var noLeadingMasterError = errors.New("there is no current leading master available to query") - -type mesosClient struct { - masterLock sync.RWMutex - master string // host:port formatted address - httpClient *http.Client - tr *http.Transport - initialMaster <-chan struct{} // signal chan, closes once an initial, non-nil master is found - state *stateCache -} - -type slaveNode struct { - hostname string - kubeletRunning bool - resources *api.NodeResources -} - -type mesosState struct { - clusterName string - nodes map[string]*slaveNode // by hostname -} - -type stateCache struct { - sync.Mutex - expiresAt time.Time - cached *mesosState - err error - ttl time.Duration - refill func(context.Context) (*mesosState, error) -} - -// reloadCache reloads the state cache if it has expired. -func (c *stateCache) reloadCache(ctx context.Context) { - now := time.Now() - c.Lock() - defer c.Unlock() - if c.expiresAt.Before(now) { - log.V(4).Infof("Reloading cached Mesos state") - c.cached, c.err = c.refill(ctx) - c.expiresAt = now.Add(c.ttl) - } else { - log.V(4).Infof("Using cached Mesos state") - } -} - -// cachedState returns the cached Mesos state. -func (c *stateCache) cachedState(ctx context.Context) (*mesosState, error) { - c.reloadCache(ctx) - return c.cached, c.err -} - -// clusterName returns the cached Mesos cluster name. -func (c *stateCache) clusterName(ctx context.Context) (string, error) { - cached, err := c.cachedState(ctx) - if err != nil { - return "", err - } - return cached.clusterName, nil -} - -// nodes returns the cached list of slave nodes. -func (c *stateCache) nodes(ctx context.Context) (map[string]*slaveNode, error) { - cached, err := c.cachedState(ctx) - if err != nil { - return nil, err - } - return cached.nodes, nil -} - -func newMesosClient( - md detector.Master, - mesosHttpClientTimeout, stateCacheTTL time.Duration) (*mesosClient, error) { - - tr := utilnet.SetTransportDefaults(&http.Transport{}) - httpClient := &http.Client{ - Transport: tr, - Timeout: mesosHttpClientTimeout, - } - return createMesosClient(md, httpClient, tr, stateCacheTTL) -} - -func createMesosClient( - md detector.Master, - httpClient *http.Client, - tr *http.Transport, - stateCacheTTL time.Duration) (*mesosClient, error) { - - initialMaster := make(chan struct{}) - client := &mesosClient{ - httpClient: httpClient, - tr: tr, - initialMaster: initialMaster, - state: &stateCache{ - ttl: stateCacheTTL, - }, - } - client.state.refill = client.pollMasterForState - first := true - if err := md.Detect(detector.OnMasterChanged(func(info *mesos.MasterInfo) { - host, port := extractMasterAddress(info) - if len(host) > 0 { - client.masterLock.Lock() - defer client.masterLock.Unlock() - client.master = fmt.Sprintf("%s:%d", host, port) - if first { - first = false - close(initialMaster) - } - } - log.Infof("cloud master changed to '%v'", client.master) - })); err != nil { - log.V(1).Infof("detector initialization failed: %v", err) - return nil, err - } - return client, nil -} - -func extractMasterAddress(info *mesos.MasterInfo) (host string, port int) { - if info != nil { - host = info.GetAddress().GetHostname() - if host == "" { - host = info.GetAddress().GetIp() - } - - if host != "" { - // use port from Address - port = int(info.GetAddress().GetPort()) - } else { - // deprecated: get host and port directly from MasterInfo (and not Address) - host = info.GetHostname() - if host == "" { - host = unpackIPv4(info.GetIp()) - } - port = int(info.GetPort()) - } - } - return -} - -func unpackIPv4(ip uint32) string { - octets := make([]byte, 4, 4) - binary.BigEndian.PutUint32(octets, ip) - ipv4 := net.IP(octets) - return ipv4.String() -} - -// listSlaves returns a (possibly cached) map of slave nodes by hostname. -// Callers must not mutate the contents of the returned slice. -func (c *mesosClient) listSlaves(ctx context.Context) (map[string]*slaveNode, error) { - return c.state.nodes(ctx) -} - -// clusterName returns a (possibly cached) cluster name. -func (c *mesosClient) clusterName(ctx context.Context) (string, error) { - return c.state.clusterName(ctx) -} - -// pollMasterForState returns an array of slave nodes -func (c *mesosClient) pollMasterForState(ctx context.Context) (*mesosState, error) { - // wait for initial master detection - select { - case <-c.initialMaster: // noop - case <-ctx.Done(): - return nil, ctx.Err() - } - - master := func() string { - c.masterLock.RLock() - defer c.masterLock.RUnlock() - return c.master - }() - if master == "" { - return nil, noLeadingMasterError - } - - //TODO(jdef) should not assume master uses http (what about https?) - - var state *mesosState - successHandler := func(res *http.Response) error { - blob, err1 := ioutil.ReadAll(res.Body) - if err1 != nil { - return err1 - } - log.V(3).Infof("Got mesos state, content length %v", len(blob)) - state, err1 = parseMesosState(blob) - return err1 - } - // thinking here is that we may get some other status codes from mesos at some point: - // - authentication - // - redirection (possibly from http to https) - // ... - for _, tt := range []struct { - uri string - handlers map[int]func(*http.Response) error - }{ - { - uri: fmt.Sprintf("http://%s/state", master), - handlers: map[int]func(*http.Response) error{ - 200: successHandler, - }, - }, - { - uri: fmt.Sprintf("http://%s/state.json", master), - handlers: map[int]func(*http.Response) error{ - 200: successHandler, - }, - }, - } { - req, err := http.NewRequest("GET", tt.uri, nil) - if err != nil { - return nil, err - } - err = c.httpDo(ctx, req, func(res *http.Response, err error) error { - if err != nil { - return err - } - defer res.Body.Close() - if handler, ok := tt.handlers[res.StatusCode]; ok { - err1 := handler(res) - if err1 != nil { - return err1 - } - } - // no handler for this error code, proceed to the next connection type - return nil - }) - if state != nil || err != nil { - return state, err - } - } - return nil, errors.New("failed to sync with Mesos master") -} - -func parseMesosState(blob []byte) (*mesosState, error) { - type State struct { - ClusterName string `json:"cluster"` - Slaves []*struct { - Id string `json:"id"` // ex: 20150106-162714-3815890698-5050-2453-S2 - Pid string `json:"pid"` // ex: slave(1)@10.22.211.18:5051 - Hostname string `json:"hostname"` // ex: 10.22.211.18, or slave-123.nowhere.com - Resources map[string]interface{} `json:"resources"` // ex: {"mem": 123, "ports": "[31000-3200]"} - } `json:"slaves"` - Frameworks []*struct { - Id string `json:"id"` // ex: 20151105-093752-3745622208-5050-1-0000 - Pid string `json:"pid"` // ex: scheduler(1)@192.168.65.228:57124 - Executors []*struct { - SlaveId string `json:"slave_id"` // ex: 20151105-093752-3745622208-5050-1-S1 - ExecutorId string `json:"executor_id"` // ex: 6704d375c68fee1e_k8sm-executor - Name string `json:"name"` // ex: Kubelet-Executor - } `json:"executors"` - } `json:"frameworks"` - } - - state := &State{ClusterName: defaultClusterName} - if err := json.Unmarshal(blob, state); err != nil { - return nil, err - } - - executorSlaveIds := map[string]struct{}{} - for _, f := range state.Frameworks { - for _, e := range f.Executors { - // Note that this simple comparison breaks when we support more than one - // k8s instance in a cluster. At the moment this is not possible for - // a number of reasons. - // TODO(sttts): find way to detect executors of this k8s instance - if e.Name == KubernetesExecutorName { - executorSlaveIds[e.SlaveId] = struct{}{} - } - } - } - - nodes := map[string]*slaveNode{} // by hostname - for _, slave := range state.Slaves { - if slave.Hostname == "" { - continue - } - node := &slaveNode{hostname: slave.Hostname} - cap := api.ResourceList{} - if slave.Resources != nil && len(slave.Resources) > 0 { - // attempt to translate CPU (cores) and memory (MB) resources - if cpu, found := slave.Resources["cpus"]; found { - if cpuNum, ok := cpu.(float64); ok { - cap[api.ResourceCPU] = *resource.NewQuantity(int64(cpuNum), resource.DecimalSI) - } else { - log.Warningf("unexpected slave cpu resource type %T: %v", cpu, cpu) - } - } else { - log.Warningf("slave failed to report cpu resource") - } - if mem, found := slave.Resources["mem"]; found { - if memNum, ok := mem.(float64); ok { - cap[api.ResourceMemory] = *resource.NewQuantity(int64(memNum), resource.BinarySI) - } else { - log.Warningf("unexpected slave mem resource type %T: %v", mem, mem) - } - } else { - log.Warningf("slave failed to report mem resource") - } - } - if len(cap) > 0 { - node.resources = &api.NodeResources{ - Capacity: cap, - } - log.V(4).Infof("node %q reporting capacity %v", node.hostname, cap) - } - if _, ok := executorSlaveIds[slave.Id]; ok { - node.kubeletRunning = true - } - nodes[node.hostname] = node - } - - result := &mesosState{ - clusterName: state.ClusterName, - nodes: nodes, - } - - return result, nil -} - -type responseHandler func(*http.Response, error) error - -// httpDo executes an HTTP request in the given context, canceling an ongoing request if the context -// is canceled prior to completion of the request. hacked from https://blog.golang.org/context -func (c *mesosClient) httpDo(ctx context.Context, req *http.Request, f responseHandler) error { - // Run the HTTP request in a goroutine and pass the response to f. - ch := make(chan error, 1) - go func() { ch <- f(c.httpClient.Do(req)) }() - select { - case <-ctx.Done(): - c.tr.CancelRequest(req) - <-ch // Wait for f to return. - return ctx.Err() - case err := <-ch: - return err - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client_test.go deleted file mode 100644 index 83209924b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client_test.go +++ /dev/null @@ -1,271 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mesos - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "testing" - "time" - - log "github.com/golang/glog" - "github.com/mesos/mesos-go/detector" - "github.com/mesos/mesos-go/mesosutil" - "golang.org/x/net/context" -) - -// Test data - -const ( - TEST_MASTER_ID = "master-12345" - TEST_MASTER_IP = 177048842 // 10.141.141.10 - TEST_MASTER_PORT = 5050 - - TEST_STATE_JSON = ` - { - "version": "0.22.0", - "unregistered_frameworks": [], - "started_tasks": 0, - "start_time": 1429456501.61141, - "staged_tasks": 0, - "slaves": [ - { - "resources": { - "ports": "[31000-32000]", - "mem": 15360, - "disk": 470842, - "cpus": 8 - }, - "registered_time": 1429456502.46999, - "pid": "slave(1)@mesos1.internal.company.com:5050", - "id": "20150419-081501-16777343-5050-16383-S2", - "hostname": "mesos1.internal.company.com", - "attributes": {}, - "active": true - }, - { - "resources": { - "ports": "[31000-32000]", - "mem": 15360, - "disk": 470842, - "cpus": 8 - }, - "registered_time": 1429456502.4144, - "pid": "slave(1)@mesos2.internal.company.com:5050", - "id": "20150419-081501-16777343-5050-16383-S1", - "hostname": "mesos2.internal.company.com", - "attributes": {}, - "active": true - }, - { - "resources": { - "ports": "[31000-32000]", - "mem": 15360, - "disk": 470842, - "cpus": 8 - }, - "registered_time": 1429456502.02879, - "pid": "slave(1)@mesos3.internal.company.com:5050", - "id": "20150419-081501-16777343-5050-16383-S0", - "hostname": "mesos3.internal.company.com", - "attributes": {}, - "active": true - } - ], - "pid": "master@mesos-master0.internal.company.com:5050", - "orphan_tasks": [], - "lost_tasks": 0, - "leader": "master@mesos-master0.internal.company.com:5050", - "killed_tasks": 0, - "failed_tasks": 0, - "elected_time": 1429456501.61638, - "deactivated_slaves": 0, - "completed_frameworks": [], - "build_user": "buildbot", - "build_time": 1425085311, - "build_date": "2015-02-27 17:01:51", - "activated_slaves": 3, - "finished_tasks": 0, - "flags": { - "zk_session_timeout": "10secs", - "work_dir": "/somepath/mesos/local/Lc9arz", - "webui_dir": "/usr/local/share/mesos/webui", - "version": "false", - "user_sorter": "drf", - "slave_reregister_timeout": "10mins", - "logbufsecs": "0", - "log_auto_initialize": "true", - "initialize_driver_logging": "true", - "framework_sorter": "drf", - "authenticators": "crammd5", - "authenticate_slaves": "false", - "authenticate": "false", - "allocation_interval": "1secs", - "logging_level": "INFO", - "quiet": "false", - "recovery_slave_removal_limit": "100%", - "registry": "replicated_log", - "registry_fetch_timeout": "1mins", - "registry_store_timeout": "5secs", - "registry_strict": "false", - "root_submissions": "true" - }, - "frameworks": [], - "git_branch": "refs/heads/0.22.0-rc1", - "git_sha": "46834faca67f877631e1beb7d61be5c080ec3dc2", - "git_tag": "0.22.0-rc1", - "hostname": "localhost", - "id": "20150419-081501-16777343-5050-16383" - }` -) - -// Mocks - -type FakeMasterDetector struct { - callback detector.MasterChanged - done chan struct{} -} - -func newFakeMasterDetector() *FakeMasterDetector { - return &FakeMasterDetector{ - done: make(chan struct{}), - } -} - -func (md FakeMasterDetector) Cancel() { - close(md.done) -} - -func (md FakeMasterDetector) Detect(cb detector.MasterChanged) error { - md.callback = cb - leadingMaster := mesosutil.NewMasterInfo(TEST_MASTER_ID, TEST_MASTER_IP, TEST_MASTER_PORT) - cb.OnMasterChanged(leadingMaster) - return nil -} - -func (md FakeMasterDetector) Done() <-chan struct{} { - return md.done -} - -// Auxiliary functions - -func makeHttpMocks() (*httptest.Server, *http.Client, *http.Transport) { - httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.V(4).Infof("Mocking response for HTTP request: %#v", r) - if r.URL.Path == "/state.json" { - w.WriteHeader(200) // OK - w.Header().Set("Content-Type", "application/json") - fmt.Fprintln(w, TEST_STATE_JSON) - } else { - w.WriteHeader(400) - fmt.Fprintln(w, "Bad Request") - } - })) - - // Intercept all client requests and feed them to the test server - transport := &http.Transport{ - Proxy: func(req *http.Request) (*url.URL, error) { - return url.Parse(httpServer.URL) - }, - } - - httpClient := &http.Client{Transport: transport} - - return httpServer, httpClient, transport -} - -// Tests - -// test mesos.parseMesosState -func Test_parseMesosState(t *testing.T) { - state, err := parseMesosState([]byte(TEST_STATE_JSON)) - - if err != nil { - t.Fatalf("parseMesosState does not yield an error") - } - if state == nil { - t.Fatalf("parseMesosState yields a non-nil state") - } - if len(state.nodes) != 3 { - t.Fatalf("parseMesosState yields a state with 3 nodes") - } -} - -// test mesos.listSlaves -func Test_listSlaves(t *testing.T) { - defer log.Flush() - md := FakeMasterDetector{} - // TODO: Uncomment next two lines and remove third line when fix #19254 - // defer httpServer.Close() - // httpServer, httpClient, httpTransport := makeHttpMocks() - _, httpClient, httpTransport := makeHttpMocks() - - cacheTTL := 500 * time.Millisecond - mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL) - - if err != nil { - t.Fatalf("createMesosClient does not yield an error") - } - - slaveNodes, err := mesosClient.listSlaves(context.TODO()) - - if err != nil { - t.Fatalf("listSlaves does not yield an error") - } - if len(slaveNodes) != 3 { - t.Fatalf("listSlaves yields a collection of size 3") - } - - expectedHostnames := map[string]struct{}{ - "mesos1.internal.company.com": {}, - "mesos2.internal.company.com": {}, - "mesos3.internal.company.com": {}, - } - - actualHostnames := make(map[string]struct{}) - for _, node := range slaveNodes { - actualHostnames[node.hostname] = struct{}{} - } - - if !reflect.DeepEqual(expectedHostnames, actualHostnames) { - t.Fatalf("listSlaves yields a collection with the expected hostnames") - } -} - -// test mesos.clusterName -func Test_clusterName(t *testing.T) { - defer log.Flush() - md := FakeMasterDetector{} - // TODO: Uncomment next two lines and remove third line when fix #19254 - // defer httpServer.Close() - // httpServer, httpClient, httpTransport := makeHttpMocks() - _, httpClient, httpTransport := makeHttpMocks() - cacheTTL := 500 * time.Millisecond - mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL) - - name, err := mesosClient.clusterName(context.TODO()) - - if err != nil { - t.Fatalf("clusterName does not yield an error") - } - if name != defaultClusterName { - t.Fatalf("clusterName yields the expected (default) value") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config.go deleted file mode 100644 index c1be30e8b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mesos - -import ( - "io" - "time" - - "github.com/scalingdata/gcfg" -) - -const ( - DefaultMesosMaster = "localhost:5050" - DefaultHttpClientTimeout = time.Duration(10) * time.Second - DefaultStateCacheTTL = time.Duration(5) * time.Second -) - -// Example Mesos cloud provider configuration file: -// -// [mesos-cloud] -// mesos-master = leader.mesos:5050 -// http-client-timeout = 500ms -// state-cache-ttl = 1h - -type ConfigWrapper struct { - Mesos_Cloud Config -} - -type Config struct { - MesosMaster string `gcfg:"mesos-master"` - MesosHttpClientTimeout Duration `gcfg:"http-client-timeout"` - StateCacheTTL Duration `gcfg:"state-cache-ttl"` -} - -type Duration struct { - Duration time.Duration `gcfg:"duration"` -} - -func (d *Duration) UnmarshalText(data []byte) error { - underlying, err := time.ParseDuration(string(data)) - if err == nil { - d.Duration = underlying - } - return err -} - -func createDefaultConfig() *Config { - return &Config{ - MesosMaster: DefaultMesosMaster, - MesosHttpClientTimeout: Duration{Duration: DefaultHttpClientTimeout}, - StateCacheTTL: Duration{Duration: DefaultStateCacheTTL}, - } -} - -func readConfig(configReader io.Reader) (*Config, error) { - config := createDefaultConfig() - wrapper := &ConfigWrapper{Mesos_Cloud: *config} - if configReader != nil { - if err := gcfg.ReadInto(wrapper, configReader); err != nil { - return nil, err - } - config = &(wrapper.Mesos_Cloud) - } - return config, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config_test.go deleted file mode 100644 index d1013471c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mesos - -import ( - "bytes" - "testing" - "time" - - log "github.com/golang/glog" -) - -// test mesos.createDefaultConfig -func Test_createDefaultConfig(t *testing.T) { - defer log.Flush() - - config := createDefaultConfig() - - if config.MesosMaster != DefaultMesosMaster { - t.Fatalf("Default config has the expected MesosMaster value") - } - - if config.MesosHttpClientTimeout.Duration != DefaultHttpClientTimeout { - t.Fatalf("Default config has the expected MesosHttpClientTimeout value") - } - - if config.StateCacheTTL.Duration != DefaultStateCacheTTL { - t.Fatalf("Default config has the expected StateCacheTTL value") - } -} - -// test mesos.readConfig -func Test_readConfig(t *testing.T) { - defer log.Flush() - - configString := ` -[mesos-cloud] - mesos-master = leader.mesos:5050 - http-client-timeout = 500ms - state-cache-ttl = 1h` - - reader := bytes.NewBufferString(configString) - - config, err := readConfig(reader) - - if err != nil { - t.Fatalf("Reading configuration does not yield an error: %#v", err) - } - - if config.MesosMaster != "leader.mesos:5050" { - t.Fatalf("Parsed config has the expected MesosMaster value") - } - - if config.MesosHttpClientTimeout.Duration != time.Duration(500)*time.Millisecond { - t.Fatalf("Parsed config has the expected MesosHttpClientTimeout value") - } - - if config.StateCacheTTL.Duration != time.Duration(1)*time.Hour { - t.Fatalf("Parsed config has the expected StateCacheTTL value") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos.go deleted file mode 100644 index 20285843b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos.go +++ /dev/null @@ -1,283 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mesos - -import ( - "errors" - "fmt" - "io" - "net" - "regexp" - - log "github.com/golang/glog" - "github.com/mesos/mesos-go/detector" - "golang.org/x/net/context" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/cloudprovider" -) - -const ( - ProviderName = "mesos" - - // KubernetesExecutorName is shared between contrib/mesos and Mesos cloud provider. - // Because cloud provider -> contrib dependencies are forbidden, this constant - // is defined here, not in contrib. - KubernetesExecutorName = "Kubelet-Executor" -) - -var ( - CloudProvider *MesosCloud - - noHostNameSpecified = errors.New("No hostname specified") -) - -func init() { - cloudprovider.RegisterCloudProvider( - ProviderName, - func(configReader io.Reader) (cloudprovider.Interface, error) { - provider, err := newMesosCloud(configReader) - if err == nil { - CloudProvider = provider - } - return provider, err - }) -} - -type MesosCloud struct { - client *mesosClient - config *Config -} - -func (c *MesosCloud) MasterURI() string { - return c.config.MesosMaster -} - -func newMesosCloud(configReader io.Reader) (*MesosCloud, error) { - config, err := readConfig(configReader) - if err != nil { - return nil, err - } - - log.V(1).Infof("new mesos cloud, master='%v'", config.MesosMaster) - if d, err := detector.New(config.MesosMaster); err != nil { - log.V(1).Infof("failed to create master detector: %v", err) - return nil, err - } else if cl, err := newMesosClient(d, - config.MesosHttpClientTimeout.Duration, - config.StateCacheTTL.Duration); err != nil { - log.V(1).Infof("failed to create mesos cloud client: %v", err) - return nil, err - } else { - return &MesosCloud{client: cl, config: config}, nil - } -} - -// Implementation of Instances.CurrentNodeName -func (c *MesosCloud) CurrentNodeName(hostname string) (string, error) { - return hostname, nil -} - -func (c *MesosCloud) AddSSHKeyToAllInstances(user string, keyData []byte) error { - return errors.New("unimplemented") -} - -// Instances returns a copy of the Mesos cloud Instances implementation. -// Mesos natively provides minimal cloud-type resources. More robust cloud -// support requires a combination of Mesos and cloud-specific knowledge. -func (c *MesosCloud) Instances() (cloudprovider.Instances, bool) { - return c, true -} - -// LoadBalancer always returns nil, false in this implementation. -// Mesos does not provide any type of native load balancing by default, -// so this implementation always returns (nil, false). -func (c *MesosCloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) { - return nil, false -} - -// Zones always returns nil, false in this implementation. -// Mesos does not provide any type of native region or zone awareness, -// so this implementation always returns (nil, false). -func (c *MesosCloud) Zones() (cloudprovider.Zones, bool) { - return nil, false -} - -// Clusters returns a copy of the Mesos cloud Clusters implementation. -// Mesos does not provide support for multiple clusters. -func (c *MesosCloud) Clusters() (cloudprovider.Clusters, bool) { - return c, true -} - -// Routes always returns nil, false in this implementation. -func (c *MesosCloud) Routes() (cloudprovider.Routes, bool) { - return nil, false -} - -// ProviderName returns the cloud provider ID. -func (c *MesosCloud) ProviderName() string { - return ProviderName -} - -// ScrubDNS filters DNS settings for pods. -func (c *MesosCloud) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) { - return nameservers, searches -} - -// ListClusters lists the names of the available Mesos clusters. -func (c *MesosCloud) ListClusters() ([]string, error) { - // Always returns a single cluster (this one!) - ctx, cancel := context.WithCancel(context.TODO()) - defer cancel() - name, err := c.client.clusterName(ctx) - return []string{name}, err -} - -// Master gets back the address (either DNS name or IP address) of the leading Mesos master node for the cluster. -func (c *MesosCloud) Master(clusterName string) (string, error) { - clusters, err := c.ListClusters() - if err != nil { - return "", err - } - for _, name := range clusters { - if name == clusterName { - if c.client.master == "" { - return "", errors.New("The currently leading master is unknown.") - } - - host, _, err := net.SplitHostPort(c.client.master) - if err != nil { - return "", err - } - - return host, nil - } - } - return "", errors.New(fmt.Sprintf("The supplied cluster '%v' does not exist", clusterName)) -} - -// ipAddress returns an IP address of the specified instance. -func ipAddress(name string) (net.IP, error) { - if name == "" { - return nil, noHostNameSpecified - } - ipaddr := net.ParseIP(name) - if ipaddr != nil { - return ipaddr, nil - } - iplist, err := net.LookupIP(name) - if err != nil { - log.V(2).Infof("failed to resolve IP from host name '%v': %v", name, err) - return nil, err - } - ipaddr = iplist[0] - log.V(2).Infof("resolved host '%v' to '%v'", name, ipaddr) - return ipaddr, nil -} - -// ExternalID returns the cloud provider ID of the specified instance (deprecated). -func (c *MesosCloud) ExternalID(instance string) (string, error) { - //TODO(jdef) use a timeout here? 15s? - ctx, cancel := context.WithCancel(context.TODO()) - defer cancel() - - nodes, err := c.client.listSlaves(ctx) - if err != nil { - return "", err - } - - node := nodes[instance] - if node == nil { - return "", cloudprovider.InstanceNotFound - } - - ip, err := ipAddress(node.hostname) - if err != nil { - return "", err - } - return ip.String(), nil -} - -// InstanceID returns the cloud provider ID of the specified instance. -func (c *MesosCloud) InstanceID(name string) (string, error) { - return "", nil -} - -// InstanceType returns the type of the specified instance. -func (c *MesosCloud) InstanceType(name string) (string, error) { - return "", nil -} - -func (c *MesosCloud) listNodes() (map[string]*slaveNode, error) { - //TODO(jdef) use a timeout here? 15s? - ctx, cancel := context.WithCancel(context.TODO()) - defer cancel() - - nodes, err := c.client.listSlaves(ctx) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - log.V(2).Info("no slaves found, are any running?") - return nil, nil - } - return nodes, nil -} - -// List lists instances that match 'filter' which is a regular expression -// which must match the entire instance name (fqdn). -func (c *MesosCloud) List(filter string) ([]string, error) { - nodes, err := c.listNodes() - if err != nil { - return nil, err - } - filterRegex, err := regexp.Compile(filter) - if err != nil { - return nil, err - } - addr := []string{} - for _, node := range nodes { - if filterRegex.MatchString(node.hostname) { - addr = append(addr, node.hostname) - } - } - return addr, nil -} - -// ListWithKubelet list those instance which have no running kubelet, i.e. the -// Kubernetes executor. -func (c *MesosCloud) ListWithoutKubelet() ([]string, error) { - nodes, err := c.listNodes() - if err != nil { - return nil, err - } - addr := make([]string, 0, len(nodes)) - for _, n := range nodes { - if !n.kubeletRunning { - addr = append(addr, n.hostname) - } - } - return addr, nil -} - -// NodeAddresses returns the addresses of the specified instance. -func (c *MesosCloud) NodeAddresses(name string) ([]api.NodeAddress, error) { - ip, err := ipAddress(name) - if err != nil { - return nil, err - } - return []api.NodeAddress{{Type: api.NodeLegacyHostIP, Address: ip.String()}}, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos_test.go deleted file mode 100644 index b504f4ef0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos_test.go +++ /dev/null @@ -1,279 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mesos - -import ( - "bytes" - "net" - "reflect" - "testing" - "time" - - log "github.com/golang/glog" - "k8s.io/kubernetes/pkg/cloudprovider" -) - -func TestIPAddress(t *testing.T) { - expected4 := net.IPv4(127, 0, 0, 1) - ip, err := ipAddress("127.0.0.1") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !reflect.DeepEqual(ip, expected4) { - t.Fatalf("expected %#v instead of %#v", expected4, ip) - } - - expected6 := net.ParseIP("::1") - if expected6 == nil { - t.Fatalf("failed to parse ipv6 ::1") - } - ip, err = ipAddress("::1") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !reflect.DeepEqual(ip, expected6) { - t.Fatalf("expected %#v instead of %#v", expected6, ip) - } - - ip, err = ipAddress("localhost") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !reflect.DeepEqual(ip, expected4) && !reflect.DeepEqual(ip, expected6) { - t.Fatalf("expected %#v or %#v instead of %#v", expected4, expected6, ip) - } - - _, err = ipAddress("") - if err != noHostNameSpecified { - t.Fatalf("expected error noHostNameSpecified but got none") - } -} - -// test mesos.newMesosCloud with no config -func Test_newMesosCloud_NoConfig(t *testing.T) { - defer log.Flush() - mesosCloud, err := newMesosCloud(nil) - - if err != nil { - t.Fatalf("Creating a new Mesos cloud provider without config does not yield an error: %#v", err) - } - - if mesosCloud.client.httpClient.Timeout != DefaultHttpClientTimeout { - t.Fatalf("Creating a new Mesos cloud provider without config does not yield an error: %#v", err) - } - - if mesosCloud.client.state.ttl != DefaultStateCacheTTL { - t.Fatalf("Mesos client with default config has the expected state cache TTL value") - } -} - -// test mesos.newMesosCloud with custom config -func Test_newMesosCloud_WithConfig(t *testing.T) { - defer log.Flush() - - configString := ` -[mesos-cloud] - http-client-timeout = 500ms - state-cache-ttl = 1h` - - reader := bytes.NewBufferString(configString) - - mesosCloud, err := newMesosCloud(reader) - - if err != nil { - t.Fatalf("Creating a new Mesos cloud provider with a custom config does not yield an error: %#v", err) - } - - if mesosCloud.client.httpClient.Timeout != time.Duration(500)*time.Millisecond { - t.Fatalf("Mesos client with a custom config has the expected HTTP client timeout value") - } - - if mesosCloud.client.state.ttl != time.Duration(1)*time.Hour { - t.Fatalf("Mesos client with a custom config has the expected state cache TTL value") - } -} - -// tests for capability reporting functions - -// test mesos.Instances -func Test_Instances(t *testing.T) { - defer log.Flush() - mesosCloud, _ := newMesosCloud(nil) - - instances, supports_instances := mesosCloud.Instances() - - if !supports_instances || instances == nil { - t.Fatalf("MesosCloud provides an implementation of Instances") - } -} - -// test mesos.LoadBalancer -func Test_TcpLoadBalancer(t *testing.T) { - defer log.Flush() - mesosCloud, _ := newMesosCloud(nil) - - lb, supports_lb := mesosCloud.LoadBalancer() - - if supports_lb || lb != nil { - t.Fatalf("MesosCloud does not provide an implementation of LoadBalancer") - } -} - -// test mesos.Zones -func Test_Zones(t *testing.T) { - defer log.Flush() - mesosCloud, _ := newMesosCloud(nil) - - zones, supports_zones := mesosCloud.Zones() - - if supports_zones || zones != nil { - t.Fatalf("MesosCloud does not provide an implementation of Zones") - } -} - -// test mesos.Clusters -func Test_Clusters(t *testing.T) { - defer log.Flush() - mesosCloud, _ := newMesosCloud(nil) - - clusters, supports_clusters := mesosCloud.Clusters() - - if !supports_clusters || clusters == nil { - t.Fatalf("MesosCloud does not provide an implementation of Clusters") - } -} - -// test mesos.MasterURI -func Test_MasterURI(t *testing.T) { - defer log.Flush() - mesosCloud, _ := newMesosCloud(nil) - - uri := mesosCloud.MasterURI() - - if uri != DefaultMesosMaster { - t.Fatalf("MasterURI returns the expected master URI (expected \"localhost\", actual \"%s\"", uri) - } -} - -// test mesos.ListClusters -func Test_ListClusters(t *testing.T) { - defer log.Flush() - md := FakeMasterDetector{} - httpServer, httpClient, httpTransport := makeHttpMocks() - defer httpServer.Close() - cacheTTL := 500 * time.Millisecond - mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL) - mesosCloud := &MesosCloud{client: mesosClient, config: createDefaultConfig()} - - clusters, err := mesosCloud.ListClusters() - - if err != nil { - t.Fatalf("ListClusters does not yield an error: %#v", err) - } - - if len(clusters) != 1 { - t.Fatalf("ListClusters should return a list of size 1: (actual: %#v)", clusters) - } - - expectedClusterNames := []string{"mesos"} - - if !reflect.DeepEqual(clusters, expectedClusterNames) { - t.Fatalf("ListClusters should return the expected list of names: (expected: %#v, actual: %#v)", - expectedClusterNames, - clusters) - } -} - -// test mesos.Master -func Test_Master(t *testing.T) { - defer log.Flush() - md := FakeMasterDetector{} - httpServer, httpClient, httpTransport := makeHttpMocks() - defer httpServer.Close() - cacheTTL := 500 * time.Millisecond - mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL) - mesosCloud := &MesosCloud{client: mesosClient, config: createDefaultConfig()} - - clusters, err := mesosCloud.ListClusters() - clusterName := clusters[0] - master, err := mesosCloud.Master(clusterName) - - if err != nil { - t.Fatalf("Master does not yield an error: %#v", err) - } - - expectedMaster := unpackIPv4(TEST_MASTER_IP) - - if master != expectedMaster { - t.Fatalf("Master returns the expected value: (expected: %#v, actual: %#v", expectedMaster, master) - } -} - -// test mesos.List -func Test_List(t *testing.T) { - defer log.Flush() - md := FakeMasterDetector{} - httpServer, httpClient, httpTransport := makeHttpMocks() - defer httpServer.Close() - cacheTTL := 500 * time.Millisecond - mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL) - mesosCloud := &MesosCloud{client: mesosClient, config: createDefaultConfig()} - - clusters, err := mesosCloud.List(".*") // recognizes the language of all strings - - if err != nil { - t.Fatalf("List does not yield an error: %#v", err) - } - - if len(clusters) != 3 { - t.Fatalf("List with a catch-all filter should return a list of size 3: (actual: %#v)", clusters) - } - - clusters, err = mesosCloud.List("$^") // end-of-string followed by start-of-string: recognizes the empty language - - if err != nil { - t.Fatalf("List does not yield an error: %#v", err) - } - - if len(clusters) != 0 { - t.Fatalf("List with a reject-all filter should return a list of size 0: (actual: %#v)", clusters) - } -} - -func Test_ExternalID(t *testing.T) { - defer log.Flush() - md := FakeMasterDetector{} - httpServer, httpClient, httpTransport := makeHttpMocks() - defer httpServer.Close() - cacheTTL := 500 * time.Millisecond - mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL) - mesosCloud := &MesosCloud{client: mesosClient, config: createDefaultConfig()} - - _, err = mesosCloud.ExternalID("unknown") - if err != cloudprovider.InstanceNotFound { - t.Fatalf("ExternalID did not return InstanceNotFound on an unknown instance") - } - - slaveName := "mesos3.internal.company.com" - id, err := mesosCloud.ExternalID(slaveName) - if id != "" { - t.Fatalf("ExternalID should not be able to resolve %q", slaveName) - } - if err == cloudprovider.InstanceNotFound { - t.Fatalf("ExternalID should find %q", slaveName) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/plugins.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/plugins.go deleted file mode 100644 index 2baf7b47f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/plugins.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mesos - -import ( - _ "github.com/mesos/mesos-go/detector/zoo" -) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/MAINTAINERS.md b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/MAINTAINERS.md deleted file mode 100644 index f71afec99..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/MAINTAINERS.md +++ /dev/null @@ -1,6 +0,0 @@ -# Maintainers - -* [Angus Lees](https://github.com/anguslees) - - -[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/pkg/cloudprovider/providers/openstack/MAINTAINERS.md?pixel)]() diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack.go deleted file mode 100644 index 2a9376c2b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack.go +++ /dev/null @@ -1,1087 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package openstack - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "regexp" - "strings" - "time" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" - "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach" - "github.com/rackspace/gophercloud/openstack/compute/v2/flavors" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips" - "github.com/rackspace/gophercloud/pagination" - "github.com/scalingdata/gcfg" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/cloudprovider" - "k8s.io/kubernetes/pkg/types" -) - -const ProviderName = "openstack" - -// metadataUrl is URL to OpenStack metadata server. It's hadrcoded 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 -const metadataUrl = "http://169.254.169.254/openstack/2012-08-10/meta_data.json" - -var ErrNotFound = errors.New("Failed to find object") -var ErrMultipleResults = errors.New("Multiple results where only one expected") -var ErrNoAddressFound = errors.New("No address found for host") -var ErrAttrNotFound = errors.New("Expected attribute not found") - -const ( - MiB = 1024 * 1024 - GB = 1000 * 1000 * 1000 -) - -// encoding.TextUnmarshaler interface for time.Duration -type MyDuration struct { - time.Duration -} - -func (d *MyDuration) UnmarshalText(text []byte) error { - res, err := time.ParseDuration(string(text)) - if err != nil { - return err - } - d.Duration = res - return nil -} - -type LoadBalancerOpts struct { - SubnetId string `gcfg:"subnet-id"` // required - FloatingNetworkId string `gcfg:"floating-network-id"` - LBMethod string `gfcg:"lb-method"` - CreateMonitor bool `gcfg:"create-monitor"` - MonitorDelay MyDuration `gcfg:"monitor-delay"` - MonitorTimeout MyDuration `gcfg:"monitor-timeout"` - MonitorMaxRetries uint `gcfg:"monitor-max-retries"` -} - -// OpenStack is an implementation of cloud provider Interface for OpenStack. -type OpenStack struct { - provider *gophercloud.ProviderClient - region string - lbOpts LoadBalancerOpts - // InstanceID of the server where this OpenStack object is instantiated. - localInstanceID string -} - -type Config struct { - Global struct { - AuthUrl string `gcfg:"auth-url"` - Username string - UserId string `gcfg:"user-id"` - Password string - ApiKey string `gcfg:"api-key"` - TenantId string `gcfg:"tenant-id"` - TenantName string `gcfg:"tenant-name"` - DomainId string `gcfg:"domain-id"` - DomainName string `gcfg:"domain-name"` - Region string - } - LoadBalancer LoadBalancerOpts -} - -func init() { - cloudprovider.RegisterCloudProvider(ProviderName, func(config io.Reader) (cloudprovider.Interface, error) { - cfg, err := readConfig(config) - if err != nil { - return nil, err - } - return newOpenStack(cfg) - }) -} - -func (cfg Config) toAuthOptions() gophercloud.AuthOptions { - return gophercloud.AuthOptions{ - IdentityEndpoint: cfg.Global.AuthUrl, - Username: cfg.Global.Username, - UserID: cfg.Global.UserId, - Password: cfg.Global.Password, - APIKey: cfg.Global.ApiKey, - TenantID: cfg.Global.TenantId, - TenantName: cfg.Global.TenantName, - DomainID: cfg.Global.DomainId, - DomainName: cfg.Global.DomainName, - - // Persistent service, so we need to be able to renew tokens. - AllowReauth: true, - } -} - -func readConfig(config io.Reader) (Config, error) { - if config == nil { - err := fmt.Errorf("no OpenStack cloud provider config file given") - return Config{}, err - } - - var cfg Config - err := gcfg.ReadInto(&cfg, config) - return cfg, err -} - -// parseMetadataUUID reads JSON from OpenStack metadata server and parses -// instance ID out of it. -func parseMetadataUUID(jsonData []byte) (string, error) { - // We should receive an object with { 'uuid': '' } and couple of other - // properties (which we ignore). - - obj := struct{ UUID string }{} - err := json.Unmarshal(jsonData, &obj) - if err != nil { - return "", err - } - - uuid := obj.UUID - if uuid == "" { - err = fmt.Errorf("cannot parse OpenStack metadata, got empty uuid") - return "", err - } - - return uuid, nil -} - -func readInstanceID() (string, error) { - // Try to find instance ID on the local filesystem (created by cloud-init) - const instanceIDFile = "/var/lib/cloud/data/instance-id" - idBytes, err := ioutil.ReadFile(instanceIDFile) - if err == nil { - instanceID := string(idBytes) - instanceID = strings.TrimSpace(instanceID) - glog.V(3).Infof("Got instance id from %s: %s", instanceIDFile, instanceID) - if instanceID != "" { - return instanceID, nil - } - // Fall through with empty instanceID and try metadata server. - } - glog.V(5).Infof("Cannot read %s: '%v', trying metadata server", instanceIDFile, err) - - // Try to get JSON from metdata server. - resp, err := http.Get(metadataUrl) - if err != nil { - glog.V(3).Infof("Cannot read %s: %v", metadataUrl, err) - return "", err - } - - if resp.StatusCode != 200 { - err = fmt.Errorf("got unexpected status code when reading metadata from %s: %s", metadataUrl, resp.Status) - glog.V(3).Infof("%v", err) - return "", err - } - - defer resp.Body.Close() - bodyBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - glog.V(3).Infof("Cannot get HTTP response body from %s: %v", metadataUrl, err) - return "", err - } - instanceID, err := parseMetadataUUID(bodyBytes) - if err != nil { - glog.V(3).Infof("Cannot parse instance ID from metadata from %s: %v", metadataUrl, err) - return "", err - } - - glog.V(3).Infof("Got instance id from %s: %s", metadataUrl, instanceID) - return instanceID, nil -} - -func newOpenStack(cfg Config) (*OpenStack, error) { - provider, err := openstack.AuthenticatedClient(cfg.toAuthOptions()) - if err != nil { - return nil, err - } - - id, err := readInstanceID() - if err != nil { - return nil, err - } - - os := OpenStack{ - provider: provider, - region: cfg.Global.Region, - lbOpts: cfg.LoadBalancer, - localInstanceID: id, - } - - return &os, nil -} - -type Instances struct { - compute *gophercloud.ServiceClient - flavor_to_resource map[string]*api.NodeResources // keyed by flavor id -} - -// Instances returns an implementation of Instances for OpenStack. -func (os *OpenStack) Instances() (cloudprovider.Instances, bool) { - glog.V(4).Info("openstack.Instances() called") - - compute, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - if err != nil { - glog.Warningf("Failed to find compute endpoint: %v", err) - return nil, false - } - - pager := flavors.ListDetail(compute, nil) - - flavor_to_resource := make(map[string]*api.NodeResources) - err = pager.EachPage(func(page pagination.Page) (bool, error) { - flavorList, err := flavors.ExtractFlavors(page) - if err != nil { - return false, err - } - for _, flavor := range flavorList { - rsrc := api.NodeResources{ - Capacity: api.ResourceList{ - api.ResourceCPU: *resource.NewQuantity(int64(flavor.VCPUs), resource.DecimalSI), - api.ResourceMemory: *resource.NewQuantity(int64(flavor.RAM)*MiB, resource.BinarySI), - "openstack.org/disk": *resource.NewQuantity(int64(flavor.Disk)*GB, resource.DecimalSI), - "openstack.org/rxTxFactor": *resource.NewMilliQuantity(int64(flavor.RxTxFactor)*1000, resource.DecimalSI), - "openstack.org/swap": *resource.NewQuantity(int64(flavor.Swap)*MiB, resource.BinarySI), - }, - } - flavor_to_resource[flavor.ID] = &rsrc - } - return true, nil - }) - if err != nil { - glog.Warningf("Failed to find compute flavors: %v", err) - return nil, false - } - - glog.V(3).Infof("Found %v compute flavors", len(flavor_to_resource)) - glog.V(1).Info("Claiming to support Instances") - - return &Instances{compute, flavor_to_resource}, true -} - -func (i *Instances) List(name_filter string) ([]string, error) { - glog.V(4).Infof("openstack List(%v) called", name_filter) - - opts := servers.ListOpts{ - Name: name_filter, - Status: "ACTIVE", - } - pager := servers.List(i.compute, opts) - - ret := make([]string, 0) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - sList, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - for _, server := range sList { - ret = append(ret, server.Name) - } - return true, nil - }) - if err != nil { - return nil, err - } - - glog.V(3).Infof("Found %v instances matching %v: %v", - len(ret), name_filter, ret) - - return ret, nil -} - -func getServerByName(client *gophercloud.ServiceClient, name string) (*servers.Server, error) { - opts := servers.ListOpts{ - Name: fmt.Sprintf("^%s$", regexp.QuoteMeta(name)), - Status: "ACTIVE", - } - pager := servers.List(client, opts) - - serverList := make([]servers.Server, 0, 1) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - s, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - serverList = append(serverList, s...) - if len(serverList) > 1 { - return false, ErrMultipleResults - } - return true, nil - }) - if err != nil { - return nil, err - } - - if len(serverList) == 0 { - return nil, ErrNotFound - } else if len(serverList) > 1 { - return nil, ErrMultipleResults - } - - return &serverList[0], nil -} - -func getAddressesByName(client *gophercloud.ServiceClient, name string) ([]api.NodeAddress, error) { - srv, err := getServerByName(client, name) - if err != nil { - return nil, err - } - - addrs := []api.NodeAddress{} - - for network, netblob := range srv.Addresses { - list, ok := netblob.([]interface{}) - if !ok { - continue - } - - for _, item := range list { - var addressType api.NodeAddressType - - props, ok := item.(map[string]interface{}) - if !ok { - continue - } - - extIPType, ok := props["OS-EXT-IPS:type"] - if (ok && extIPType == "floating") || (!ok && network == "public") { - addressType = api.NodeExternalIP - } else { - addressType = api.NodeInternalIP - } - - tmp, ok := props["addr"] - if !ok { - continue - } - addr, ok := tmp.(string) - if !ok { - continue - } - - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ - Type: addressType, - Address: addr, - }, - ) - } - } - - // AccessIPs are usually duplicates of "public" addresses. - if srv.AccessIPv4 != "" { - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ - Type: api.NodeExternalIP, - Address: srv.AccessIPv4, - }, - ) - } - - if srv.AccessIPv6 != "" { - api.AddToNodeAddresses(&addrs, - api.NodeAddress{ - Type: api.NodeExternalIP, - Address: srv.AccessIPv6, - }, - ) - } - - return addrs, nil -} - -func getAddressByName(client *gophercloud.ServiceClient, name string) (string, error) { - addrs, err := getAddressesByName(client, name) - if err != nil { - return "", err - } else if len(addrs) == 0 { - return "", ErrNoAddressFound - } - - for _, addr := range addrs { - if addr.Type == api.NodeInternalIP { - return addr.Address, nil - } - } - - return addrs[0].Address, nil -} - -// Implementation of Instances.CurrentNodeName -func (i *Instances) CurrentNodeName(hostname string) (string, error) { - return hostname, nil -} - -func (i *Instances) AddSSHKeyToAllInstances(user string, keyData []byte) error { - return errors.New("unimplemented") -} - -func (i *Instances) NodeAddresses(name string) ([]api.NodeAddress, error) { - glog.V(4).Infof("NodeAddresses(%v) called", name) - - addrs, err := getAddressesByName(i.compute, name) - if err != nil { - return nil, err - } - - glog.V(4).Infof("NodeAddresses(%v) => %v", name, addrs) - return addrs, nil -} - -// ExternalID returns the cloud provider ID of the specified instance (deprecated). -func (i *Instances) ExternalID(name string) (string, error) { - srv, err := getServerByName(i.compute, name) - if err != nil { - return "", err - } - return srv.ID, nil -} - -// InstanceID returns the cloud provider ID of the specified instance. -func (i *Instances) InstanceID(name string) (string, error) { - srv, err := getServerByName(i.compute, name) - if err != nil { - return "", err - } - // In the future it is possible to also return an endpoint as: - // / - return "/" + srv.ID, nil -} - -// InstanceType returns the type of the specified instance. -func (i *Instances) InstanceType(name string) (string, error) { - return "", nil -} - -func (os *OpenStack) Clusters() (cloudprovider.Clusters, bool) { - return nil, false -} - -// ProviderName returns the cloud provider ID. -func (os *OpenStack) ProviderName() string { - return ProviderName -} - -// ScrubDNS filters DNS settings for pods. -func (os *OpenStack) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) { - return nameservers, searches -} - -type LoadBalancer struct { - network *gophercloud.ServiceClient - compute *gophercloud.ServiceClient - opts LoadBalancerOpts -} - -func (os *OpenStack) LoadBalancer() (cloudprovider.LoadBalancer, bool) { - glog.V(4).Info("openstack.LoadBalancer() called") - - // TODO: Search for and support Rackspace loadbalancer API, and others. - network, err := openstack.NewNetworkV2(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - if err != nil { - glog.Warningf("Failed to find neutron endpoint: %v", err) - return nil, false - } - - compute, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - if err != nil { - glog.Warningf("Failed to find compute endpoint: %v", err) - return nil, false - } - - glog.V(1).Info("Claiming to support LoadBalancer") - - return &LoadBalancer{network, compute, os.lbOpts}, true -} - -func isNotFound(err error) bool { - e, ok := err.(*gophercloud.UnexpectedResponseCodeError) - return ok && e.Actual == http.StatusNotFound -} - -func getPoolByName(client *gophercloud.ServiceClient, name string) (*pools.Pool, error) { - opts := pools.ListOpts{ - Name: name, - } - pager := pools.List(client, opts) - - poolList := make([]pools.Pool, 0, 1) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - p, err := pools.ExtractPools(page) - if err != nil { - return false, err - } - poolList = append(poolList, p...) - if len(poolList) > 1 { - return false, ErrMultipleResults - } - return true, nil - }) - if err != nil { - if isNotFound(err) { - return nil, ErrNotFound - } - return nil, err - } - - if len(poolList) == 0 { - return nil, ErrNotFound - } else if len(poolList) > 1 { - return nil, ErrMultipleResults - } - - return &poolList[0], nil -} - -func getVipByName(client *gophercloud.ServiceClient, name string) (*vips.VirtualIP, error) { - opts := vips.ListOpts{ - Name: name, - } - pager := vips.List(client, opts) - - vipList := make([]vips.VirtualIP, 0, 1) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - v, err := vips.ExtractVIPs(page) - if err != nil { - return false, err - } - vipList = append(vipList, v...) - if len(vipList) > 1 { - return false, ErrMultipleResults - } - return true, nil - }) - if err != nil { - if isNotFound(err) { - return nil, ErrNotFound - } - return nil, err - } - - if len(vipList) == 0 { - return nil, ErrNotFound - } else if len(vipList) > 1 { - return nil, ErrMultipleResults - } - - return &vipList[0], nil -} - -func getFloatingIPByPortID(client *gophercloud.ServiceClient, portID string) (*floatingips.FloatingIP, error) { - opts := floatingips.ListOpts{ - PortID: portID, - } - pager := floatingips.List(client, opts) - - floatingIPList := make([]floatingips.FloatingIP, 0, 1) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - f, err := floatingips.ExtractFloatingIPs(page) - if err != nil { - return false, err - } - floatingIPList = append(floatingIPList, f...) - if len(floatingIPList) > 1 { - return false, ErrMultipleResults - } - return true, nil - }) - if err != nil { - if isNotFound(err) { - return nil, ErrNotFound - } - return nil, err - } - - if len(floatingIPList) == 0 { - return nil, ErrNotFound - } else if len(floatingIPList) > 1 { - return nil, ErrMultipleResults - } - - return &floatingIPList[0], nil -} - -func (lb *LoadBalancer) GetLoadBalancer(name, region string) (*api.LoadBalancerStatus, bool, error) { - vip, err := getVipByName(lb.network, name) - if err == ErrNotFound { - return nil, false, nil - } - if vip == nil { - return nil, false, err - } - - status := &api.LoadBalancerStatus{} - status.Ingress = []api.LoadBalancerIngress{{IP: vip.Address}} - - return status, true, err -} - -// TODO: This code currently ignores 'region' and always creates a -// loadbalancer in only the current OpenStack region. We should take -// a list of regions (from config) and query/create loadbalancers in -// each region. - -func (lb *LoadBalancer) EnsureLoadBalancer(name, region string, loadBalancerIP net.IP, ports []*api.ServicePort, hosts []string, serviceName types.NamespacedName, affinity api.ServiceAffinity) (*api.LoadBalancerStatus, error) { - glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", name, region, loadBalancerIP, ports, hosts, serviceName) - - if len(ports) > 1 { - return nil, fmt.Errorf("multiple ports are not yet supported in openstack load balancers") - } else if len(ports) == 0 { - return nil, fmt.Errorf("no ports provided to openstack load balancer") - } - - // The service controller verified all the protocols match on the ports, just check and use the first one - // TODO: Convert all error messages to use an event recorder - if ports[0].Protocol != api.ProtocolTCP { - return nil, fmt.Errorf("Only TCP LoadBalancer is supported for openstack load balancers") - } - - var persistence *vips.SessionPersistence - switch affinity { - case api.ServiceAffinityNone: - persistence = nil - case api.ServiceAffinityClientIP: - persistence = &vips.SessionPersistence{Type: "SOURCE_IP"} - default: - return nil, fmt.Errorf("unsupported load balancer affinity: %v", affinity) - } - - glog.V(2).Infof("Checking if openstack load balancer already exists: %s", name) - _, exists, err := lb.GetLoadBalancer(name, region) - if err != nil { - return nil, fmt.Errorf("error checking if openstack load balancer already exists: %v", err) - } - - // 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(name, region) - if err != nil { - return nil, fmt.Errorf("error deleting existing openstack load balancer: %v", err) - } - } - - lbmethod := lb.opts.LBMethod - if lbmethod == "" { - lbmethod = pools.LBMethodRoundRobin - } - pool, err := pools.Create(lb.network, pools.CreateOpts{ - Name: name, - Protocol: pools.ProtocolTCP, - SubnetID: lb.opts.SubnetId, - LBMethod: lbmethod, - }).Extract() - if err != nil { - return nil, err - } - - for _, host := range hosts { - addr, err := getAddressByName(lb.compute, host) - if err != nil { - return nil, err - } - - _, err = members.Create(lb.network, members.CreateOpts{ - PoolID: pool.ID, - ProtocolPort: ports[0].NodePort, //TODO: need to handle multi-port - Address: addr, - }).Extract() - if err != nil { - pools.Delete(lb.network, pool.ID) - return nil, err - } - } - - var mon *monitors.Monitor - if lb.opts.CreateMonitor { - mon, err = monitors.Create(lb.network, monitors.CreateOpts{ - Type: monitors.TypeTCP, - Delay: int(lb.opts.MonitorDelay.Duration.Seconds()), - Timeout: int(lb.opts.MonitorTimeout.Duration.Seconds()), - MaxRetries: int(lb.opts.MonitorMaxRetries), - }).Extract() - if err != nil { - pools.Delete(lb.network, pool.ID) - return nil, err - } - - _, err = pools.AssociateMonitor(lb.network, pool.ID, mon.ID).Extract() - if err != nil { - monitors.Delete(lb.network, mon.ID) - pools.Delete(lb.network, pool.ID) - return nil, err - } - } - - createOpts := vips.CreateOpts{ - Name: name, - Description: fmt.Sprintf("Kubernetes external service %s", name), - Protocol: "TCP", - ProtocolPort: ports[0].Port, //TODO: need to handle multi-port - PoolID: pool.ID, - SubnetID: lb.opts.SubnetId, - Persistence: persistence, - } - if loadBalancerIP != nil { - createOpts.Address = loadBalancerIP.String() - } - - vip, err := vips.Create(lb.network, createOpts).Extract() - if err != nil { - if mon != nil { - monitors.Delete(lb.network, mon.ID) - } - pools.Delete(lb.network, pool.ID) - return nil, err - } - - status := &api.LoadBalancerStatus{} - - status.Ingress = []api.LoadBalancerIngress{{IP: vip.Address}} - - if lb.opts.FloatingNetworkId != "" { - floatIPOpts := floatingips.CreateOpts{ - FloatingNetworkID: lb.opts.FloatingNetworkId, - PortID: vip.PortID, - } - floatIP, err := floatingips.Create(lb.network, floatIPOpts).Extract() - if err != nil { - return nil, err - } - - status.Ingress = append(status.Ingress, api.LoadBalancerIngress{IP: floatIP.FloatingIP}) - } - - return status, nil - -} - -func (lb *LoadBalancer) UpdateLoadBalancer(name, region string, hosts []string) error { - glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", name, region, hosts) - - vip, err := getVipByName(lb.network, name) - if err != nil { - return err - } - - // Set of member (addresses) that _should_ exist - addrs := map[string]bool{} - for _, host := range hosts { - addr, err := getAddressByName(lb.compute, host) - if err != nil { - return err - } - - addrs[addr] = true - } - - // Iterate over members that _do_ exist - pager := members.List(lb.network, members.ListOpts{PoolID: vip.PoolID}) - err = pager.EachPage(func(page pagination.Page) (bool, error) { - memList, err := members.ExtractMembers(page) - if err != nil { - return false, err - } - - for _, member := range memList { - if _, found := addrs[member.Address]; found { - // Member already exists - delete(addrs, member.Address) - } else { - // Member needs to be deleted - err = members.Delete(lb.network, member.ID).ExtractErr() - if err != nil { - return false, err - } - } - } - - return true, nil - }) - if err != nil { - return err - } - - // Anything left in addrs is a new member that needs to be added - for addr := range addrs { - _, err := members.Create(lb.network, members.CreateOpts{ - PoolID: vip.PoolID, - Address: addr, - ProtocolPort: vip.ProtocolPort, - }).Extract() - if err != nil { - return err - } - } - - return nil -} - -func (lb *LoadBalancer) EnsureLoadBalancerDeleted(name, region string) error { - glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", name, region) - - vip, err := getVipByName(lb.network, name) - if err != nil && err != ErrNotFound { - return err - } - - if lb.opts.FloatingNetworkId != "" && vip != nil { - floatingIP, err := getFloatingIPByPortID(lb.network, vip.PortID) - if err != nil && !isNotFound(err) { - return err - } - if floatingIP != nil { - err = floatingips.Delete(lb.network, floatingIP.ID).ExtractErr() - if err != nil && !isNotFound(err) { - return err - } - } - } - - // We have to delete the VIP before the pool can be deleted, - // so no point continuing if this fails. - if vip != nil { - err := vips.Delete(lb.network, vip.ID).ExtractErr() - if err != nil && !isNotFound(err) { - return err - } - } - - var pool *pools.Pool - if vip != nil { - pool, err = pools.Get(lb.network, vip.PoolID).Extract() - if err != nil && !isNotFound(err) { - return err - } - } else { - // The VIP is gone, but it is conceivable that a Pool - // still exists that we failed to delete on some - // previous occasion. Make a best effort attempt to - // cleanup any pools with the same name as the VIP. - pool, err = getPoolByName(lb.network, name) - if err != nil && err != ErrNotFound { - return err - } - } - - if pool != nil { - for _, monId := range pool.MonitorIDs { - _, err = pools.DisassociateMonitor(lb.network, pool.ID, monId).Extract() - if err != nil { - return err - } - - err = monitors.Delete(lb.network, monId).ExtractErr() - if err != nil && !isNotFound(err) { - return err - } - } - err = pools.Delete(lb.network, pool.ID).ExtractErr() - if err != nil && !isNotFound(err) { - return err - } - } - - return nil -} - -func (os *OpenStack) Zones() (cloudprovider.Zones, bool) { - glog.V(1).Info("Claiming to support Zones") - - return os, true -} -func (os *OpenStack) GetZone() (cloudprovider.Zone, error) { - glog.V(1).Infof("Current zone is %v", os.region) - - return cloudprovider.Zone{Region: os.region}, nil -} - -func (os *OpenStack) Routes() (cloudprovider.Routes, bool) { - return nil, false -} - -// Attaches given cinder volume to the compute running kubelet -func (os *OpenStack) AttachDisk(diskName string) (string, error) { - disk, err := os.getVolume(diskName) - if err != nil { - return "", err - } - cClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - if err != nil || cClient == nil { - glog.Errorf("Unable to initialize nova client for region: %s", os.region) - return "", err - } - - if len(disk.Attachments) > 0 && disk.Attachments[0]["server_id"] != nil { - if os.localInstanceID == disk.Attachments[0]["server_id"] { - glog.V(4).Infof("Disk: %q is already attached to compute: %q", diskName, os.localInstanceID) - return disk.ID, nil - } else { - errMsg := fmt.Sprintf("Disk %q is attached to a different compute: %q, should be detached before proceeding", diskName, disk.Attachments[0]["server_id"]) - glog.Errorf(errMsg) - return "", errors.New(errMsg) - } - } - // add read only flag here if possible spothanis - _, err = volumeattach.Create(cClient, os.localInstanceID, &volumeattach.CreateOpts{ - VolumeID: disk.ID, - }).Extract() - if err != nil { - glog.Errorf("Failed to attach %s volume to %s compute", diskName, os.localInstanceID) - return "", err - } - glog.V(2).Infof("Successfully attached %s volume to %s compute", diskName, os.localInstanceID) - return disk.ID, nil -} - -// Detaches given cinder volume from the compute running kubelet -func (os *OpenStack) DetachDisk(partialDiskId string) error { - disk, err := os.getVolume(partialDiskId) - if err != nil { - return err - } - cClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - if err != nil || cClient == nil { - glog.Errorf("Unable to initialize nova client for region: %s", os.region) - return err - } - if len(disk.Attachments) > 0 && disk.Attachments[0]["server_id"] != nil && os.localInstanceID == disk.Attachments[0]["server_id"] { - // This is a blocking call and effects kubelet's performance directly. - // We should consider kicking it out into a separate routine, if it is bad. - err = volumeattach.Delete(cClient, os.localInstanceID, disk.ID).ExtractErr() - if err != nil { - glog.Errorf("Failed to delete volume %s from compute %s attached %v", disk.ID, os.localInstanceID, err) - return err - } - glog.V(2).Infof("Successfully detached volume: %s from compute: %s", disk.ID, os.localInstanceID) - } else { - errMsg := fmt.Sprintf("Disk: %s has no attachments or is not attached to compute: %s", disk.Name, os.localInstanceID) - glog.Errorf(errMsg) - return errors.New(errMsg) - } - return nil -} - -// Takes a partial/full disk id or diskname -func (os *OpenStack) getVolume(diskName string) (volumes.Volume, error) { - sClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - - var volume volumes.Volume - if err != nil || sClient == nil { - glog.Errorf("Unable to initialize cinder client for region: %s", os.region) - return volume, err - } - - err = volumes.List(sClient, nil).EachPage(func(page pagination.Page) (bool, error) { - vols, err := volumes.ExtractVolumes(page) - if err != nil { - glog.Errorf("Failed to extract volumes: %v", err) - return false, err - } else { - for _, v := range vols { - glog.V(4).Infof("%s %s %v", v.ID, v.Name, v.Attachments) - if v.Name == diskName || strings.Contains(v.ID, diskName) { - volume = v - return true, nil - } - } - } - // if it reached here then no disk with the given name was found. - errmsg := fmt.Sprintf("Unable to find disk: %s in region %s", diskName, os.region) - return false, errors.New(errmsg) - }) - if err != nil { - glog.Errorf("Error occured getting volume: %s", diskName) - return volume, err - } - return volume, err -} - -// Create a volume of given size (in GiB) -func (os *OpenStack) CreateVolume(name string, size int, tags *map[string]string) (volumeName string, err error) { - - sClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - - if err != nil || sClient == nil { - glog.Errorf("Unable to initialize cinder client for region: %s", os.region) - return "", err - } - - opts := volumes.CreateOpts{ - Name: name, - Size: size, - } - if tags != nil { - opts.Metadata = *tags - } - vol, err := volumes.Create(sClient, opts).Extract() - if err != nil { - glog.Errorf("Failed to create a %d GB volume: %v", size, err) - return "", err - } - glog.Infof("Created volume %v", vol.ID) - return vol.ID, err -} - -func (os *OpenStack) DeleteVolume(volumeName string) error { - sClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - - if err != nil || sClient == nil { - glog.Errorf("Unable to initialize cinder client for region: %s", os.region) - return err - } - err = volumes.Delete(sClient, volumeName).ExtractErr() - if err != nil { - glog.Errorf("Cannot delete volume %s: %v", volumeName, err) - } - return err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack_test.go deleted file mode 100644 index a4db2fafb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack_test.go +++ /dev/null @@ -1,228 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package openstack - -import ( - "os" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/util/rand" - - "github.com/rackspace/gophercloud" -) - -func TestReadConfig(t *testing.T) { - _, err := readConfig(nil) - if err == nil { - t.Errorf("Should fail when no config is provided: %s", err) - } - - cfg, err := readConfig(strings.NewReader(` -[Global] -auth-url = http://auth.url -username = user -[LoadBalancer] -create-monitor = yes -monitor-delay = 1m -monitor-timeout = 30s -monitor-max-retries = 3 -`)) - if err != nil { - t.Fatalf("Should succeed when a valid config is provided: %s", err) - } - if cfg.Global.AuthUrl != "http://auth.url" { - t.Errorf("incorrect authurl: %s", cfg.Global.AuthUrl) - } - - if !cfg.LoadBalancer.CreateMonitor { - t.Errorf("incorrect lb.createmonitor: %t", cfg.LoadBalancer.CreateMonitor) - } - if cfg.LoadBalancer.MonitorDelay.Duration != 1*time.Minute { - t.Errorf("incorrect lb.monitordelay: %s", cfg.LoadBalancer.MonitorDelay) - } - if cfg.LoadBalancer.MonitorTimeout.Duration != 30*time.Second { - t.Errorf("incorrect lb.monitortimeout: %s", cfg.LoadBalancer.MonitorTimeout) - } - if cfg.LoadBalancer.MonitorMaxRetries != 3 { - t.Errorf("incorrect lb.monitormaxretries: %d", cfg.LoadBalancer.MonitorMaxRetries) - } -} - -func TestToAuthOptions(t *testing.T) { - cfg := Config{} - cfg.Global.Username = "user" - // etc. - - ao := cfg.toAuthOptions() - - if !ao.AllowReauth { - t.Errorf("Will need to be able to reauthenticate") - } - if ao.Username != cfg.Global.Username { - t.Errorf("Username %s != %s", ao.Username, cfg.Global.Username) - } -} - -// This allows acceptance testing against an existing OpenStack -// install, using the standard OS_* OpenStack client environment -// variables. -// FIXME: it would be better to hermetically test against canned JSON -// requests/responses. -func configFromEnv() (cfg Config, ok bool) { - cfg.Global.AuthUrl = os.Getenv("OS_AUTH_URL") - - cfg.Global.TenantId = os.Getenv("OS_TENANT_ID") - // Rax/nova _insists_ that we don't specify both tenant ID and name - if cfg.Global.TenantId == "" { - cfg.Global.TenantName = os.Getenv("OS_TENANT_NAME") - } - - cfg.Global.Username = os.Getenv("OS_USERNAME") - cfg.Global.Password = os.Getenv("OS_PASSWORD") - cfg.Global.ApiKey = os.Getenv("OS_API_KEY") - cfg.Global.Region = os.Getenv("OS_REGION_NAME") - cfg.Global.DomainId = os.Getenv("OS_DOMAIN_ID") - cfg.Global.DomainName = os.Getenv("OS_DOMAIN_NAME") - - ok = (cfg.Global.AuthUrl != "" && - cfg.Global.Username != "" && - (cfg.Global.Password != "" || cfg.Global.ApiKey != "") && - (cfg.Global.TenantId != "" || cfg.Global.TenantName != "" || - cfg.Global.DomainId != "" || cfg.Global.DomainName != "")) - - return -} - -func TestNewOpenStack(t *testing.T) { - cfg, ok := configFromEnv() - if !ok { - t.Skipf("No config found in environment") - } - - _, err := newOpenStack(cfg) - if err != nil { - t.Fatalf("Failed to construct/authenticate OpenStack: %s", err) - } -} - -func TestInstances(t *testing.T) { - cfg, ok := configFromEnv() - if !ok { - t.Skipf("No config found in environment") - } - - os, err := newOpenStack(cfg) - if err != nil { - t.Fatalf("Failed to construct/authenticate OpenStack: %s", err) - } - - i, ok := os.Instances() - if !ok { - t.Fatalf("Instances() returned false") - } - - srvs, err := i.List(".") - if err != nil { - t.Fatalf("Instances.List() failed: %s", err) - } - if len(srvs) == 0 { - t.Fatalf("Instances.List() returned zero servers") - } - t.Logf("Found servers (%d): %s\n", len(srvs), srvs) - - addrs, err := i.NodeAddresses(srvs[0]) - if err != nil { - t.Fatalf("Instances.NodeAddresses(%s) failed: %s", srvs[0], err) - } - t.Logf("Found NodeAddresses(%s) = %s\n", srvs[0], addrs) -} - -func TestLoadBalancer(t *testing.T) { - cfg, ok := configFromEnv() - if !ok { - t.Skipf("No config found in environment") - } - - os, err := newOpenStack(cfg) - if err != nil { - t.Fatalf("Failed to construct/authenticate OpenStack: %s", err) - } - - lb, ok := os.LoadBalancer() - if !ok { - t.Fatalf("LoadBalancer() returned false - perhaps your stack doesn't support Neutron?") - } - - _, exists, err := lb.GetLoadBalancer("noexist", "region") - if err != nil { - t.Fatalf("GetLoadBalancer(\"noexist\") returned error: %s", err) - } - if exists { - t.Fatalf("GetLoadBalancer(\"noexist\") returned exists") - } -} - -func TestZones(t *testing.T) { - os := OpenStack{ - provider: &gophercloud.ProviderClient{ - IdentityBase: "http://auth.url/", - }, - region: "myRegion", - } - - z, ok := os.Zones() - if !ok { - t.Fatalf("Zones() returned false") - } - - zone, err := z.GetZone() - if err != nil { - t.Fatalf("GetZone() returned error: %s", err) - } - - if zone.Region != "myRegion" { - t.Fatalf("GetZone() returned wrong region (%s)", zone.Region) - } -} - -func TestVolumes(t *testing.T) { - cfg, ok := configFromEnv() - if !ok { - t.Skipf("No config found in environment") - } - - os, err := newOpenStack(cfg) - if err != nil { - t.Fatalf("Failed to construct/authenticate OpenStack: %s", err) - } - - tags := map[string]string{ - "test": "value", - } - vol, err := os.CreateVolume("kubernetes-test-volume-"+rand.String(10), 1, &tags) - if err != nil { - t.Fatalf("Cannot create a new Cinder volume: %v", err) - } - - err = os.DeleteVolume(vol) - if err != nil { - t.Fatalf("Cannot delete Cinder volume %s: %v", vol, err) - } - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt.go deleted file mode 100644 index 24b47c852..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt.go +++ /dev/null @@ -1,291 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package ovirt - -import ( - "encoding/xml" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "path" - "sort" - "strings" - - "github.com/scalingdata/gcfg" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/cloudprovider" -) - -const ProviderName = "ovirt" - -type OVirtInstance struct { - UUID string - Name string - IPAddress string -} - -type OVirtInstanceMap map[string]OVirtInstance - -type OVirtCloud struct { - VmsRequest *url.URL - HostsRequest *url.URL -} - -type OVirtApiConfig struct { - Connection struct { - ApiEntry string `gcfg:"uri"` - Username string `gcfg:"username"` - Password string `gcfg:"password"` - } - Filters struct { - VmsQuery string `gcfg:"vms"` - } -} - -type XmlVmAddress struct { - Address string `xml:"address,attr"` -} - -type XmlVmInfo struct { - UUID string `xml:"id,attr"` - Name string `xml:"name"` - Hostname string `xml:"guest_info>fqdn"` - Addresses []XmlVmAddress `xml:"guest_info>ips>ip"` - State string `xml:"status>state"` -} - -type XmlVmsList struct { - XMLName xml.Name `xml:"vms"` - Vm []XmlVmInfo `xml:"vm"` -} - -func init() { - cloudprovider.RegisterCloudProvider(ProviderName, - func(config io.Reader) (cloudprovider.Interface, error) { - return newOVirtCloud(config) - }) -} - -func newOVirtCloud(config io.Reader) (*OVirtCloud, error) { - if config == nil { - return nil, fmt.Errorf("missing configuration file for ovirt cloud provider") - } - - oVirtConfig := OVirtApiConfig{} - - /* defaults */ - oVirtConfig.Connection.Username = "admin@internal" - - if err := gcfg.ReadInto(&oVirtConfig, config); err != nil { - return nil, err - } - - if oVirtConfig.Connection.ApiEntry == "" { - return nil, fmt.Errorf("missing ovirt uri in cloud provider configuration") - } - - request, err := url.Parse(oVirtConfig.Connection.ApiEntry) - if err != nil { - return nil, err - } - - request.Path = path.Join(request.Path, "vms") - request.User = url.UserPassword(oVirtConfig.Connection.Username, oVirtConfig.Connection.Password) - request.RawQuery = url.Values{"search": {oVirtConfig.Filters.VmsQuery}}.Encode() - - return &OVirtCloud{VmsRequest: request}, nil -} - -func (aws *OVirtCloud) Clusters() (cloudprovider.Clusters, bool) { - return nil, false -} - -// ProviderName returns the cloud provider ID. -func (v *OVirtCloud) ProviderName() string { - return ProviderName -} - -// ScrubDNS filters DNS settings for pods. -func (v *OVirtCloud) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) { - return nameservers, searches -} - -// LoadBalancer returns an implementation of LoadBalancer for oVirt cloud -func (v *OVirtCloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) { - return nil, false -} - -// Instances returns an implementation of Instances for oVirt cloud -func (v *OVirtCloud) Instances() (cloudprovider.Instances, bool) { - return v, true -} - -// Zones returns an implementation of Zones for oVirt cloud -func (v *OVirtCloud) Zones() (cloudprovider.Zones, bool) { - return nil, false -} - -// Routes returns an implementation of Routes for oVirt cloud -func (v *OVirtCloud) Routes() (cloudprovider.Routes, bool) { - return nil, false -} - -// NodeAddresses returns the NodeAddresses of a particular machine instance -func (v *OVirtCloud) NodeAddresses(name string) ([]api.NodeAddress, error) { - instance, err := v.fetchInstance(name) - if err != nil { - return nil, err - } - - var address net.IP - - if instance.IPAddress != "" { - address = net.ParseIP(instance.IPAddress) - if address == nil { - return nil, fmt.Errorf("couldn't parse address: %s", instance.IPAddress) - } - } else { - resolved, err := net.LookupIP(name) - if err != nil || len(resolved) < 1 { - return nil, fmt.Errorf("couldn't lookup address: %s", name) - } - address = resolved[0] - } - - return []api.NodeAddress{{Type: api.NodeLegacyHostIP, Address: address.String()}}, nil -} - -// ExternalID returns the cloud provider ID of the specified instance (deprecated). -func (v *OVirtCloud) ExternalID(name string) (string, error) { - instance, err := v.fetchInstance(name) - if err != nil { - return "", err - } - return instance.UUID, nil -} - -// InstanceID returns the cloud provider ID of the specified instance. -func (v *OVirtCloud) InstanceID(name string) (string, error) { - instance, err := v.fetchInstance(name) - if err != nil { - return "", err - } - // TODO: define a way to identify the provider instance to complete - // the format /. - return "/" + instance.UUID, err -} - -// InstanceType returns the type of the specified instance. -func (v *OVirtCloud) InstanceType(name string) (string, error) { - return "", nil -} - -func getInstancesFromXml(body io.Reader) (OVirtInstanceMap, error) { - if body == nil { - return nil, fmt.Errorf("ovirt rest-api response body is missing") - } - - content, err := ioutil.ReadAll(body) - if err != nil { - return nil, err - } - - vmlist := XmlVmsList{} - - if err := xml.Unmarshal(content, &vmlist); err != nil { - return nil, err - } - - instances := make(OVirtInstanceMap) - - for _, vm := range vmlist.Vm { - // Always return only vms that are up and running - if vm.Hostname != "" && strings.ToLower(vm.State) == "up" { - address := "" - if len(vm.Addresses) > 0 { - address = vm.Addresses[0].Address - } - - instances[vm.Hostname] = OVirtInstance{ - UUID: vm.UUID, - Name: vm.Name, - IPAddress: address, - } - } - } - - return instances, nil -} - -func (v *OVirtCloud) fetchAllInstances() (OVirtInstanceMap, error) { - response, err := http.Get(v.VmsRequest.String()) - if err != nil { - return nil, err - } - - defer response.Body.Close() - - return getInstancesFromXml(response.Body) -} - -func (v *OVirtCloud) fetchInstance(name string) (*OVirtInstance, error) { - allInstances, err := v.fetchAllInstances() - if err != nil { - return nil, err - } - - instance, found := allInstances[name] - if !found { - return nil, fmt.Errorf("cannot find instance: %s", name) - } - - return &instance, nil -} - -func (m *OVirtInstanceMap) ListSortedNames() []string { - var names []string - - for k := range *m { - names = append(names, k) - } - - sort.Strings(names) - - return names -} - -// List enumerates the set of minions instances known by the cloud provider -func (v *OVirtCloud) List(filter string) ([]string, error) { - instances, err := v.fetchAllInstances() - if err != nil { - return nil, err - } - return instances.ListSortedNames(), nil -} - -// Implementation of Instances.CurrentNodeName -func (v *OVirtCloud) CurrentNodeName(hostname string) (string, error) { - return hostname, nil -} - -func (v *OVirtCloud) AddSSHKeyToAllInstances(user string, keyData []byte) error { - return errors.New("unimplemented") -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt_test.go deleted file mode 100644 index c76bde726..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt_test.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package ovirt - -import ( - "io" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/cloudprovider" -) - -func TestOVirtCloudConfiguration(t *testing.T) { - config1 := (io.Reader)(nil) - - _, err1 := cloudprovider.GetCloudProvider("ovirt", config1) - if err1 == nil { - t.Fatalf("An error is expected when the configuration is missing") - } - - config2 := strings.NewReader("") - - _, err2 := cloudprovider.GetCloudProvider("ovirt", config2) - if err2 == nil { - t.Fatalf("An error is expected when the configuration is empty") - } - - config3 := strings.NewReader(` -[connection] - `) - - _, err3 := cloudprovider.GetCloudProvider("ovirt", config3) - if err3 == nil { - t.Fatalf("An error is expected when the uri is missing") - } - - config4 := strings.NewReader(` -[connection] -uri = https://localhost:8443/ovirt-engine/api -`) - - _, err4 := cloudprovider.GetCloudProvider("ovirt", config4) - if err4 != nil { - t.Fatalf("Unexpected error creating the provider: %s", err4) - } -} - -func TestOVirtCloudXmlParsing(t *testing.T) { - body1 := (io.Reader)(nil) - - _, err1 := getInstancesFromXml(body1) - if err1 == nil { - t.Fatalf("An error is expected when body is missing") - } - - body2 := strings.NewReader("") - - _, err2 := getInstancesFromXml(body2) - if err2 == nil { - t.Fatalf("An error is expected when body is empty") - } - - body3 := strings.NewReader(` - - - -`) - - instances3, err3 := getInstancesFromXml(body3) - if err3 != nil { - t.Fatalf("Unexpected error listing instances: %s", err3) - } - if len(instances3) > 0 { - t.Fatalf("Unexpected number of instance(s): %d", len(instances3)) - } - - body4 := strings.NewReader(` - - - Up - host1 - - - - - - Up - - - Down - host2 - - - Up - host3 - - -`) - - instances4, err4 := getInstancesFromXml(body4) - if err4 != nil { - t.Fatalf("Unexpected error listing instances: %s", err4) - } - if len(instances4) != 2 { - t.Fatalf("Unexpected number of instance(s): %d", len(instances4)) - } - - names := instances4.ListSortedNames() - if names[0] != "host1" || names[1] != "host3" { - t.Fatalf("Unexpected instance(s): %s", instances4) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/providers.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/providers.go deleted file mode 100644 index 6664e8903..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/providers.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cloudprovider - -import ( - // Cloud providers - _ "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" - _ "k8s.io/kubernetes/pkg/cloudprovider/providers/gce" - _ "k8s.io/kubernetes/pkg/cloudprovider/providers/mesos" - _ "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack" - _ "k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt" - _ "k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace" -) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/MAINTAINERS.md b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/MAINTAINERS.md deleted file mode 100644 index 4c72c1a0a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/MAINTAINERS.md +++ /dev/null @@ -1,6 +0,0 @@ -# Maintainers - -* [Thom May](https://github.com/thommay) - - -[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/pkg/cloudprovider/providers/rackspace/MAINTAINERS.md?pixel)]() diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace.go deleted file mode 100644 index fbc0d7bff..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace.go +++ /dev/null @@ -1,393 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package rackspace - -import ( - "errors" - "fmt" - "io" - "net" - "regexp" - "time" - - "github.com/rackspace/gophercloud" - osservers "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace" - "github.com/rackspace/gophercloud/rackspace/compute/v2/servers" - "github.com/scalingdata/gcfg" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/cloudprovider" -) - -const ProviderName = "rackspace" - -var ErrNotFound = errors.New("Failed to find object") -var ErrMultipleResults = errors.New("Multiple results where only one expected") -var ErrNoAddressFound = errors.New("No address found for host") -var ErrAttrNotFound = errors.New("Expected attribute not found") - -// encoding.TextUnmarshaler interface for time.Duration -type MyDuration struct { - time.Duration -} - -func (d *MyDuration) UnmarshalText(text []byte) error { - res, err := time.ParseDuration(string(text)) - if err != nil { - return err - } - d.Duration = res - return nil -} - -type LoadBalancerOpts struct { - SubnetId string `gcfg:"subnet-id"` // required - CreateMonitor bool `gcfg:"create-monitor"` - MonitorDelay MyDuration `gcfg:"monitor-delay"` - MonitorTimeout MyDuration `gcfg:"monitor-timeout"` - MonitorMaxRetries uint `gcfg:"monitor-max-retries"` -} - -// Rackspace is an implementation of cloud provider Interface for Rackspace. -type Rackspace struct { - provider *gophercloud.ProviderClient - region string - lbOpts LoadBalancerOpts -} - -type Config struct { - Global struct { - AuthUrl string `gcfg:"auth-url"` - Username string - UserId string `gcfg:"user-id"` - Password string - ApiKey string `gcfg:"api-key"` - TenantId string `gcfg:"tenant-id"` - TenantName string `gcfg:"tenant-name"` - DomainId string `gcfg:"domain-id"` - DomainName string `gcfg:"domain-name"` - Region string - } - LoadBalancer LoadBalancerOpts -} - -func init() { - cloudprovider.RegisterCloudProvider(ProviderName, func(config io.Reader) (cloudprovider.Interface, error) { - cfg, err := readConfig(config) - if err != nil { - return nil, err - } - return newRackspace(cfg) - }) -} - -func (cfg Config) toAuthOptions() gophercloud.AuthOptions { - return gophercloud.AuthOptions{ - IdentityEndpoint: cfg.Global.AuthUrl, - Username: cfg.Global.Username, - UserID: cfg.Global.UserId, - Password: cfg.Global.Password, - APIKey: cfg.Global.ApiKey, - TenantID: cfg.Global.TenantId, - TenantName: cfg.Global.TenantName, - - // Persistent service, so we need to be able to renew tokens - AllowReauth: true, - } -} - -func readConfig(config io.Reader) (Config, error) { - if config == nil { - err := fmt.Errorf("no Rackspace cloud provider config file given") - return Config{}, err - } - - var cfg Config - err := gcfg.ReadInto(&cfg, config) - return cfg, err -} - -func newRackspace(cfg Config) (*Rackspace, error) { - provider, err := rackspace.AuthenticatedClient(cfg.toAuthOptions()) - if err != nil { - return nil, err - } - - os := Rackspace{ - provider: provider, - region: cfg.Global.Region, - lbOpts: cfg.LoadBalancer, - } - return &os, nil -} - -type Instances struct { - compute *gophercloud.ServiceClient -} - -// Instances returns an implementation of Instances for Rackspace. -func (os *Rackspace) Instances() (cloudprovider.Instances, bool) { - glog.V(2).Info("rackspace.Instances() called") - - compute, err := rackspace.NewComputeV2(os.provider, gophercloud.EndpointOpts{ - Region: os.region, - }) - if err != nil { - glog.Warningf("Failed to find compute endpoint: %v", err) - return nil, false - } - glog.V(1).Info("Claiming to support Instances") - - return &Instances{compute}, true -} - -func (i *Instances) List(name_filter string) ([]string, error) { - glog.V(2).Infof("rackspace List(%v) called", name_filter) - - opts := osservers.ListOpts{ - Name: name_filter, - Status: "ACTIVE", - } - pager := servers.List(i.compute, opts) - - ret := make([]string, 0) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - sList, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - for _, server := range sList { - ret = append(ret, server.Name) - } - return true, nil - }) - if err != nil { - return nil, err - } - - glog.V(2).Infof("Found %v entries: %v", len(ret), ret) - - return ret, nil -} - -func serverHasAddress(srv osservers.Server, ip string) bool { - if ip == firstAddr(srv.Addresses["private"]) { - return true - } - if ip == firstAddr(srv.Addresses["public"]) { - return true - } - if ip == srv.AccessIPv4 { - return true - } - if ip == srv.AccessIPv6 { - return true - } - return false -} - -func getServerByAddress(client *gophercloud.ServiceClient, name string) (*osservers.Server, error) { - pager := servers.List(client, nil) - - serverList := make([]osservers.Server, 0, 1) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - s, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - for _, v := range s { - if serverHasAddress(v, name) { - serverList = append(serverList, v) - } - } - if len(serverList) > 1 { - return false, ErrMultipleResults - } - return true, nil - }) - if err != nil { - return nil, err - } - - if len(serverList) == 0 { - return nil, ErrNotFound - } else if len(serverList) > 1 { - return nil, ErrMultipleResults - } - - return &serverList[0], nil -} - -func getServerByName(client *gophercloud.ServiceClient, name string) (*osservers.Server, error) { - if net.ParseIP(name) != nil { - // we're an IP, so we'll have to walk the full list of servers to - // figure out which one we are. - return getServerByAddress(client, name) - } - opts := osservers.ListOpts{ - Name: fmt.Sprintf("^%s$", regexp.QuoteMeta(name)), - Status: "ACTIVE", - } - pager := servers.List(client, opts) - - serverList := make([]osservers.Server, 0, 1) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - s, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - serverList = append(serverList, s...) - if len(serverList) > 1 { - return false, ErrMultipleResults - } - return true, nil - }) - if err != nil { - return nil, err - } - - if len(serverList) == 0 { - return nil, ErrNotFound - } else if len(serverList) > 1 { - return nil, ErrMultipleResults - } - - return &serverList[0], nil -} - -func firstAddr(netblob interface{}) string { - // Run-time types for the win :( - list, ok := netblob.([]interface{}) - if !ok || len(list) < 1 { - return "" - } - props, ok := list[0].(map[string]interface{}) - if !ok { - return "" - } - tmp, ok := props["addr"] - if !ok { - return "" - } - addr, ok := tmp.(string) - if !ok { - return "" - } - return addr -} - -func getAddressByName(api *gophercloud.ServiceClient, name string) (string, error) { - srv, err := getServerByName(api, name) - if err != nil { - return "", err - } - - var s string - if s == "" { - s = firstAddr(srv.Addresses["private"]) - } - if s == "" { - s = firstAddr(srv.Addresses["public"]) - } - if s == "" { - s = srv.AccessIPv4 - } - if s == "" { - s = srv.AccessIPv6 - } - if s == "" { - return "", ErrNoAddressFound - } - return s, nil -} - -func (i *Instances) NodeAddresses(name string) ([]api.NodeAddress, error) { - glog.V(2).Infof("NodeAddresses(%v) called", name) - - ip, err := getAddressByName(i.compute, name) - if err != nil { - return nil, err - } - - glog.V(2).Infof("NodeAddresses(%v) => %v", name, ip) - - // net.ParseIP().String() is to maintain compatibility with the old code - return []api.NodeAddress{{Type: api.NodeLegacyHostIP, Address: net.ParseIP(ip).String()}}, nil -} - -// ExternalID returns the cloud provider ID of the specified instance (deprecated). -func (i *Instances) ExternalID(name string) (string, error) { - return "", fmt.Errorf("unimplemented") -} - -// InstanceID returns the cloud provider ID of the specified instance. -func (i *Instances) InstanceID(name string) (string, error) { - return "", nil -} - -// InstanceType returns the type of the specified instance. -func (i *Instances) InstanceType(name string) (string, error) { - return "", nil -} - -func (i *Instances) AddSSHKeyToAllInstances(user string, keyData []byte) error { - return errors.New("unimplemented") -} - -// Implementation of Instances.CurrentNodeName -func (i *Instances) CurrentNodeName(hostname string) (string, error) { - return hostname, nil -} - -func (os *Rackspace) Clusters() (cloudprovider.Clusters, bool) { - return nil, false -} - -// ProviderName returns the cloud provider ID. -func (os *Rackspace) ProviderName() string { - return ProviderName -} - -// ScrubDNS filters DNS settings for pods. -func (os *Rackspace) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) { - return nameservers, searches -} - -func (os *Rackspace) LoadBalancer() (cloudprovider.LoadBalancer, bool) { - return nil, false -} - -func (os *Rackspace) Zones() (cloudprovider.Zones, bool) { - glog.V(1).Info("Claiming to support Zones") - - return os, true -} - -func (os *Rackspace) Routes() (cloudprovider.Routes, bool) { - return nil, false -} - -func (os *Rackspace) GetZone() (cloudprovider.Zone, error) { - glog.V(1).Infof("Current zone is %v", os.region) - - return cloudprovider.Zone{Region: os.region}, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace_test.go deleted file mode 100644 index bc3738310..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace_test.go +++ /dev/null @@ -1,175 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package rackspace - -import ( - "os" - "strings" - "testing" - "time" - - "github.com/rackspace/gophercloud" -) - -func TestReadConfig(t *testing.T) { - _, err := readConfig(nil) - if err == nil { - t.Errorf("Should fail when no config is provided: %s", err) - } - - cfg, err := readConfig(strings.NewReader(` -[Global] -auth-url = http://auth.url -username = user -[LoadBalancer] -create-monitor = yes -monitor-delay = 1m -monitor-timeout = 30s -monitor-max-retries = 3 -`)) - if err != nil { - t.Fatalf("Should succeed when a valid config is provided: %s", err) - } - if cfg.Global.AuthUrl != "http://auth.url" { - t.Errorf("incorrect authurl: %s", cfg.Global.AuthUrl) - } - - if !cfg.LoadBalancer.CreateMonitor { - t.Errorf("incorrect lb.createmonitor: %t", cfg.LoadBalancer.CreateMonitor) - } - if cfg.LoadBalancer.MonitorDelay.Duration != 1*time.Minute { - t.Errorf("incorrect lb.monitordelay: %s", cfg.LoadBalancer.MonitorDelay) - } - if cfg.LoadBalancer.MonitorTimeout.Duration != 30*time.Second { - t.Errorf("incorrect lb.monitortimeout: %s", cfg.LoadBalancer.MonitorTimeout) - } - if cfg.LoadBalancer.MonitorMaxRetries != 3 { - t.Errorf("incorrect lb.monitormaxretries: %d", cfg.LoadBalancer.MonitorMaxRetries) - } -} - -func TestToAuthOptions(t *testing.T) { - cfg := Config{} - cfg.Global.Username = "user" - // etc. - - ao := cfg.toAuthOptions() - - if !ao.AllowReauth { - t.Errorf("Will need to be able to reauthenticate") - } - if ao.Username != cfg.Global.Username { - t.Errorf("Username %s != %s", ao.Username, cfg.Global.Username) - } -} - -// This allows acceptance testing against an existing Rackspace -// install, using the standard OS_* Rackspace client environment -// variables. -// FIXME: it would be better to hermetically test against canned JSON -// requests/responses. -func configFromEnv() (cfg Config, ok bool) { - cfg.Global.AuthUrl = os.Getenv("OS_AUTH_URL") - - cfg.Global.TenantId = os.Getenv("OS_TENANT_ID") - // Rax/nova _insists_ that we don't specify both tenant ID and name - if cfg.Global.TenantId == "" { - cfg.Global.TenantName = os.Getenv("OS_TENANT_NAME") - } - - cfg.Global.Username = os.Getenv("OS_USERNAME") - cfg.Global.Password = os.Getenv("OS_PASSWORD") - cfg.Global.ApiKey = os.Getenv("OS_API_KEY") - cfg.Global.Region = os.Getenv("OS_REGION_NAME") - cfg.Global.DomainId = os.Getenv("OS_DOMAIN_ID") - cfg.Global.DomainName = os.Getenv("OS_DOMAIN_NAME") - - ok = (cfg.Global.AuthUrl != "" && - cfg.Global.Username != "" && - (cfg.Global.Password != "" || cfg.Global.ApiKey != "") && - (cfg.Global.TenantId != "" || cfg.Global.TenantName != "" || - cfg.Global.DomainId != "" || cfg.Global.DomainName != "")) - - return -} - -func TestNewRackspace(t *testing.T) { - cfg, ok := configFromEnv() - if !ok { - t.Skipf("No config found in environment") - } - - _, err := newRackspace(cfg) - if err != nil { - t.Fatalf("Failed to construct/authenticate Rackspace: %s", err) - } -} - -func TestInstances(t *testing.T) { - cfg, ok := configFromEnv() - if !ok { - t.Skipf("No config found in environment") - } - - os, err := newRackspace(cfg) - if err != nil { - t.Fatalf("Failed to construct/authenticate Rackspace: %s", err) - } - - i, ok := os.Instances() - if !ok { - t.Fatalf("Instances() returned false") - } - - srvs, err := i.List(".") - if err != nil { - t.Fatalf("Instances.List() failed: %s", err) - } - if len(srvs) == 0 { - t.Fatalf("Instances.List() returned zero servers") - } - t.Logf("Found servers (%d): %s\n", len(srvs), srvs) - - addrs, err := i.NodeAddresses(srvs[0]) - if err != nil { - t.Fatalf("Instances.NodeAddresses(%s) failed: %s", srvs[0], err) - } - t.Logf("Found NodeAddresses(%s) = %s\n", srvs[0], addrs) -} - -func TestZones(t *testing.T) { - os := Rackspace{ - provider: &gophercloud.ProviderClient{ - IdentityBase: "http://auth.url/", - }, - region: "myRegion", - } - - z, ok := os.Zones() - if !ok { - t.Fatalf("Zones() returned false") - } - - zone, err := z.GetZone() - if err != nil { - t.Fatalf("GetZone() returned error: %s", err) - } - - if zone.Region != "myRegion" { - t.Fatalf("GetZone() returned wrong region (%s)", zone.Region) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/OWNERS b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/OWNERS new file mode 100644 index 000000000..35859cd8c --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/OWNERS @@ -0,0 +1,5 @@ +assignees: + - bprashanth + - davidopp + - derekwaynecarr + - mikedanese diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/controller_utils.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/controller_utils.go new file mode 100644 index 000000000..fc377134d --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/controller_utils.go @@ -0,0 +1,647 @@ +/* +Copyright 2014 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. +*/ + +package controller + +import ( + "fmt" + "sync" + "sync/atomic" + "time" + + "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" + "k8s.io/kubernetes/pkg/client/record" + "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/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 + // of expectations, without it the controller could stay asleep forever. This should + // be set based on the expected latency of watch events. + // + // Currently a controller can service (create *and* observe the watch events for said + // creation) about 10 pods a second, so it takes about 1 min to service + // 500 pods. Just creation is limited to 20qps, and watching happens with ~10-30s + // latency/pod at the scale of 3000 pods over 100 nodes. + ExpectationsTimeout = 5 * time.Minute +) + +var ( + KeyFunc = framework.DeletionHandlingMetaNamespaceKeyFunc +) + +type ResyncPeriodFunc func() time.Duration + +// Returns 0 for resyncPeriod in case resyncing is not needed. +func NoResyncPeriodFunc() time.Duration { + return 0 +} + +// StaticResyncPeriodFunc returns the resync period specified +func StaticResyncPeriodFunc(resyncPeriod time.Duration) ResyncPeriodFunc { + return func() time.Duration { + return resyncPeriod + } +} + +// Expectations are a way for controllers to tell the controller manager what they expect. eg: +// ControllerExpectations: { +// controller1: expects 2 adds in 2 minutes +// controller2: expects 2 dels in 2 minutes +// controller3: expects -1 adds in 2 minutes => controller3's expectations have already been met +// } +// +// Implementation: +// ControlleeExpectation = pair of atomic counters to track controllee's creation/deletion +// ControllerExpectationsStore = TTLStore + a ControlleeExpectation per controller +// +// * Once set expectations can only be lowered +// * A controller isn't synced till its expectations are either fulfilled, or expire +// * Controllers that don't set expectations will get woken up for every matching controllee + +// ExpKeyFunc to parse out the key from a ControlleeExpectation +var ExpKeyFunc = func(obj interface{}) (string, error) { + if e, ok := obj.(*ControlleeExpectations); ok { + return e.key, nil + } + return "", fmt.Errorf("Could not find key for obj %#v", obj) +} + +// ControllerExpectationsInterface is an interface that allows users to set and wait on expectations. +// Only abstracted out for testing. +// Warning: if using KeyFunc it is not safe to use a single ControllerExpectationsInterface with different +// types of controllers, because the keys might conflict across types. +type ControllerExpectationsInterface interface { + GetExpectations(controllerKey string) (*ControlleeExpectations, bool, error) + SatisfiedExpectations(controllerKey string) bool + DeleteExpectations(controllerKey string) + SetExpectations(controllerKey string, add, del int) error + ExpectCreations(controllerKey string, adds int) error + ExpectDeletions(controllerKey string, dels int) error + CreationObserved(controllerKey string) + DeletionObserved(controllerKey string) + RaiseExpectations(controllerKey string, add, del int) + LowerExpectations(controllerKey string, add, del int) +} + +// ControllerExpectations is a cache mapping controllers to what they expect to see before being woken up for a sync. +type ControllerExpectations struct { + cache.Store +} + +// GetExpectations returns the ControlleeExpectations of the given controller. +func (r *ControllerExpectations) GetExpectations(controllerKey string) (*ControlleeExpectations, bool, error) { + if exp, exists, err := r.GetByKey(controllerKey); err == nil && exists { + return exp.(*ControlleeExpectations), true, nil + } else { + return nil, false, err + } +} + +// DeleteExpectations deletes the expectations of the given controller from the TTLStore. +func (r *ControllerExpectations) DeleteExpectations(controllerKey string) { + if exp, exists, err := r.GetByKey(controllerKey); err == nil && exists { + if err := r.Delete(exp); err != nil { + glog.V(2).Infof("Error deleting expectations for controller %v: %v", controllerKey, err) + } + } +} + +// SatisfiedExpectations returns true if the required adds/dels for the given controller have been observed. +// Add/del counts are established by the controller at sync time, and updated as controllees are observed by the controller +// manager. +func (r *ControllerExpectations) SatisfiedExpectations(controllerKey string) bool { + if exp, exists, err := r.GetExpectations(controllerKey); exists { + if exp.Fulfilled() { + return true + } else if exp.isExpired() { + glog.V(4).Infof("Controller expectations expired %#v", exp) + return true + } else { + glog.V(4).Infof("Controller still waiting on expectations %#v", exp) + return false + } + } else if err != nil { + glog.V(2).Infof("Error encountered while checking expectations %#v, forcing sync", err) + } else { + // When a new controller is created, it doesn't have expectations. + // When it doesn't see expected watch events for > TTL, the expectations expire. + // - In this case it wakes up, creates/deletes controllees, and sets expectations again. + // When it has satisfied expectations and no controllees need to be created/destroyed > TTL, the expectations expire. + // - In this case it continues without setting expectations till it needs to create/delete controllees. + glog.V(4).Infof("Controller %v either never recorded expectations, or the ttl expired.", controllerKey) + } + // Trigger a sync if we either encountered and error (which shouldn't happen since we're + // getting from local store) or this controller hasn't established expectations. + return true +} + +// TODO: Extend ExpirationCache to support explicit expiration. +// 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 +} + +// 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()} + glog.V(4).Infof("Setting expectations %+v", exp) + return r.Add(exp) +} + +func (r *ControllerExpectations) ExpectCreations(controllerKey string, adds int) error { + return r.SetExpectations(controllerKey, adds, 0) +} + +func (r *ControllerExpectations) ExpectDeletions(controllerKey string, dels int) error { + return r.SetExpectations(controllerKey, 0, dels) +} + +// Decrements the expectation counts of the given controller. +func (r *ControllerExpectations) LowerExpectations(controllerKey string, add, del int) { + if exp, exists, err := r.GetExpectations(controllerKey); err == nil && exists { + exp.Add(int64(-add), int64(-del)) + // The expectations might've been modified since the update on the previous line. + glog.V(4).Infof("Lowered expectations %+v", exp) + } +} + +// Increments the expectation counts of the given controller. +func (r *ControllerExpectations) RaiseExpectations(controllerKey string, add, del int) { + if exp, exists, err := r.GetExpectations(controllerKey); err == nil && exists { + exp.Add(int64(add), int64(del)) + // The expectations might've been modified since the update on the previous line. + glog.V(4).Infof("Raised expectations %+v", exp) + } +} + +// CreationObserved atomically decrements the `add` expecation count of the given controller. +func (r *ControllerExpectations) CreationObserved(controllerKey string) { + r.LowerExpectations(controllerKey, 1, 0) +} + +// DeletionObserved atomically decrements the `del` expectation count of the given controller. +func (r *ControllerExpectations) DeletionObserved(controllerKey string) { + r.LowerExpectations(controllerKey, 0, 1) +} + +// Expectations are either fulfilled, or expire naturally. +type Expectations interface { + Fulfilled() bool +} + +// ControlleeExpectations track controllee creates/deletes. +type ControlleeExpectations struct { + add int64 + del int64 + key string + timestamp time.Time +} + +// Add increments the add and del counters. +func (e *ControlleeExpectations) Add(add, del int64) { + atomic.AddInt64(&e.add, add) + atomic.AddInt64(&e.del, del) +} + +// Fulfilled returns true if this expectation has been fulfilled. +func (e *ControlleeExpectations) Fulfilled() bool { + // TODO: think about why this line being atomic doesn't matter + return atomic.LoadInt64(&e.add) <= 0 && atomic.LoadInt64(&e.del) <= 0 +} + +// GetExpectations returns the add and del expectations of the controllee. +func (e *ControlleeExpectations) GetExpectations() (int64, int64) { + return atomic.LoadInt64(&e.add), atomic.LoadInt64(&e.del) +} + +// NewControllerExpectations returns a store for ControllerExpectations. +func NewControllerExpectations() *ControllerExpectations { + return &ControllerExpectations{cache.NewStore(ExpKeyFunc)} +} + +// UIDSetKeyFunc to parse out the key from a UIDSet. +var UIDSetKeyFunc = func(obj interface{}) (string, error) { + if u, ok := obj.(*UIDSet); ok { + return u.key, nil + } + return "", fmt.Errorf("Could not find key for obj %#v", obj) +} + +// UIDSet holds a key and a set of UIDs. Used by the +// UIDTrackingControllerExpectations to remember which UID it has seen/still +// waiting for. +type UIDSet struct { + sets.String + key string +} + +// UIDTrackingControllerExpectations tracks the UID of the pods it deletes. +// This cache is needed over plain old expectations to safely handle graceful +// deletion. The desired behavior is to treat an update that sets the +// DeletionTimestamp on an object as a delete. To do so consistenly, one needs +// to remember the expected deletes so they aren't double counted. +// TODO: Track creates as well (#22599) +type UIDTrackingControllerExpectations struct { + ControllerExpectationsInterface + // TODO: There is a much nicer way to do this that involves a single store, + // a lock per entry, and a ControlleeExpectationsInterface type. + uidStoreLock sync.Mutex + // Store used for the UIDs associated with any expectation tracked via the + // ControllerExpectationsInterface. + uidStore cache.Store +} + +// GetUIDs is a convenience method to avoid exposing the set of expected uids. +// The returned set is not thread safe, all modifications must be made holding +// the uidStoreLock. +func (u *UIDTrackingControllerExpectations) GetUIDs(controllerKey string) sets.String { + if uid, exists, err := u.uidStore.GetByKey(controllerKey); err == nil && exists { + return uid.(*UIDSet).String + } + return nil +} + +// ExpectDeletions records expectations for the given deleteKeys, against the given controller. +func (u *UIDTrackingControllerExpectations) ExpectDeletions(rcKey string, deletedKeys []string) error { + u.uidStoreLock.Lock() + defer u.uidStoreLock.Unlock() + + if existing := u.GetUIDs(rcKey); existing != nil && existing.Len() != 0 { + glog.Errorf("Clobbering existing delete keys: %+v", existing) + } + expectedUIDs := sets.NewString() + for _, k := range deletedKeys { + expectedUIDs.Insert(k) + } + glog.V(4).Infof("Controller %v waiting on deletions for: %+v", rcKey, deletedKeys) + if err := u.uidStore.Add(&UIDSet{expectedUIDs, rcKey}); err != nil { + return err + } + return u.ControllerExpectationsInterface.ExpectDeletions(rcKey, expectedUIDs.Len()) +} + +// DeletionObserved records the given deleteKey as a deletion, for the given rc. +func (u *UIDTrackingControllerExpectations) DeletionObserved(rcKey, deleteKey string) { + u.uidStoreLock.Lock() + defer u.uidStoreLock.Unlock() + + uids := u.GetUIDs(rcKey) + if uids != nil && uids.Has(deleteKey) { + glog.V(4).Infof("Controller %v received delete for pod %v", rcKey, deleteKey) + u.ControllerExpectationsInterface.DeletionObserved(rcKey) + uids.Delete(deleteKey) + } +} + +// DeleteExpectations deletes the UID set and invokes DeleteExpectations on the +// underlying ControllerExpectationsInterface. +func (u *UIDTrackingControllerExpectations) DeleteExpectations(rcKey string) { + u.uidStoreLock.Lock() + defer u.uidStoreLock.Unlock() + + u.ControllerExpectationsInterface.DeleteExpectations(rcKey) + if uidExp, exists, err := u.uidStore.GetByKey(rcKey); err == nil && exists { + if err := u.uidStore.Delete(uidExp); err != nil { + glog.V(2).Infof("Error deleting uid expectations for controller %v: %v", rcKey, err) + } + } +} + +// NewUIDTrackingControllerExpectations returns a wrapper around +// ControllerExpectations that is aware of deleteKeys. +func NewUIDTrackingControllerExpectations(ce ControllerExpectationsInterface) *UIDTrackingControllerExpectations { + return &UIDTrackingControllerExpectations{ControllerExpectationsInterface: ce, uidStore: cache.NewStore(UIDSetKeyFunc)} +} + +// PodControlInterface is an interface that knows how to add or delete pods +// created as an interface to allow testing. +type PodControlInterface interface { + // CreatePods creates new pods according to the spec. + 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 + // DeletePod deletes the pod identified by podID. + DeletePod(namespace string, podID string, object runtime.Object) error +} + +// RealPodControl is the default implementation of PodControlInterface. +type RealPodControl struct { + KubeClient clientset.Interface + Recorder record.EventRecorder +} + +var _ PodControlInterface = &RealPodControl{} + +func getPodsLabelSet(template *api.PodTemplateSpec) labels.Set { + desiredLabels := make(labels.Set) + for k, v := range template.Labels { + desiredLabels[k] = v + } + return desiredLabels +} + +func getPodsAnnotationSet(template *api.PodTemplateSpec, object runtime.Object) (labels.Set, error) { + desiredAnnotations := make(labels.Set) + for k, v := range template.Annotations { + desiredAnnotations[k] = v + } + createdByRef, err := api.GetReference(object) + if err != nil { + return desiredAnnotations, fmt.Errorf("unable to get controller reference: %v", err) + } + + // TODO: this code was not safe previously - as soon as new code came along that switched to v2, old clients + // would be broken upon reading it. This is explicitly hardcoded to v1 to guarantee predictable deployment. + // We need to consistently handle this case of annotation versioning. + codec := api.Codecs.LegacyCodec(unversioned.GroupVersion{Group: api.GroupName, Version: "v1"}) + + createdByRefJson, err := runtime.Encode(codec, &api.SerializedReference{ + Reference: *createdByRef, + }) + if err != nil { + return desiredAnnotations, fmt.Errorf("unable to serialize controller reference: %v", err) + } + desiredAnnotations[CreatedByAnnotation] = string(createdByRefJson) + return desiredAnnotations, nil +} + +func getPodsPrefix(controllerName string) string { + // use the dash (if the name isn't too long) to make the pod name a bit prettier + prefix := fmt.Sprintf("%s-", controllerName) + if ok, _ := validation.ValidatePodName(prefix, true); !ok { + prefix = controllerName + } + return prefix +} + +func (r RealPodControl) CreatePods(namespace string, template *api.PodTemplateSpec, object runtime.Object) error { + return r.createPods("", namespace, template, object) +} + +func (r RealPodControl) CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { + return r.createPods(nodeName, namespace, template, object) +} + +func (r RealPodControl) createPods(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { + desiredLabels := getPodsLabelSet(template) + desiredAnnotations, err := getPodsAnnotationSet(template, object) + if err != nil { + return err + } + meta, err := api.ObjectMetaFor(object) + if err != nil { + return fmt.Errorf("object does not have ObjectMeta, %v", err) + } + prefix := getPodsPrefix(meta.Name) + + pod := &api.Pod{ + ObjectMeta: api.ObjectMeta{ + Labels: desiredLabels, + Annotations: desiredAnnotations, + GenerateName: prefix, + }, + } + if err := api.Scheme.Convert(&template.Spec, &pod.Spec); err != nil { + return fmt.Errorf("unable to convert pod template: %v", err) + } + if len(nodeName) != 0 { + pod.Spec.NodeName = nodeName + } + if labels.Set(pod.Labels).AsSelector().Empty() { + return fmt.Errorf("unable to create pods, no labels") + } + if newPod, err := r.KubeClient.Core().Pods(namespace).Create(pod); err != nil { + r.Recorder.Eventf(object, api.EventTypeWarning, "FailedCreate", "Error creating: %v", err) + return fmt.Errorf("unable to create pods: %v", err) + } else { + glog.V(4).Infof("Controller %v created pod %v", meta.Name, newPod.Name) + r.Recorder.Eventf(object, api.EventTypeNormal, "SuccessfulCreate", "Created pod: %v", newPod.Name) + } + return nil +} + +func (r RealPodControl) DeletePod(namespace string, podID string, object runtime.Object) error { + meta, err := api.ObjectMetaFor(object) + if err != nil { + return fmt.Errorf("object does not have ObjectMeta, %v", err) + } + if err := r.KubeClient.Core().Pods(namespace).Delete(podID, nil); err != nil { + r.Recorder.Eventf(object, api.EventTypeWarning, "FailedDelete", "Error deleting: %v", err) + return fmt.Errorf("unable to delete pods: %v", err) + } else { + glog.V(4).Infof("Controller %v deleted pod %v", meta.Name, podID) + r.Recorder.Eventf(object, api.EventTypeNormal, "SuccessfulDelete", "Deleted pod: %v", podID) + } + return nil +} + +type FakePodControl struct { + sync.Mutex + Templates []api.PodTemplateSpec + DeletePodName []string + Err error +} + +var _ PodControlInterface = &FakePodControl{} + +func (f *FakePodControl) CreatePods(namespace string, spec *api.PodTemplateSpec, object runtime.Object) error { + f.Lock() + defer f.Unlock() + if f.Err != nil { + return f.Err + } + f.Templates = append(f.Templates, *spec) + return nil +} + +func (f *FakePodControl) CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { + f.Lock() + defer f.Unlock() + 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() + if f.Err != nil { + return f.Err + } + f.DeletePodName = append(f.DeletePodName, podID) + return nil +} + +func (f *FakePodControl) Clear() { + f.Lock() + defer f.Unlock() + f.DeletePodName = []string{} + f.Templates = []api.PodTemplateSpec{} +} + +// ActivePods type allows custom sorting of pods so a controller can pick the best ones to delete. +type ActivePods []*api.Pod + +func (s ActivePods) Len() int { return len(s) } +func (s ActivePods) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +func (s ActivePods) Less(i, j int) bool { + // 1. Unassigned < assigned + // If only one of the pods is unassigned, the unassigned one is smaller + 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. PodPending < PodUnknown < PodRunning + m := map[api.PodPhase]int{api.PodPending: 0, api.PodUnknown: 1, api.PodRunning: 2} + if m[s[i].Status.Phase] != m[s[j].Status.Phase] { + return m[s[i].Status.Phase] < m[s[j].Status.Phase] + } + // 3. Not ready < ready + // If only one of the pods is not ready, the not ready one is smaller + 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 empty time < less time < more time + // If both pods are ready, the latest ready one is smaller + if api.IsPodReady(s[i]) && api.IsPodReady(s[j]) && !podReadyTime(s[i]).Equal(podReadyTime(s[j])) { + return afterOrZero(podReadyTime(s[i]), podReadyTime(s[j])) + } + // 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. Empty creation time pods < newer pods < older pods + if !s[i].CreationTimestamp.Equal(s[j].CreationTimestamp) { + return afterOrZero(s[i].CreationTimestamp, s[j].CreationTimestamp) + } + return false +} + +// afterOrZero checks if time t1 is after time t2; if one of them +// is zero, the zero time is seen as after non-zero time. +func afterOrZero(t1, t2 unversioned.Time) bool { + if t1.Time.IsZero() || t2.Time.IsZero() { + return t1.Time.IsZero() + } + return t1.After(t2.Time) +} + +func podReadyTime(pod *api.Pod) unversioned.Time { + if api.IsPodReady(pod) { + for _, c := range pod.Status.Conditions { + // we only care about pod ready conditions + if c.Type == api.PodReady && c.Status == api.ConditionTrue { + return c.LastTransitionTime + } + } + } + return unversioned.Time{} +} + +func maxContainerRestarts(pod *api.Pod) int { + maxRestarts := 0 + for _, c := range pod.Status.ContainerStatuses { + maxRestarts = integer.IntMax(maxRestarts, c.RestartCount) + } + return maxRestarts +} + +// FilterActivePods returns pods that have not terminated. +func FilterActivePods(pods []api.Pod) []*api.Pod { + var result []*api.Pod + for i := range pods { + p := pods[i] + if IsPodActive(p) { + result = append(result, &p) + } else { + glog.V(4).Infof("Ignoring inactive pod %v/%v in state %v, deletion time %v", + p.Namespace, p.Name, p.Status.Phase, p.DeletionTimestamp) + } + } + return result +} + +func IsPodActive(p api.Pod) bool { + return api.PodSucceeded != p.Status.Phase && + api.PodFailed != p.Status.Phase && + p.DeletionTimestamp == nil +} + +// FilterActiveReplicaSets returns replica sets that have (or at least ought to have) pods. +func FilterActiveReplicaSets(replicaSets []*extensions.ReplicaSet) []*extensions.ReplicaSet { + active := []*extensions.ReplicaSet{} + for i := range replicaSets { + if replicaSets[i].Spec.Replicas > 0 { + active = append(active, replicaSets[i]) + } + } + return active +} + +// 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. +func PodKey(pod *api.Pod) string { + return fmt.Sprintf("%v/%v", pod.Namespace, pod.Name) +} + +// ControllersByCreationTimestamp sorts a list of ReplicationControllers by creation timestamp, using their names as a tie breaker. +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 + } + return o[i].CreationTimestamp.Before(o[j].CreationTimestamp) +} + +// ReplicaSetsByCreationTimestamp sorts a list of ReplicationSets 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) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chown/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/doc.go similarity index 84% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chown/doc.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/doc.go index 3c41f5ed3..1e310b466 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chown/doc.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/doc.go @@ -14,5 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package chown provides utilities to chown a path -package chown +// Package controller contains code for controllers (like the replication +// controller). +package controller diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/framework/controller_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/framework/controller_test.go deleted file mode 100644 index dbede3423..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/framework/controller_test.go +++ /dev/null @@ -1,404 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package framework_test - -import ( - "fmt" - "math/rand" - "sync" - "testing" - "time" - - "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/util/sets" - - "github.com/google/gofuzz" -) - -func Example() { - // source simulates an apiserver object endpoint. - source := framework.NewFakeControllerSource() - - // This will hold the downstream state, as we know it. - downstream := cache.NewStore(framework.DeletionHandlingMetaNamespaceKeyFunc) - - // This will hold incoming changes. Note how we pass downstream in as a - // KeyLister, that way resync operations will result in the correct set - // of update/delete deltas. - fifo := cache.NewDeltaFIFO(cache.MetaNamespaceKeyFunc, nil, downstream) - - // Let's do threadsafe output to get predictable test results. - deletionCounter := make(chan string, 1000) - - cfg := &framework.Config{ - Queue: fifo, - ListerWatcher: source, - ObjectType: &api.Pod{}, - FullResyncPeriod: time.Millisecond * 100, - RetryOnError: false, - - // Let's implement a simple controller that just deletes - // everything that comes in. - Process: func(obj interface{}) error { - // Obj is from the Pop method of the Queue we make above. - newest := obj.(cache.Deltas).Newest() - - if newest.Type != cache.Deleted { - // Update our downstream store. - err := downstream.Add(newest.Object) - if err != nil { - return err - } - - // Delete this object. - source.Delete(newest.Object.(runtime.Object)) - } else { - // Update our downstream store. - err := downstream.Delete(newest.Object) - if err != nil { - return err - } - - // fifo's KeyOf is easiest, because it handles - // DeletedFinalStateUnknown markers. - key, err := fifo.KeyOf(newest.Object) - if err != nil { - return err - } - - // Report this deletion. - deletionCounter <- key - } - return nil - }, - } - - // Create the controller and run it until we close stop. - stop := make(chan struct{}) - defer close(stop) - go framework.New(cfg).Run(stop) - - // Let's add a few objects to the source. - testIDs := []string{"a-hello", "b-controller", "c-framework"} - for _, name := range testIDs { - // Note that these pods are not valid-- the fake source doesn't - // call validation or anything. - source.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: name}}) - } - - // Let's wait for the controller to process the things we just added. - outputSet := sets.String{} - for i := 0; i < len(testIDs); i++ { - outputSet.Insert(<-deletionCounter) - } - - for _, key := range outputSet.List() { - fmt.Println(key) - } - // Output: - // a-hello - // b-controller - // c-framework -} - -func ExampleInformer() { - // source simulates an apiserver object endpoint. - source := framework.NewFakeControllerSource() - - // Let's do threadsafe output to get predictable test results. - deletionCounter := make(chan string, 1000) - - // Make a controller that immediately deletes anything added to it, and - // logs anything deleted. - _, controller := framework.NewInformer( - source, - &api.Pod{}, - time.Millisecond*100, - framework.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - source.Delete(obj.(runtime.Object)) - }, - DeleteFunc: func(obj interface{}) { - key, err := framework.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - key = "oops something went wrong with the key" - } - - // Report this deletion. - deletionCounter <- key - }, - }, - ) - - // Run the controller and run it until we close stop. - stop := make(chan struct{}) - defer close(stop) - go controller.Run(stop) - - // Let's add a few objects to the source. - testIDs := []string{"a-hello", "b-controller", "c-framework"} - for _, name := range testIDs { - // Note that these pods are not valid-- the fake source doesn't - // call validation or anything. - source.Add(&api.Pod{ObjectMeta: api.ObjectMeta{Name: name}}) - } - - // Let's wait for the controller to process the things we just added. - outputSet := sets.String{} - for i := 0; i < len(testIDs); i++ { - outputSet.Insert(<-deletionCounter) - } - - for _, key := range outputSet.List() { - fmt.Println(key) - } - // Output: - // a-hello - // b-controller - // c-framework -} - -func TestHammerController(t *testing.T) { - // This test executes a bunch of requests through the fake source and - // controller framework to make sure there's no locking/threading - // errors. If an error happens, it should hang forever or trigger the - // race detector. - - // source simulates an apiserver object endpoint. - source := framework.NewFakeControllerSource() - - // Let's do threadsafe output to get predictable test results. - outputSetLock := sync.Mutex{} - // map of key to operations done on the key - outputSet := map[string][]string{} - - recordFunc := func(eventType string, obj interface{}) { - key, err := framework.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - t.Errorf("something wrong with key: %v", err) - key = "oops something went wrong with the key" - } - - // Record some output when items are deleted. - outputSetLock.Lock() - defer outputSetLock.Unlock() - outputSet[key] = append(outputSet[key], eventType) - } - - // Make a controller which just logs all the changes it gets. - _, controller := framework.NewInformer( - source, - &api.Pod{}, - time.Millisecond*100, - framework.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { recordFunc("add", obj) }, - UpdateFunc: func(oldObj, newObj interface{}) { recordFunc("update", newObj) }, - DeleteFunc: func(obj interface{}) { recordFunc("delete", obj) }, - }, - ) - - if controller.HasSynced() { - t.Errorf("Expected HasSynced() to return false before we started the controller") - } - - // Run the controller and run it until we close stop. - stop := make(chan struct{}) - go controller.Run(stop) - - // Let's wait for the controller to do its initial sync - time.Sleep(100 * time.Millisecond) - if !controller.HasSynced() { - t.Errorf("Expected HasSynced() to return true after the initial sync") - } - - wg := sync.WaitGroup{} - const threads = 3 - wg.Add(threads) - for i := 0; i < threads; i++ { - go func() { - defer wg.Done() - // Let's add a few objects to the source. - currentNames := sets.String{} - rs := rand.NewSource(rand.Int63()) - f := fuzz.New().NilChance(.5).NumElements(0, 2).RandSource(rs) - r := rand.New(rs) // Mustn't use r and f concurrently! - for i := 0; i < 100; i++ { - var name string - var isNew bool - if currentNames.Len() == 0 || r.Intn(3) == 1 { - f.Fuzz(&name) - isNew = true - } else { - l := currentNames.List() - name = l[r.Intn(len(l))] - } - - pod := &api.Pod{} - f.Fuzz(pod) - pod.ObjectMeta.Name = name - pod.ObjectMeta.Namespace = "default" - // Add, update, or delete randomly. - // Note that these pods are not valid-- the fake source doesn't - // call validation or perform any other checking. - if isNew { - currentNames.Insert(name) - source.Add(pod) - continue - } - switch r.Intn(2) { - case 0: - currentNames.Insert(name) - source.Modify(pod) - case 1: - currentNames.Delete(name) - source.Delete(pod) - } - } - }() - } - wg.Wait() - - // Let's wait for the controller to finish processing the things we just added. - time.Sleep(100 * time.Millisecond) - close(stop) - - outputSetLock.Lock() - t.Logf("got: %#v", outputSet) -} - -func TestUpdate(t *testing.T) { - // This test is going to exercise the various paths that result in a - // call to update. - - // source simulates an apiserver object endpoint. - source := framework.NewFakeControllerSource() - - const ( - FROM = "from" - ADD_MISSED = "missed the add event" - TO = "to" - ) - - // These are the transitions we expect to see; because this is - // asynchronous, there are a lot of valid possibilities. - type pair struct{ from, to string } - allowedTransitions := map[pair]bool{ - pair{FROM, TO}: true, - pair{FROM, ADD_MISSED}: true, - pair{ADD_MISSED, TO}: true, - - // Because a resync can happen when we've already observed one - // of the above but before the item is deleted. - pair{TO, TO}: true, - // Because a resync could happen before we observe an update. - pair{FROM, FROM}: true, - } - - pod := func(name, check string, final bool) *api.Pod { - p := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: name, - Labels: map[string]string{"check": check}, - }, - } - if final { - p.Labels["final"] = "true" - } - return p - } - deletePod := func(p *api.Pod) bool { - return p.Labels["final"] == "true" - } - - tests := []func(string){ - func(name string) { - name = "a-" + name - source.Add(pod(name, FROM, false)) - source.Modify(pod(name, TO, true)) - }, - func(name string) { - name = "b-" + name - source.Add(pod(name, FROM, false)) - source.ModifyDropWatch(pod(name, TO, true)) - }, - func(name string) { - name = "c-" + name - source.AddDropWatch(pod(name, FROM, false)) - source.Modify(pod(name, ADD_MISSED, false)) - source.Modify(pod(name, TO, true)) - }, - func(name string) { - name = "d-" + name - source.Add(pod(name, FROM, true)) - }, - } - - const threads = 3 - - var testDoneWG sync.WaitGroup - testDoneWG.Add(threads * len(tests)) - - // Make a controller that deletes things once it observes an update. - // It calls Done() on the wait group on deletions so we can tell when - // everything we've added has been deleted. - _, controller := framework.NewInformer( - source, - &api.Pod{}, - time.Millisecond*1, - framework.ResourceEventHandlerFuncs{ - UpdateFunc: func(oldObj, newObj interface{}) { - o, n := oldObj.(*api.Pod), newObj.(*api.Pod) - from, to := o.Labels["check"], n.Labels["check"] - if !allowedTransitions[pair{from, to}] { - t.Errorf("observed transition %q -> %q for %v", from, to, n.Name) - } - if deletePod(n) { - source.Delete(n) - } - }, - DeleteFunc: func(obj interface{}) { - testDoneWG.Done() - }, - }, - ) - - // Run the controller and run it until we close stop. - // Once Run() is called, calls to testDoneWG.Done() might start, so - // all testDoneWG.Add() calls must happen before this point - stop := make(chan struct{}) - go controller.Run(stop) - - // run every test a few times, in parallel - var wg sync.WaitGroup - wg.Add(threads * len(tests)) - for i := 0; i < threads; i++ { - for j, f := range tests { - go func(name string, f func(string)) { - defer wg.Done() - f(name) - }(fmt.Sprintf("%v-%v", i, j), f) - } - } - wg.Wait() - - // Let's wait for the controller to process the things we just added. - testDoneWG.Wait() - close(stop) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/framework/fake_controller_source_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/framework/fake_controller_source_test.go deleted file mode 100644 index 01269ce64..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/framework/fake_controller_source_test.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package framework - -import ( - "sync" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/watch" -) - -// ensure the watch delivers the requested and only the requested items. -func consume(t *testing.T, w watch.Interface, rvs []string, done *sync.WaitGroup) { - defer done.Done() - for _, rv := range rvs { - got, ok := <-w.ResultChan() - if !ok { - t.Errorf("%#v: unexpected channel close, wanted %v", rvs, rv) - return - } - gotRV := got.Object.(*api.Pod).ObjectMeta.ResourceVersion - if e, a := rv, gotRV; e != a { - t.Errorf("wanted %v, got %v", e, a) - } else { - t.Logf("Got %v as expected", gotRV) - } - } - // We should not get anything else. - got, open := <-w.ResultChan() - if open { - t.Errorf("%#v: unwanted object %#v", rvs, got) - } -} - -func TestRCNumber(t *testing.T) { - pod := func(name string) *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: name, - }, - } - } - - wg := &sync.WaitGroup{} - wg.Add(3) - - source := NewFakeControllerSource() - source.Add(pod("foo")) - source.Modify(pod("foo")) - source.Modify(pod("foo")) - - w, err := source.Watch(api.ListOptions{ResourceVersion: "1"}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - go consume(t, w, []string{"2", "3"}, wg) - - list, err := source.List(api.ListOptions{}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if e, a := "3", list.(*api.List).ResourceVersion; e != a { - t.Errorf("wanted %v, got %v", e, a) - } - - w2, err := source.Watch(api.ListOptions{ResourceVersion: "2"}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - go consume(t, w2, []string{"3"}, wg) - - w3, err := source.Watch(api.ListOptions{ResourceVersion: "3"}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - go consume(t, w3, []string{}, wg) - source.Shutdown() - wg.Wait() -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/lookup_cache.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/lookup_cache.go new file mode 100644 index 000000000..5d82908be --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/lookup_cache.go @@ -0,0 +1,90 @@ +/* +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. +*/ + +package controller + +import ( + "hash/adler32" + "sync" + + "github.com/golang/groupcache/lru" + "k8s.io/kubernetes/pkg/api/meta" + hashutil "k8s.io/kubernetes/pkg/util/hash" +) + +type objectWithMeta interface { + meta.Object +} + +// keyFunc returns the key of an object, which is used to look up in the cache for it's matching object. +// Since we match objects by namespace and Labels/Selector, so if two objects have the same namespace and labels, +// they will have the same key. +func keyFunc(obj objectWithMeta) uint64 { + hash := adler32.New() + hashutil.DeepHashObject(hash, &equivalenceLabelObj{ + namespace: obj.GetNamespace(), + labels: obj.GetLabels(), + }) + return uint64(hash.Sum32()) +} + +type equivalenceLabelObj struct { + namespace string + labels map[string]string +} + +// MatchingCache save label and selector matching relationship +type MatchingCache struct { + mutex sync.RWMutex + cache *lru.Cache +} + +// NewMatchingCache return a NewMatchingCache, which save label and selector matching relationship. +func NewMatchingCache(maxCacheEntries int) *MatchingCache { + return &MatchingCache{ + cache: lru.New(maxCacheEntries), + } +} + +// Add will add matching information to the cache. +func (c *MatchingCache) Add(labelObj objectWithMeta, selectorObj objectWithMeta) { + key := keyFunc(labelObj) + c.mutex.Lock() + defer c.mutex.Unlock() + c.cache.Add(key, selectorObj) +} + +// GetMatchingObject lookup the matching object for a given object. +// Note: the cache information may be invalid since the controller may be deleted or updated, +// we need check in the external request to ensure the cache data is not dirty. +func (c *MatchingCache) GetMatchingObject(labelObj objectWithMeta) (controller interface{}, exists bool) { + key := keyFunc(labelObj) + c.mutex.Lock() + defer c.mutex.Unlock() + return c.cache.Get(key) +} + +// Update update the cached matching information. +func (c *MatchingCache) Update(labelObj objectWithMeta, selectorObj objectWithMeta) { + c.Add(labelObj, selectorObj) +} + +// InvalidateAll invalidate the whole cache. +func (c *MatchingCache) InvalidateAll() { + c.mutex.Lock() + defer c.mutex.Unlock() + c.cache = lru.New(c.cache.MaxEntries) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/OWNERS b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/OWNERS new file mode 100644 index 000000000..a046efc0c --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/OWNERS @@ -0,0 +1,5 @@ +assignees: + - derekwaynecarr + - lavalamp + - smarterclayton + - wojtek-t diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/converter_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/converter_test.go deleted file mode 100644 index c639492a7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/converter_test.go +++ /dev/null @@ -1,847 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package conversion - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" - "strings" - "testing" - - "github.com/google/gofuzz" - flag "github.com/spf13/pflag" - - "k8s.io/kubernetes/pkg/util" -) - -var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.") - -// Test a weird version/kind embedding format. -type MyWeirdCustomEmbeddedVersionKindField struct { - ID string `json:"ID,omitempty"` - APIVersion string `json:"myVersionKey,omitempty"` - ObjectKind string `json:"myKindKey,omitempty"` - Z string `json:"Z,omitempty"` - Y uint64 `json:"Y,omitempty"` -} - -type TestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]TestType2 `json:"N,omitempty"` - O *TestType2 `json:"O,omitempty"` - P []TestType2 `json:"Q,omitempty"` -} - -type TestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} - -type ExternalTestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} -type ExternalTestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]ExternalTestType2 `json:"N,omitempty"` - O *ExternalTestType2 `json:"O,omitempty"` - P []ExternalTestType2 `json:"Q,omitempty"` -} - -func testLogger(t *testing.T) DebugLogger { - // We don't set logger to eliminate rubbish logs in tests. - // If you want to switch it, simply switch it to: "return t" - return nil -} - -func TestConverter_byteSlice(t *testing.T) { - c := NewConverter(DefaultNameFunc) - src := []byte{1, 2, 3} - dest := []byte{} - err := c.Convert(&src, &dest, 0, nil) - if err != nil { - t.Fatalf("expected no error") - } - if e, a := src, dest; !reflect.DeepEqual(e, a) { - t.Errorf("expected %#v, got %#v", e, a) - } -} - -func TestConverter_MismatchedTypes(t *testing.T) { - c := NewConverter(DefaultNameFunc) - - err := c.RegisterConversionFunc( - func(in *[]string, out *int, s Scope) error { - if str, err := strconv.Atoi((*in)[0]); err != nil { - return err - } else { - *out = str - return nil - } - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - src := []string{"5"} - var dest *int - err = c.Convert(&src, &dest, 0, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := 5, *dest; e != a { - t.Errorf("expected %#v, got %#v", e, a) - } -} - -func TestConverter_DefaultConvert(t *testing.T) { - type A struct { - Foo string - Baz int - } - type B struct { - Bar string - Baz int - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - c.nameFunc = func(t reflect.Type) string { return "MyType" } - - // Ensure conversion funcs can call DefaultConvert to get default behavior, - // then fixup remaining fields manually - err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - if err := s.DefaultConvert(in, out, IgnoreMissingFields); err != nil { - return err - } - out.Bar = in.Foo - return nil - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := A{"hello, intrepid test reader!", 3} - y := B{} - - err = c.Convert(&x, &y, 0, nil) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if e, a := x.Foo, y.Bar; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := x.Baz, y.Baz; e != a { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestConverter_DeepCopy(t *testing.T) { - type A struct { - Foo *string - Bar []string - Baz interface{} - Qux map[string]string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - - foo, baz := "foo", "baz" - x := A{ - Foo: &foo, - Bar: []string{"bar"}, - Baz: &baz, - Qux: map[string]string{"qux": "qux"}, - } - y := A{} - - if err := c.Convert(&x, &y, 0, nil); err != nil { - t.Fatalf("unexpected error %v", err) - } - *x.Foo = "foo2" - x.Bar[0] = "bar2" - *x.Baz.(*string) = "baz2" - x.Qux["qux"] = "qux2" - if e, a := *x.Foo, *y.Foo; e == a { - t.Errorf("expected difference between %v and %v", e, a) - } - if e, a := x.Bar, y.Bar; reflect.DeepEqual(e, a) { - t.Errorf("expected difference between %v and %v", e, a) - } - if e, a := *x.Baz.(*string), *y.Baz.(*string); e == a { - t.Errorf("expected difference between %v and %v", e, a) - } - if e, a := x.Qux, y.Qux; reflect.DeepEqual(e, a) { - t.Errorf("expected difference between %v and %v", e, a) - } -} - -func TestConverter_CallsRegisteredFunctions(t *testing.T) { - type A struct { - Foo string - Baz int - } - type B struct { - Bar string - Baz int - } - type C struct{} - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - out.Bar = in.Foo - return s.Convert(&in.Baz, &out.Baz, 0) - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.RegisterConversionFunc(func(in *B, out *A, s Scope) error { - out.Foo = in.Bar - return s.Convert(&in.Baz, &out.Baz, 0) - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := A{"hello, intrepid test reader!", 3} - y := B{} - - err = c.Convert(&x, &y, 0, nil) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if e, a := x.Foo, y.Bar; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := x.Baz, y.Baz; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - z := B{"all your test are belong to us", 42} - w := A{} - - err = c.Convert(&z, &w, 0, nil) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if e, a := z.Bar, w.Foo; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := z.Baz, w.Baz; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - err = c.RegisterConversionFunc(func(in *A, out *C, s Scope) error { - return fmt.Errorf("C can't store an A, silly") - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.Convert(&A{}, &C{}, 0, nil) - if err == nil { - t.Errorf("unexpected non-error") - } -} - -func TestConverter_IgnoredConversion(t *testing.T) { - type A struct{} - type B struct{} - - count := 0 - c := NewConverter(DefaultNameFunc) - if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - count++ - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - if err := c.RegisterIgnoredConversion(&A{}, &B{}); err != nil { - t.Fatal(err) - } - a := A{} - b := B{} - if err := c.Convert(&a, &b, 0, nil); err != nil { - t.Errorf("%v", err) - } - if count != 0 { - t.Errorf("unexpected number of conversion invocations") - } -} - -func TestConverter_IgnoredConversionNested(t *testing.T) { - type C string - type A struct { - C C - } - type B struct { - C C - } - - c := NewConverter(DefaultNameFunc) - typed := C("") - if err := c.RegisterIgnoredConversion(&typed, &typed); err != nil { - t.Fatal(err) - } - a := A{C: C("test")} - b := B{C: C("other")} - if err := c.Convert(&a, &b, AllowDifferentFieldTypeNames, nil); err != nil { - t.Errorf("%v", err) - } - if b.C != C("other") { - t.Errorf("expected no conversion of field C: %#v", b) - } -} - -func TestConverter_GeneratedConversionOverriden(t *testing.T) { - type A struct{} - type B struct{} - c := NewConverter(DefaultNameFunc) - if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error { - return fmt.Errorf("generated function should be overriden") - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - a := A{} - b := B{} - if err := c.Convert(&a, &b, 0, nil); err != nil { - t.Errorf("%v", err) - } -} - -func TestConverter_WithConversionOverriden(t *testing.T) { - type A struct{} - type B struct{} - c := NewConverter(DefaultNameFunc) - if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - return fmt.Errorf("conversion function should be overriden") - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error { - return fmt.Errorf("generated function should be overriden") - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - ext := NewConversionFuncs() - ext.Add(func(in *A, out *B, s Scope) error { - return nil - }) - newc := c.WithConversions(ext) - - a := A{} - b := B{} - if err := c.Convert(&a, &b, 0, nil); err == nil || err.Error() != "conversion function should be overriden" { - t.Errorf("unexpected error: %v", err) - } - if err := newc.Convert(&a, &b, 0, nil); err != nil { - t.Errorf("%v", err) - } -} - -func TestConverter_MapsStringArrays(t *testing.T) { - type A struct { - Foo string - Baz int - Other string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error { - if len(*input) == 0 { - *out = "" - } - *out = (*input)[0] - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := map[string][]string{ - "Foo": {"bar"}, - "Baz": {"1"}, - "Other": {"", "test"}, - "other": {"wrong"}, - } - y := A{"test", 2, "something"} - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err == nil { - t.Error("unexpected non-error") - } - - if err := c.RegisterConversionFunc(func(input *[]string, out *int, s Scope) error { - if len(*input) == 0 { - *out = 0 - } - str := (*input)[0] - i, err := strconv.Atoi(str) - if err != nil { - return err - } - *out = i - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err != nil { - t.Fatalf("unexpected error %v", err) - } - if !reflect.DeepEqual(y, A{"bar", 1, ""}) { - t.Errorf("unexpected result: %#v", y) - } -} - -func TestConverter_MapsStringArraysWithMappingKey(t *testing.T) { - type A struct { - Foo string `json:"test"` - Baz int - Other string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error { - if len(*input) == 0 { - *out = "" - } - *out = (*input)[0] - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := map[string][]string{ - "Foo": {"bar"}, - "test": {"baz"}, - } - y := A{"", 0, ""} - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{}); err != nil { - t.Fatalf("unexpected error %v", err) - } - if !reflect.DeepEqual(y, A{"bar", 0, ""}) { - t.Errorf("unexpected result: %#v", y) - } - - mapping := func(key string, sourceTag, destTag reflect.StructTag) (source string, dest string) { - if s := destTag.Get("json"); len(s) > 0 { - return strings.SplitN(s, ",", 2)[0], key - } - return key, key - } - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{KeyNameMapping: mapping}); err != nil { - t.Fatalf("unexpected error %v", err) - } - if !reflect.DeepEqual(y, A{"baz", 0, ""}) { - t.Errorf("unexpected result: %#v", y) - } -} - -func TestConverter_fuzz(t *testing.T) { - // Use the same types from the scheme test. - table := []struct { - from, to, check interface{} - }{ - {&TestType1{}, &ExternalTestType1{}, &TestType1{}}, - {&ExternalTestType1{}, &TestType1{}, &ExternalTestType1{}}, - } - - f := fuzz.New().NilChance(.5).NumElements(0, 100) - c := NewConverter(DefaultNameFunc) - c.nameFunc = func(t reflect.Type) string { - // Hide the fact that we don't have separate packages for these things. - return map[reflect.Type]string{ - reflect.TypeOf(TestType1{}): "TestType1", - reflect.TypeOf(ExternalTestType1{}): "TestType1", - reflect.TypeOf(TestType2{}): "TestType2", - reflect.TypeOf(ExternalTestType2{}): "TestType2", - }[t] - } - c.Debug = testLogger(t) - - for i, item := range table { - for j := 0; j < *fuzzIters; j++ { - f.Fuzz(item.from) - err := c.Convert(item.from, item.to, 0, nil) - if err != nil { - t.Errorf("(%v, %v): unexpected error: %v", i, j, err) - continue - } - err = c.Convert(item.to, item.check, 0, nil) - if err != nil { - t.Errorf("(%v, %v): unexpected error: %v", i, j, err) - continue - } - if e, a := item.from, item.check; !reflect.DeepEqual(e, a) { - t.Errorf("(%v, %v): unexpected diff: %v", i, j, objDiff(e, a)) - } - } - } -} - -func TestConverter_MapElemAddr(t *testing.T) { - type Foo struct { - A map[int]int - } - type Bar struct { - A map[string]string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - err := c.RegisterConversionFunc( - func(in *int, out *string, s Scope) error { - *out = fmt.Sprintf("%v", *in) - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.RegisterConversionFunc( - func(in *string, out *int, s Scope) error { - if str, err := strconv.Atoi(*in); err != nil { - return err - } else { - *out = str - return nil - } - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - f := fuzz.New().NilChance(0).NumElements(3, 3) - first := Foo{} - second := Bar{} - f.Fuzz(&first) - err = c.Convert(&first, &second, AllowDifferentFieldTypeNames, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - third := Foo{} - err = c.Convert(&second, &third, AllowDifferentFieldTypeNames, nil) - if e, a := first, third; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected diff: %v", objDiff(e, a)) - } -} - -func TestConverter_tags(t *testing.T) { - type Foo struct { - A string `test:"foo"` - } - type Bar struct { - A string `test:"bar"` - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - err := c.RegisterConversionFunc( - func(in *string, out *string, s Scope) error { - if e, a := "foo", s.SrcTag().Get("test"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "bar", s.DestTag().Get("test"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.Convert(&Foo{}, &Bar{}, AllowDifferentFieldTypeNames, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestConverter_meta(t *testing.T) { - type Foo struct{ A string } - type Bar struct{ A string } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - checks := 0 - err := c.RegisterConversionFunc( - func(in *Foo, out *Bar, s Scope) error { - if s.Meta() == nil || s.Meta().SrcVersion != "test" || s.Meta().DestVersion != "passes" { - t.Errorf("Meta did not get passed!") - } - checks++ - s.Convert(&in.A, &out.A, 0) - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.RegisterConversionFunc( - func(in *string, out *string, s Scope) error { - if s.Meta() == nil || s.Meta().SrcVersion != "test" || s.Meta().DestVersion != "passes" { - t.Errorf("Meta did not get passed a second time!") - } - checks++ - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.Convert(&Foo{}, &Bar{}, 0, &Meta{SrcVersion: "test", DestVersion: "passes"}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if checks != 2 { - t.Errorf("Registered functions did not get called.") - } -} - -func TestConverter_flags(t *testing.T) { - type Foo struct{ A string } - type Bar struct{ A string } - table := []struct { - from, to interface{} - flags FieldMatchingFlags - shouldSucceed bool - }{ - // Check that DestFromSource allows extra fields only in source. - { - from: &struct{ A string }{}, - to: &struct{ A, B string }{}, - flags: DestFromSource, - shouldSucceed: false, - }, { - from: &struct{ A, B string }{}, - to: &struct{ A string }{}, - flags: DestFromSource, - shouldSucceed: true, - }, - - // Check that SourceToDest allows for extra fields only in dest. - { - from: &struct{ A string }{}, - to: &struct{ A, B string }{}, - flags: SourceToDest, - shouldSucceed: true, - }, { - from: &struct{ A, B string }{}, - to: &struct{ A string }{}, - flags: SourceToDest, - shouldSucceed: false, - }, - - // Check that IgnoreMissingFields makes the above failure cases pass. - { - from: &struct{ A string }{}, - to: &struct{ A, B string }{}, - flags: DestFromSource | IgnoreMissingFields, - shouldSucceed: true, - }, { - from: &struct{ A, B string }{}, - to: &struct{ A string }{}, - flags: SourceToDest | IgnoreMissingFields, - shouldSucceed: true, - }, - - // Check that the field type name must match unless - // AllowDifferentFieldTypeNames is specified. - { - from: &struct{ A, B Foo }{}, - to: &struct{ A Bar }{}, - flags: DestFromSource, - shouldSucceed: false, - }, { - from: &struct{ A Foo }{}, - to: &struct{ A, B Bar }{}, - flags: SourceToDest, - shouldSucceed: false, - }, { - from: &struct{ A, B Foo }{}, - to: &struct{ A Bar }{}, - flags: DestFromSource | AllowDifferentFieldTypeNames, - shouldSucceed: true, - }, { - from: &struct{ A Foo }{}, - to: &struct{ A, B Bar }{}, - flags: SourceToDest | AllowDifferentFieldTypeNames, - shouldSucceed: true, - }, - } - f := fuzz.New().NilChance(.5).NumElements(0, 100) - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - - for i, item := range table { - for j := 0; j < *fuzzIters; j++ { - f.Fuzz(item.from) - err := c.Convert(item.from, item.to, item.flags, nil) - if item.shouldSucceed && err != nil { - t.Errorf("(%v, %v): unexpected error: %v", i, j, err) - continue - } - if !item.shouldSucceed && err == nil { - t.Errorf("(%v, %v): unexpected non-error", i, j) - continue - } - } - } -} - -func TestConverter_FieldRename(t *testing.T) { - type WeirdMeta struct { - Name string - Type string - } - type NameMeta struct { - Name string - } - type TypeMeta struct { - Type string - } - type A struct { - WeirdMeta - } - type B struct { - TypeMeta - NameMeta - } - - c := NewConverter(DefaultNameFunc) - err := c.SetStructFieldCopy(WeirdMeta{}, "WeirdMeta", TypeMeta{}, "TypeMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.SetStructFieldCopy(WeirdMeta{}, "WeirdMeta", NameMeta{}, "NameMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.SetStructFieldCopy(TypeMeta{}, "TypeMeta", WeirdMeta{}, "WeirdMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.SetStructFieldCopy(NameMeta{}, "NameMeta", WeirdMeta{}, "WeirdMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - c.Debug = testLogger(t) - - aVal := &A{ - WeirdMeta: WeirdMeta{ - Name: "Foo", - Type: "Bar", - }, - } - - bVal := &B{ - TypeMeta: TypeMeta{"Bar"}, - NameMeta: NameMeta{"Foo"}, - } - - table := map[string]struct { - from, to, expect interface{} - flags FieldMatchingFlags - }{ - "to": { - aVal, - &B{}, - bVal, - AllowDifferentFieldTypeNames | SourceToDest | IgnoreMissingFields, - }, - "from": { - bVal, - &A{}, - aVal, - AllowDifferentFieldTypeNames | SourceToDest, - }, - "toDestFirst": { - aVal, - &B{}, - bVal, - AllowDifferentFieldTypeNames, - }, - "fromDestFirst": { - bVal, - &A{}, - aVal, - AllowDifferentFieldTypeNames | IgnoreMissingFields, - }, - } - - for name, item := range table { - err := c.Convert(item.from, item.to, item.flags, nil) - if err != nil { - t.Errorf("%v: unexpected error: %v", name, err) - continue - } - if e, a := item.expect, item.to; !reflect.DeepEqual(e, a) { - t.Errorf("%v: unexpected diff: %v", name, objDiff(e, a)) - } - } -} - -func objDiff(a, b interface{}) string { - ab, err := json.Marshal(a) - if err != nil { - panic("a") - } - bb, err := json.Marshal(b) - if err != nil { - panic("b") - } - return util.StringDiff(string(ab), string(bb)) - - // An alternate diff attempt, in case json isn't showing you - // the difference. (reflect.DeepEqual makes a distinction between - // nil and empty slices, for example.) - //return util.StringDiff( - // fmt.Sprintf("%#v", a), - // fmt.Sprintf("%#v", b), - //) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/deep_copy_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/deep_copy_test.go deleted file mode 100644 index a1cd65308..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/deep_copy_test.go +++ /dev/null @@ -1,161 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package conversion - -import ( - "math/rand" - "reflect" - "testing" - - "github.com/google/gofuzz" -) - -func TestDeepCopy(t *testing.T) { - semantic := EqualitiesOrDie() - f := fuzz.New().NilChance(.5).NumElements(0, 100) - table := []interface{}{ - map[string]string{}, - int(5), - "hello world", - struct { - A, B, C struct { - D map[string]int - } - X []int - Y []byte - }{}, - } - for _, obj := range table { - obj2, err := NewCloner().DeepCopy(obj) - if err != nil { - t.Errorf("Error: couldn't copy %#v", obj) - continue - } - if e, a := obj, obj2; !semantic.DeepEqual(e, a) { - t.Errorf("expected %#v\ngot %#v", e, a) - } - - obj3 := reflect.New(reflect.TypeOf(obj)).Interface() - f.Fuzz(obj3) - obj4, err := NewCloner().DeepCopy(obj3) - if err != nil { - t.Errorf("Error: couldn't copy %#v", obj) - continue - } - if e, a := obj3, obj4; !semantic.DeepEqual(e, a) { - t.Errorf("expected %#v\ngot %#v", e, a) - } - f.Fuzz(obj3) - } -} - -func copyOrDie(t *testing.T, in interface{}) interface{} { - out, err := NewCloner().DeepCopy(in) - if err != nil { - t.Fatalf("DeepCopy failed: %#q: %v", in, err) - } - return out -} - -func TestDeepCopySliceSeparate(t *testing.T) { - x := []int{5} - y := copyOrDie(t, x).([]int) - x[0] = 3 - if y[0] == 3 { - t.Errorf("deep copy wasn't deep: %#q %#q", x, y) - } -} - -func TestDeepCopyArraySeparate(t *testing.T) { - x := [1]int{5} - y := copyOrDie(t, x).([1]int) - x[0] = 3 - if y[0] == 3 { - t.Errorf("deep copy wasn't deep: %#q %#q", x, y) - } -} - -func TestDeepCopyMapSeparate(t *testing.T) { - x := map[string]int{"foo": 5} - y := copyOrDie(t, x).(map[string]int) - x["foo"] = 3 - if y["foo"] == 3 { - t.Errorf("deep copy wasn't deep: %#q %#q", x, y) - } -} - -func TestDeepCopyPointerSeparate(t *testing.T) { - z := 5 - x := &z - y := copyOrDie(t, x).(*int) - *x = 3 - if *y == 3 { - t.Errorf("deep copy wasn't deep: %#q %#q", x, y) - } -} - -func TestDeepCopyStruct(t *testing.T) { - type Foo struct { - A int - } - type Bar struct { - Foo - F *Foo - } - a := &Bar{Foo{1}, &Foo{2}} - b := copyOrDie(t, a).(*Bar) - a.A = 3 - a.F.A = 4 - - if b.A != 1 || b.F.A != 2 { - t.Errorf("deep copy wasn't deep: %#v, %#v", a, b) - } -} - -var result interface{} - -func BenchmarkDeepCopy(b *testing.B) { - table := []interface{}{ - map[string]string{}, - int(5), - "hello world", - struct { - A, B, C struct { - D map[string]int - } - X []int - Y []byte - }{}, - } - - f := fuzz.New().RandSource(rand.NewSource(1)).NilChance(.5).NumElements(0, 100) - for i := range table { - out := table[i] - obj := reflect.New(reflect.TypeOf(out)).Interface() - f.Fuzz(obj) - table[i] = obj - } - - b.ResetTimer() - var r interface{} - for i := 0; i < b.N; i++ { - for j := range table { - r, _ = NewCloner().DeepCopy(table[j]) - } - } - result = r -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/helper_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/helper_test.go deleted file mode 100644 index 69fef3334..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/helper_test.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package conversion - -import "testing" - -func TestInvalidPtrValueKind(t *testing.T) { - var simple interface{} - switch obj := simple.(type) { - default: - _, err := EnforcePtr(obj) - if err == nil { - t.Errorf("Expected error on invalid kind") - } - } -} - -func TestEnforceNilPtr(t *testing.T) { - var nilPtr *struct{} - _, err := EnforcePtr(nilPtr) - if err == nil { - t.Errorf("Expected error on nil pointer") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go index 0f04e7bb4..63c545697 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go @@ -23,6 +23,16 @@ import ( "strings" ) +// Marshaler converts an object to a query parameter string representation +type Marshaler interface { + MarshalQueryParameter() (string, error) +} + +// Unmarshaler converts a string representation to an object +type Unmarshaler interface { + UnmarshalQueryParameter(string) error +} + func jsonTag(field reflect.StructField) (string, bool) { structTag := field.Tag.Get("json") if len(structTag) == 0 { @@ -72,6 +82,31 @@ func zeroValue(value reflect.Value) bool { return reflect.DeepEqual(reflect.Zero(value.Type()).Interface(), value.Interface()) } +func customMarshalValue(value reflect.Value) (reflect.Value, bool) { + // Return unless we implement a custom query marshaler + if !value.CanInterface() { + return reflect.Value{}, false + } + + marshaler, ok := value.Interface().(Marshaler) + if !ok { + return reflect.Value{}, false + } + + // Don't invoke functions on nil pointers + // If the type implements MarshalQueryParameter, AND the tag is not omitempty, AND the value is a nil pointer, "" seems like a reasonable response + if isPointerKind(value.Kind()) && zeroValue(value) { + return reflect.ValueOf(""), true + } + + // Get the custom marshalled value + v, err := marshaler.MarshalQueryParameter() + if err != nil { + return reflect.Value{}, false + } + return reflect.ValueOf(v), true +} + func addParam(values url.Values, tag string, omitempty bool, value reflect.Value) { if omitempty && zeroValue(value) { return @@ -128,7 +163,8 @@ func convertStruct(result url.Values, st reflect.Type, sv reflect.Value) { kind := ft.Kind() if isPointerKind(kind) { - kind = ft.Elem().Kind() + ft = ft.Elem() + kind = ft.Kind() if !field.IsNil() { field = reflect.Indirect(field) } @@ -142,7 +178,11 @@ func convertStruct(result url.Values, st reflect.Type, sv reflect.Value) { addListOfParams(result, tag, omitempty, field) } case isStructKind(kind) && !(zeroValue(field) && omitempty): - convertStruct(result, ft, field) + if marshalValue, ok := customMarshalValue(field); ok { + addParam(result, tag, omitempty, marshalValue) + } else { + convertStruct(result, ft, field) + } } } } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/queryparams/convert_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/queryparams/convert_test.go deleted file mode 100644 index 405357557..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/conversion/queryparams/convert_test.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package queryparams_test - -import ( - "net/url" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/conversion/queryparams" -) - -type namedString string -type namedBool bool - -type bar struct { - Float1 float32 `json:"float1"` - Float2 float64 `json:"float2"` - Int1 int64 `json:"int1,omitempty"` - Int2 int32 `json:"int2,omitempty"` - Int3 int16 `json:"int3,omitempty"` - Str1 string `json:"str1,omitempty"` - Ignored int - Ignored2 string -} - -func (obj *bar) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -type foo struct { - Str string `json:"str"` - Integer int `json:"integer,omitempty"` - Slice []string `json:"slice,omitempty"` - Boolean bool `json:"boolean,omitempty"` - NamedStr namedString `json:"namedStr,omitempty"` - NamedBool namedBool `json:"namedBool,omitempty"` - Foobar bar `json:"foobar,omitempty"` - Testmap map[string]string `json:"testmap,omitempty"` -} - -func (obj *foo) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -type baz struct { - Ptr *int `json:"ptr"` - Bptr *bool `json:"bptr,omitempty"` -} - -func (obj *baz) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -func validateResult(t *testing.T, input interface{}, actual, expected url.Values) { - local := url.Values{} - for k, v := range expected { - local[k] = v - } - for k, v := range actual { - if ev, ok := local[k]; !ok || !reflect.DeepEqual(ev, v) { - if !ok { - t.Errorf("%#v: actual value key %s not found in expected map", input, k) - } else { - t.Errorf("%#v: values don't match: actual: %#v, expected: %#v", input, v, ev) - } - break - } - delete(local, k) - } - if len(local) > 0 { - t.Errorf("%#v: expected map has keys that were not found in actual map: %#v", input, local) - } -} - -func TestConvert(t *testing.T) { - tests := []struct { - input interface{} - expected url.Values - }{ - { - input: &foo{ - Str: "hello", - }, - expected: url.Values{"str": {"hello"}}, - }, - { - input: &foo{ - Str: "test string", - Slice: []string{"one", "two", "three"}, - Integer: 234, - Boolean: true, - }, - expected: url.Values{"str": {"test string"}, "slice": {"one", "two", "three"}, "integer": {"234"}, "boolean": {"true"}}, - }, - { - input: &foo{ - Str: "named types", - NamedStr: "value1", - NamedBool: true, - }, - expected: url.Values{"str": {"named types"}, "namedStr": {"value1"}, "namedBool": {"true"}}, - }, - { - input: &foo{ - Str: "don't ignore embedded struct", - Foobar: bar{ - Float1: 5.0, - }, - }, - expected: url.Values{"str": {"don't ignore embedded struct"}, "float1": {"5"}, "float2": {"0"}}, - }, - { - // Ignore untagged fields - input: &bar{ - Float1: 23.5, - Float2: 100.7, - Int1: 1, - Int2: 2, - Int3: 3, - Ignored: 1, - Ignored2: "ignored", - }, - expected: url.Values{"float1": {"23.5"}, "float2": {"100.7"}, "int1": {"1"}, "int2": {"2"}, "int3": {"3"}}, - }, - { - // include fields that are not tagged omitempty - input: &foo{ - NamedStr: "named str", - }, - expected: url.Values{"str": {""}, "namedStr": {"named str"}}, - }, - { - input: &baz{ - Ptr: intp(5), - Bptr: boolp(true), - }, - expected: url.Values{"ptr": {"5"}, "bptr": {"true"}}, - }, - { - input: &baz{ - Bptr: boolp(true), - }, - expected: url.Values{"ptr": {""}, "bptr": {"true"}}, - }, - { - input: &baz{ - Ptr: intp(5), - }, - expected: url.Values{"ptr": {"5"}}, - }, - } - - for _, test := range tests { - result, err := queryparams.Convert(test.input) - if err != nil { - t.Errorf("Unexpected error while converting %#v: %v", test.input, err) - } - validateResult(t, test.input, result, test.expected) - } -} - -func intp(n int) *int { return &n } - -func boolp(b bool) *bool { return &b } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/OWNERS b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/OWNERS new file mode 100644 index 000000000..766c481bd --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/OWNERS @@ -0,0 +1,3 @@ +assignees: + - erictune + - liggitt diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials.go deleted file mode 100644 index 395c438ed..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials.go +++ /dev/null @@ -1,163 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws_credentials - -import ( - "encoding/base64" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ecr" - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/cloudprovider" - "k8s.io/kubernetes/pkg/credentialprovider" -) - -var registryUrls = []string{"*.dkr.ecr.*.amazonaws.com"} - -// awsHandlerLogger is a handler that logs all AWS SDK requests -// Copied from cloudprovider/aws/log_handler.go -func awsHandlerLogger(req *request.Request) { - service := req.ClientInfo.ServiceName - - name := "?" - if req.Operation != nil { - name = req.Operation.Name - } - - glog.V(4).Infof("AWS request: %s %s", service, name) -} - -// An interface for testing purposes. -type tokenGetter interface { - GetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) -} - -// The canonical implementation -type ecrTokenGetter struct { - svc *ecr.ECR -} - -func (p *ecrTokenGetter) GetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) { - return p.svc.GetAuthorizationToken(input) -} - -// ecrProvider is a DockerConfigProvider that gets and refreshes 12-hour tokens -// from AWS to access ECR. -type ecrProvider struct { - getter tokenGetter -} - -// Not using the package init() function: this module should be initialized only -// if using the AWS cloud provider. This way, we avoid timeouts waiting for a -// non-existent provider. -func Init() { - credentialprovider.RegisterCredentialProvider("aws-ecr-key", - &credentialprovider.CachingDockerConfigProvider{ - Provider: &ecrProvider{}, - // Refresh credentials a little earlier before they expire - Lifetime: 11*time.Hour + 55*time.Minute, - }) -} - -// Enabled implements DockerConfigProvider.Enabled for the AWS token-based implementation. -// For now, it gets activated only if AWS was chosen as the cloud provider. -// TODO: figure how to enable it manually for deployments that are not on AWS but still -// use ECR somehow? -func (p *ecrProvider) Enabled() bool { - provider, err := cloudprovider.GetCloudProvider("aws", nil) - if err != nil { - glog.Errorf("while initializing AWS cloud provider %v", err) - return false - } - if provider == nil { - return false - } - - zones, ok := provider.Zones() - if !ok { - glog.Errorf("couldn't get Zones() interface") - return false - } - zone, err := zones.GetZone() - if err != nil { - glog.Errorf("while getting zone %v", err) - return false - } - if zone.Region == "" { - glog.Errorf("Region information is empty") - return false - } - - getter := &ecrTokenGetter{svc: ecr.New(session.New(&aws.Config{ - Credentials: nil, - Region: &zone.Region, - }))} - getter.svc.Handlers.Sign.PushFrontNamed(request.NamedHandler{ - Name: "k8s/logger", - Fn: awsHandlerLogger, - }) - p.getter = getter - - return true -} - -// Provide implements DockerConfigProvider.Provide, refreshing ECR tokens on demand -func (p *ecrProvider) Provide() credentialprovider.DockerConfig { - cfg := credentialprovider.DockerConfig{} - - // TODO: fill in RegistryIds? - params := &ecr.GetAuthorizationTokenInput{} - output, err := p.getter.GetAuthorizationToken(params) - if err != nil { - glog.Errorf("while requesting ECR authorization token %v", err) - return cfg - } - if output == nil { - glog.Errorf("Got back no ECR token") - return cfg - } - - for _, data := range output.AuthorizationData { - if data.ProxyEndpoint != nil && - data.AuthorizationToken != nil { - decodedToken, err := base64.StdEncoding.DecodeString(aws.StringValue(data.AuthorizationToken)) - if err != nil { - glog.Errorf("while decoding token for endpoint %s %v", data.ProxyEndpoint, err) - return cfg - } - parts := strings.SplitN(string(decodedToken), ":", 2) - user := parts[0] - password := parts[1] - entry := credentialprovider.DockerConfigEntry{ - Username: user, - Password: password, - // ECR doesn't care and Docker is about to obsolete it - Email: "not@val.id", - } - - // Add our entry for each of the supported container registry URLs - for _, k := range registryUrls { - cfg[k] = entry - } - } - } - return cfg -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials_test.go deleted file mode 100644 index a07493993..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials_test.go +++ /dev/null @@ -1,108 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package aws_credentials - -import ( - "encoding/base64" - "fmt" - "path" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ecr" - - "k8s.io/kubernetes/pkg/credentialprovider" -) - -const user = "foo" -const password = "1234567890abcdef" -const email = "not@val.id" - -// Mock implementation -type testTokenGetter struct { - user string - password string - endpoint string -} - -func (p *testTokenGetter) GetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) { - - expiration := time.Now().Add(1 * time.Hour) - creds := []byte(fmt.Sprintf("%s:%s", p.user, p.password)) - data := &ecr.AuthorizationData{ - AuthorizationToken: aws.String(base64.StdEncoding.EncodeToString(creds)), - ExpiresAt: &expiration, - ProxyEndpoint: aws.String(p.endpoint), - } - output := &ecr.GetAuthorizationTokenOutput{ - AuthorizationData: []*ecr.AuthorizationData{data}, - } - - return output, nil //p.svc.GetAuthorizationToken(input) -} - -func TestEcrProvide(t *testing.T) { - registry := "123456789012.dkr.ecr.lala-land-1.amazonaws.com" - otherRegistries := []string{"private.registry.com", - "gcr.io", - } - image := "foo/bar" - - provider := &ecrProvider{ - getter: &testTokenGetter{ - user: user, - password: password, - endpoint: registry}, - } - - keyring := &credentialprovider.BasicDockerKeyring{} - keyring.Add(provider.Provide()) - - // Verify that we get the expected username/password combo for - // an ECR image name. - fullImage := path.Join(registry, image) - creds, ok := keyring.Lookup(fullImage) - if !ok { - t.Errorf("Didn't find expected URL: %s", fullImage) - return - } - if len(creds) > 1 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if user != val.Username { - t.Errorf("Unexpected username value, want: _token, got: %s", val.Username) - } - if password != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", password, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } - - // Verify that we get an error for other images. - for _, otherRegistry := range otherRegistries { - fullImage = path.Join(otherRegistry, image) - creds, ok = keyring.Lookup(fullImage) - if ok { - t.Errorf("Unexpectedly found image: %s", fullImage) - return - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/config_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/config_test.go deleted file mode 100644 index 587879fe9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/config_test.go +++ /dev/null @@ -1,225 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package credentialprovider - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestDockerConfigJsonJSONDecode(t *testing.T) { - input := []byte(`{"auths": {"http://foo.example.com":{"username": "foo", "password": "bar", "email": "foo@example.com"}, "http://bar.example.com":{"username": "bar", "password": "baz", "email": "bar@example.com"}}}`) - - expect := DockerConfigJson{ - Auths: DockerConfig(map[string]DockerConfigEntry{ - "http://foo.example.com": { - Username: "foo", - Password: "bar", - Email: "foo@example.com", - }, - "http://bar.example.com": { - Username: "bar", - Password: "baz", - Email: "bar@example.com", - }, - }), - } - - var output DockerConfigJson - err := json.Unmarshal(input, &output) - if err != nil { - t.Errorf("Received unexpected error: %v", err) - } - - if !reflect.DeepEqual(expect, output) { - t.Errorf("Received unexpected output. Expected %#v, got %#v", expect, output) - } -} - -func TestDockerConfigJSONDecode(t *testing.T) { - input := []byte(`{"http://foo.example.com":{"username": "foo", "password": "bar", "email": "foo@example.com"}, "http://bar.example.com":{"username": "bar", "password": "baz", "email": "bar@example.com"}}`) - - expect := DockerConfig(map[string]DockerConfigEntry{ - "http://foo.example.com": { - Username: "foo", - Password: "bar", - Email: "foo@example.com", - }, - "http://bar.example.com": { - Username: "bar", - Password: "baz", - Email: "bar@example.com", - }, - }) - - var output DockerConfig - err := json.Unmarshal(input, &output) - if err != nil { - t.Errorf("Received unexpected error: %v", err) - } - - if !reflect.DeepEqual(expect, output) { - t.Errorf("Received unexpected output. Expected %#v, got %#v", expect, output) - } -} - -func TestDockerConfigEntryJSONDecode(t *testing.T) { - tests := []struct { - input []byte - expect DockerConfigEntry - fail bool - }{ - // simple case, just decode the fields - { - input: []byte(`{"username": "foo", "password": "bar", "email": "foo@example.com"}`), - expect: DockerConfigEntry{ - Username: "foo", - Password: "bar", - Email: "foo@example.com", - }, - fail: false, - }, - - // auth field decodes to username & password - { - input: []byte(`{"auth": "Zm9vOmJhcg==", "email": "foo@example.com"}`), - expect: DockerConfigEntry{ - Username: "foo", - Password: "bar", - Email: "foo@example.com", - }, - fail: false, - }, - - // auth field overrides username & password - { - input: []byte(`{"username": "foo", "password": "bar", "auth": "cGluZzpwb25n", "email": "foo@example.com"}`), - expect: DockerConfigEntry{ - Username: "ping", - Password: "pong", - Email: "foo@example.com", - }, - fail: false, - }, - - // poorly-formatted auth causes failure - { - input: []byte(`{"auth": "pants", "email": "foo@example.com"}`), - expect: DockerConfigEntry{ - Username: "", - Password: "", - Email: "foo@example.com", - }, - fail: true, - }, - - // invalid JSON causes failure - { - input: []byte(`{"email": false}`), - expect: DockerConfigEntry{ - Username: "", - Password: "", - Email: "", - }, - fail: true, - }, - } - - for i, tt := range tests { - var output DockerConfigEntry - err := json.Unmarshal(tt.input, &output) - if (err != nil) != tt.fail { - t.Errorf("case %d: expected fail=%t, got err=%v", i, tt.fail, err) - } - - if !reflect.DeepEqual(tt.expect, output) { - t.Errorf("case %d: expected output %#v, got %#v", i, tt.expect, output) - } - } -} - -func TestDecodeDockerConfigFieldAuth(t *testing.T) { - tests := []struct { - input string - username string - password string - fail bool - }{ - // auth field decodes to username & password - { - input: "Zm9vOmJhcg==", - username: "foo", - password: "bar", - }, - - // good base64 data, but no colon separating username & password - { - input: "cGFudHM=", - fail: true, - }, - - // bad base64 data - { - input: "pants", - fail: true, - }, - } - - for i, tt := range tests { - username, password, err := decodeDockerConfigFieldAuth(tt.input) - if (err != nil) != tt.fail { - t.Errorf("case %d: expected fail=%t, got err=%v", i, tt.fail, err) - } - - if tt.username != username { - t.Errorf("case %d: expected username %q, got %q", i, tt.username, username) - } - - if tt.password != password { - t.Errorf("case %d: expected password %q, got %q", i, tt.password, password) - } - } -} - -func TestDockerConfigEntryJSONCompatibleEncode(t *testing.T) { - tests := []struct { - input DockerConfigEntry - expect []byte - }{ - // simple case, just decode the fields - { - expect: []byte(`{"username":"foo","password":"bar","email":"foo@example.com","auth":"Zm9vOmJhcg=="}`), - input: DockerConfigEntry{ - Username: "foo", - Password: "bar", - Email: "foo@example.com", - }, - }, - } - - for i, tt := range tests { - actual, err := json.Marshal(tt.input) - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - } - - if string(tt.expect) != string(actual) { - t.Errorf("case %d: expected %v, got %v", i, string(tt.expect), string(actual)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/doc.go deleted file mode 100644 index e6f2beba8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package gcp_credentials contains implementations of DockerConfigProvider -// for Google Cloud Platform. -package gcp_credentials diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt.go deleted file mode 100644 index 3c1a05d4b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package gcp_credentials - -import ( - "io/ioutil" - "time" - - "github.com/golang/glog" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "k8s.io/kubernetes/pkg/credentialprovider" - - "github.com/spf13/pflag" -) - -const ( - storageReadOnlyScope = "https://www.googleapis.com/auth/devstorage.read_only" -) - -var ( - flagJwtFile = pflag.String("google-json-key", "", - "The Google Cloud Platform Service Account JSON Key to use for authentication.") -) - -// A DockerConfigProvider that reads its configuration from Google -// Compute Engine metadata. -type jwtProvider struct { - path *string - config *jwt.Config - tokenUrl string -} - -// init registers the various means by which credentials may -// be resolved on GCP. -func init() { - credentialprovider.RegisterCredentialProvider("google-jwt-key", - &credentialprovider.CachingDockerConfigProvider{ - Provider: &jwtProvider{ - path: flagJwtFile, - }, - Lifetime: 30 * time.Minute, - }) -} - -// Enabled implements DockerConfigProvider for the JSON Key based implementation. -func (j *jwtProvider) Enabled() bool { - if *j.path == "" { - return false - } - - data, err := ioutil.ReadFile(*j.path) - if err != nil { - glog.Errorf("while reading file %s got %v", *j.path, err) - return false - } - config, err := google.JWTConfigFromJSON(data, storageReadOnlyScope) - if err != nil { - glog.Errorf("while parsing %s data got %v", *j.path, err) - return false - } - - j.config = config - if j.tokenUrl != "" { - j.config.TokenURL = j.tokenUrl - } - return true -} - -// Provide implements DockerConfigProvider -func (j *jwtProvider) Provide() credentialprovider.DockerConfig { - cfg := credentialprovider.DockerConfig{} - - ts := j.config.TokenSource(oauth2.NoContext) - token, err := ts.Token() - if err != nil { - glog.Errorf("while exchanging json key %s for access token %v", *j.path, err) - return cfg - } - if !token.Valid() { - glog.Errorf("Got back invalid token: %v", token) - return cfg - } - - entry := credentialprovider.DockerConfigEntry{ - Username: "_token", - Password: token.AccessToken, - Email: j.config.Email, - } - - // Add our entry for each of the supported container registry URLs - for _, k := range containerRegistryUrls { - cfg[k] = entry - } - return cfg -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt_test.go deleted file mode 100644 index 8aa2ad733..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt_test.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package gcp_credentials - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/credentialprovider" -) - -const email = "foo@bar.com" - -// From oauth2/jwt_test.go -var ( - dummyPrivateKey = `-----BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE -DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY -fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK -1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr -k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9 -/E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt -3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn -2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3 -nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK -6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf -5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e -DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1 -M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g -z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y -1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK -J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U -f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx -QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA -cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr -Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw -5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg -KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84 -OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd -mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ -5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg== ------END RSA PRIVATE KEY-----` - - jsonKey = fmt.Sprintf(`{"private_key":"%[1]s", "client_email":"%[2]s"}`, - strings.Replace(dummyPrivateKey, "\n", "\\n", -1), email) -) - -func TestJwtProvider(t *testing.T) { - token := "asdhflkjsdfkjhsdf" - - // Modeled after oauth2/jwt_test.go - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(fmt.Sprintf(`{ - "access_token": "%[1]s", - "scope": "user", - "token_type": "bearer", - "expires_in": 3600 - }`, token))) - })) - // TODO: Uncomment when fix #19254 - // defer ts.Close() - - file, err := ioutil.TempFile(os.TempDir(), "temp") - if err != nil { - t.Fatalf("Error creating temp file: %v", err) - } - - filename := file.Name() - _, err = file.WriteString(jsonKey) - if err != nil { - t.Fatalf("Error writing temp file: %v", err) - } - - provider := &jwtProvider{ - path: &filename, - tokenUrl: ts.URL, - } - if !provider.Enabled() { - t.Fatalf("Provider is unexpectedly disabled") - } - - keyring := &credentialprovider.BasicDockerKeyring{} - keyring.Add(provider.Provide()) - - // Verify that we get the expected username/password combo for - // a gcr.io image name. - registryUrl := "gcr.io/foo/bar" - creds, ok := keyring.Lookup(registryUrl) - if !ok { - t.Errorf("Didn't find expected URL: %s", registryUrl) - return - } - if len(creds) > 1 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if "_token" != val.Username { - t.Errorf("Unexpected username value, want: _token, got: %s", val.Username) - } - if token != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", token, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata.go deleted file mode 100644 index 8ab929315..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata.go +++ /dev/null @@ -1,202 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package gcp_credentials - -import ( - "encoding/json" - "net/http" - "strings" - "time" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/credentialprovider" -) - -const ( - metadataUrl = "http://metadata.google.internal./computeMetadata/v1/" - metadataAttributes = metadataUrl + "instance/attributes/" - dockerConfigKey = metadataAttributes + "google-dockercfg" - dockerConfigUrlKey = metadataAttributes + "google-dockercfg-url" - metadataScopes = metadataUrl + "instance/service-accounts/default/scopes" - metadataToken = metadataUrl + "instance/service-accounts/default/token" - metadataEmail = metadataUrl + "instance/service-accounts/default/email" - storageScopePrefix = "https://www.googleapis.com/auth/devstorage" - cloudPlatformScopePrefix = "https://www.googleapis.com/auth/cloud-platform" -) - -// For these urls, the parts of the host name can be glob, for example '*.gcr.io" will match -// "foo.gcr.io" and "bar.gcr.io". -var containerRegistryUrls = []string{"container.cloud.google.com", "gcr.io", "*.gcr.io"} - -var metadataHeader = &http.Header{ - "Metadata-Flavor": []string{"Google"}, -} - -// A DockerConfigProvider that reads its configuration from Google -// Compute Engine metadata. -type metadataProvider struct { - Client *http.Client -} - -// A DockerConfigProvider that reads its configuration from a specific -// Google Compute Engine metadata key: 'google-dockercfg'. -type dockerConfigKeyProvider struct { - metadataProvider -} - -// A DockerConfigProvider that reads its configuration from a URL read from -// a specific Google Compute Engine metadata key: 'google-dockercfg-url'. -type dockerConfigUrlKeyProvider struct { - metadataProvider -} - -// A DockerConfigProvider that provides a dockercfg with: -// Username: "_token" -// Password: "{access token from metadata}" -type containerRegistryProvider struct { - metadataProvider -} - -// init registers the various means by which credentials may -// be resolved on GCP. -func init() { - credentialprovider.RegisterCredentialProvider("google-dockercfg", - &credentialprovider.CachingDockerConfigProvider{ - Provider: &dockerConfigKeyProvider{ - metadataProvider{Client: http.DefaultClient}, - }, - Lifetime: 60 * time.Second, - }) - - credentialprovider.RegisterCredentialProvider("google-dockercfg-url", - &credentialprovider.CachingDockerConfigProvider{ - Provider: &dockerConfigUrlKeyProvider{ - metadataProvider{Client: http.DefaultClient}, - }, - Lifetime: 60 * time.Second, - }) - - credentialprovider.RegisterCredentialProvider("google-container-registry", - // Never cache this. The access token is already - // cached by the metadata service. - &containerRegistryProvider{ - metadataProvider{Client: http.DefaultClient}, - }) -} - -// Enabled implements DockerConfigProvider for all of the Google implementations. -func (g *metadataProvider) Enabled() bool { - _, err := credentialprovider.ReadUrl(metadataUrl, g.Client, metadataHeader) - return err == nil -} - -// Provide implements DockerConfigProvider -func (g *dockerConfigKeyProvider) Provide() credentialprovider.DockerConfig { - // Read the contents of the google-dockercfg metadata key and - // parse them as an alternate .dockercfg - if cfg, err := credentialprovider.ReadDockerConfigFileFromUrl(dockerConfigKey, g.Client, metadataHeader); err != nil { - glog.Errorf("while reading 'google-dockercfg' metadata: %v", err) - } else { - return cfg - } - - return credentialprovider.DockerConfig{} -} - -// Provide implements DockerConfigProvider -func (g *dockerConfigUrlKeyProvider) Provide() credentialprovider.DockerConfig { - // Read the contents of the google-dockercfg-url key and load a .dockercfg from there - if url, err := credentialprovider.ReadUrl(dockerConfigUrlKey, g.Client, metadataHeader); err != nil { - glog.Errorf("while reading 'google-dockercfg-url' metadata: %v", err) - } else { - if strings.HasPrefix(string(url), "http") { - if cfg, err := credentialprovider.ReadDockerConfigFileFromUrl(string(url), g.Client, nil); err != nil { - glog.Errorf("while reading 'google-dockercfg-url'-specified url: %s, %v", string(url), err) - } else { - return cfg - } - } else { - // TODO(mattmoor): support reading alternate scheme URLs (e.g. gs:// or s3://) - glog.Errorf("Unsupported URL scheme: %s", string(url)) - } - } - - return credentialprovider.DockerConfig{} -} - -// Enabled implements a special metadata-based check, which verifies the -// storage scope is available on the GCE VM. -func (g *containerRegistryProvider) Enabled() bool { - value, err := credentialprovider.ReadUrl(metadataScopes+"?alt=json", g.Client, metadataHeader) - if err != nil { - return false - } - var scopes []string - if err := json.Unmarshal([]byte(value), &scopes); err != nil { - return false - } - - for _, v := range scopes { - // cloudPlatformScope implies storage scope. - if strings.HasPrefix(v, storageScopePrefix) || strings.HasPrefix(v, cloudPlatformScopePrefix) { - return true - } - } - glog.Warningf("Google container registry is disabled, no storage scope is available: %s", value) - return false -} - -// tokenBlob is used to decode the JSON blob containing an access token -// that is returned by GCE metadata. -type tokenBlob struct { - AccessToken string `json:"access_token"` -} - -// Provide implements DockerConfigProvider -func (g *containerRegistryProvider) Provide() credentialprovider.DockerConfig { - cfg := credentialprovider.DockerConfig{} - - tokenJsonBlob, err := credentialprovider.ReadUrl(metadataToken, g.Client, metadataHeader) - if err != nil { - glog.Errorf("while reading access token endpoint: %v", err) - return cfg - } - - email, err := credentialprovider.ReadUrl(metadataEmail, g.Client, metadataHeader) - if err != nil { - glog.Errorf("while reading email endpoint: %v", err) - return cfg - } - - var parsedBlob tokenBlob - if err := json.Unmarshal([]byte(tokenJsonBlob), &parsedBlob); err != nil { - glog.Errorf("while parsing json blob %s: %v", tokenJsonBlob, err) - return cfg - } - - entry := credentialprovider.DockerConfigEntry{ - Username: "_token", - Password: parsedBlob.AccessToken, - Email: string(email), - } - - // Add our entry for each of the supported container registry URLs - for _, k := range containerRegistryUrls { - cfg[k] = entry - } - return cfg -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata_test.go deleted file mode 100644 index 5da1bcd3b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata_test.go +++ /dev/null @@ -1,347 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package gcp_credentials - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/credentialprovider" -) - -func TestDockerKeyringFromGoogleDockerConfigMetadata(t *testing.T) { - registryUrl := "hello.kubernetes.io" - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, registryUrl, email, auth) - - const probeEndpoint = "/computeMetadata/v1/" - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Only serve the one metadata key. - if probeEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - } else if strings.HasSuffix(dockerConfigKey, r.URL.Path) { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - fmt.Fprintln(w, sampleDockerConfig) - } else { - w.WriteHeader(http.StatusNotFound) - } - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - // Make a transport that reroutes all traffic to the example server - transport := &http.Transport{ - Proxy: func(req *http.Request) (*url.URL, error) { - return url.Parse(server.URL + req.URL.Path) - }, - } - - keyring := &credentialprovider.BasicDockerKeyring{} - provider := &dockerConfigKeyProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - } - - if !provider.Enabled() { - t.Errorf("Provider is unexpectedly disabled") - } - - keyring.Add(provider.Provide()) - - creds, ok := keyring.Lookup(registryUrl) - if !ok { - t.Errorf("Didn't find expected URL: %s", registryUrl) - return - } - if len(creds) > 1 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if username != val.Username { - t.Errorf("Unexpected username value, want: %s, got: %s", username, val.Username) - } - if password != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", password, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } -} - -func TestDockerKeyringFromGoogleDockerConfigMetadataUrl(t *testing.T) { - registryUrl := "hello.kubernetes.io" - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, registryUrl, email, auth) - - const probeEndpoint = "/computeMetadata/v1/" - const valueEndpoint = "/my/value" - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Only serve the URL key and the value endpoint - if probeEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - } else if valueEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - fmt.Fprintln(w, sampleDockerConfig) - } else if strings.HasSuffix(dockerConfigUrlKey, r.URL.Path) { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/text") - fmt.Fprint(w, "http://foo.bar.com"+valueEndpoint) - } else { - w.WriteHeader(http.StatusNotFound) - } - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - // Make a transport that reroutes all traffic to the example server - transport := &http.Transport{ - Proxy: func(req *http.Request) (*url.URL, error) { - return url.Parse(server.URL + req.URL.Path) - }, - } - - keyring := &credentialprovider.BasicDockerKeyring{} - provider := &dockerConfigUrlKeyProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - } - - if !provider.Enabled() { - t.Errorf("Provider is unexpectedly disabled") - } - - keyring.Add(provider.Provide()) - - creds, ok := keyring.Lookup(registryUrl) - if !ok { - t.Errorf("Didn't find expected URL: %s", registryUrl) - return - } - if len(creds) > 1 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if username != val.Username { - t.Errorf("Unexpected username value, want: %s, got: %s", username, val.Username) - } - if password != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", password, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } -} - -func TestContainerRegistryBasics(t *testing.T) { - registryUrl := "container.cloud.google.com" - email := "1234@project.gserviceaccount.com" - token := &tokenBlob{AccessToken: "ya26.lots-of-indiscernible-garbage"} - - const ( - defaultEndpoint = "/computeMetadata/v1/instance/service-accounts/default/" - scopeEndpoint = defaultEndpoint + "scopes" - emailEndpoint = defaultEndpoint + "email" - tokenEndpoint = defaultEndpoint + "token" - ) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Only serve the URL key and the value endpoint - if scopeEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, `["%s.read_write"]`, storageScopePrefix) - } else if emailEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, email) - } else if tokenEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - bytes, err := json.Marshal(token) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - fmt.Fprintln(w, string(bytes)) - } else { - w.WriteHeader(http.StatusNotFound) - } - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - // Make a transport that reroutes all traffic to the example server - transport := &http.Transport{ - Proxy: func(req *http.Request) (*url.URL, error) { - return url.Parse(server.URL + req.URL.Path) - }, - } - - keyring := &credentialprovider.BasicDockerKeyring{} - provider := &containerRegistryProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - } - - if !provider.Enabled() { - t.Errorf("Provider is unexpectedly disabled") - } - - keyring.Add(provider.Provide()) - - creds, ok := keyring.Lookup(registryUrl) - if !ok { - t.Errorf("Didn't find expected URL: %s", registryUrl) - return - } - if len(creds) > 1 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if "_token" != val.Username { - t.Errorf("Unexpected username value, want: %s, got: %s", "_token", val.Username) - } - if token.AccessToken != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", token.AccessToken, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } -} - -func TestContainerRegistryNoStorageScope(t *testing.T) { - const ( - defaultEndpoint = "/computeMetadata/v1/instance/service-accounts/default/" - scopeEndpoint = defaultEndpoint + "scopes" - ) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Only serve the URL key and the value endpoint - if scopeEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `["https://www.googleapis.com/auth/compute.read_write"]`) - } else { - w.WriteHeader(http.StatusNotFound) - } - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - // Make a transport that reroutes all traffic to the example server - transport := &http.Transport{ - Proxy: func(req *http.Request) (*url.URL, error) { - return url.Parse(server.URL + req.URL.Path) - }, - } - - provider := &containerRegistryProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - } - - if provider.Enabled() { - t.Errorf("Provider is unexpectedly enabled") - } -} - -func TestComputePlatformScopeSubstitutesStorageScope(t *testing.T) { - const ( - defaultEndpoint = "/computeMetadata/v1/instance/service-accounts/default/" - scopeEndpoint = defaultEndpoint + "scopes" - ) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Only serve the URL key and the value endpoint - if scopeEndpoint == r.URL.Path { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `["https://www.googleapis.com/auth/compute.read_write","https://www.googleapis.com/auth/cloud-platform.read-only"]`) - } else { - w.WriteHeader(http.StatusNotFound) - } - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - // Make a transport that reroutes all traffic to the example server - transport := &http.Transport{ - Proxy: func(req *http.Request) (*url.URL, error) { - return url.Parse(server.URL + req.URL.Path) - }, - } - - provider := &containerRegistryProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - } - - if !provider.Enabled() { - t.Errorf("Provider is unexpectedly disabled") - } -} - -func TestAllProvidersNoMetadata(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotFound) - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - // Make a transport that reroutes all traffic to the example server - transport := &http.Transport{ - Proxy: func(req *http.Request) (*url.URL, error) { - return url.Parse(server.URL + req.URL.Path) - }, - } - - providers := []credentialprovider.DockerConfigProvider{ - &dockerConfigKeyProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - }, - &dockerConfigUrlKeyProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - }, - &containerRegistryProvider{ - metadataProvider{Client: &http.Client{Transport: transport}}, - }, - } - - for _, provider := range providers { - if provider.Enabled() { - t.Errorf("Provider %s is unexpectedly enabled", reflect.TypeOf(provider).String()) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/keyring.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/keyring.go index 0ea079aee..2378156dc 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/keyring.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/keyring.go @@ -67,7 +67,11 @@ func (dk *BasicDockerKeyring) Add(cfg DockerConfig) { Email: ident.Email, } - parsed, err := url.Parse(loc) + value := loc + if !strings.HasPrefix(value, "https://") && !strings.HasPrefix(value, "http://") { + value = "https://" + value + } + parsed, err := url.Parse(value) if err != nil { glog.Errorf("Entry %q in dockercfg invalid (%v), ignoring", loc, err) continue @@ -77,17 +81,20 @@ func (dk *BasicDockerKeyring) Add(cfg DockerConfig) { // foo.bar.com/namespace // Or hostname matches: // foo.bar.com + // It also considers /v2/ and /v1/ equivalent to the hostname // See ResolveAuthConfig in docker/registry/auth.go. - if parsed.Host != "" { - // NOTE: foo.bar.com comes through as Path. - dk.creds[parsed.Host] = append(dk.creds[parsed.Host], creds) - dk.index = append(dk.index, parsed.Host) + effectivePath := parsed.Path + if strings.HasPrefix(effectivePath, "/v2/") || strings.HasPrefix(effectivePath, "/v1/") { + effectivePath = effectivePath[3:] } - if (len(parsed.Path) > 0) && (parsed.Path != "/") { - key := parsed.Host + parsed.Path - dk.creds[key] = append(dk.creds[key], creds) - dk.index = append(dk.index, key) + var key string + if (len(effectivePath) > 0) && (effectivePath != "/") { + key = parsed.Host + effectivePath + } else { + key = parsed.Host } + dk.creds[key] = append(dk.creds[key], creds) + dk.index = append(dk.index, key) } eliminateDupes := sets.NewString(dk.index...) @@ -100,7 +107,10 @@ func (dk *BasicDockerKeyring) Add(cfg DockerConfig) { sort.Sort(sort.Reverse(sort.StringSlice(dk.index))) } -const defaultRegistryHost = "index.docker.io/v1/" +const ( + defaultRegistryHost = "index.docker.io" + defaultRegistryKey = defaultRegistryHost + "/v1/" +) // isDefaultRegistryMatch determines whether the given image will // pull from the default registry (DockerHub) based on the @@ -223,8 +233,10 @@ func (dk *BasicDockerKeyring) Lookup(image string) ([]docker.AuthConfiguration, } // Use credentials for the default registry if provided, and appropriate - if auth, ok := dk.creds[defaultRegistryHost]; ok && isDefaultRegistryMatch(image) { - return auth, true + if isDefaultRegistryMatch(image) { + if auth, ok := dk.creds[defaultRegistryHost]; ok { + return auth, true + } } return []docker.AuthConfiguration{}, false diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/keyring_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/keyring_test.go deleted file mode 100644 index cd92d79b2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/keyring_test.go +++ /dev/null @@ -1,476 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package credentialprovider - -import ( - "encoding/base64" - "fmt" - "testing" -) - -func TestUrlsMatch(t *testing.T) { - tests := []struct { - globUrl string - targetUrl string - matchExpected bool - }{ - // match when there is no path component - { - globUrl: "*.kubernetes.io", - targetUrl: "prefix.kubernetes.io", - matchExpected: true, - }, - { - globUrl: "prefix.*.io", - targetUrl: "prefix.kubernetes.io", - matchExpected: true, - }, - { - globUrl: "prefix.kubernetes.*", - targetUrl: "prefix.kubernetes.io", - matchExpected: true, - }, - { - globUrl: "*-good.kubernetes.io", - targetUrl: "prefix-good.kubernetes.io", - matchExpected: true, - }, - // match with path components - { - globUrl: "*.kubernetes.io/blah", - targetUrl: "prefix.kubernetes.io/blah", - matchExpected: true, - }, - { - globUrl: "prefix.*.io/foo", - targetUrl: "prefix.kubernetes.io/foo/bar", - matchExpected: true, - }, - // match with path components and ports - { - globUrl: "*.kubernetes.io:1111/blah", - targetUrl: "prefix.kubernetes.io:1111/blah", - matchExpected: true, - }, - { - globUrl: "prefix.*.io:1111/foo", - targetUrl: "prefix.kubernetes.io:1111/foo/bar", - matchExpected: true, - }, - // no match when number of parts mismatch - { - globUrl: "*.kubernetes.io", - targetUrl: "kubernetes.io", - matchExpected: false, - }, - { - globUrl: "*.*.kubernetes.io", - targetUrl: "prefix.kubernetes.io", - matchExpected: false, - }, - { - globUrl: "*.*.kubernetes.io", - targetUrl: "kubernetes.io", - matchExpected: false, - }, - // no match when some parts mismatch - { - globUrl: "kubernetes.io", - targetUrl: "kubernetes.com", - matchExpected: false, - }, - { - globUrl: "k*.io", - targetUrl: "quay.io", - matchExpected: false, - }, - // no match when ports mismatch - { - globUrl: "*.kubernetes.io:1234/blah", - targetUrl: "prefix.kubernetes.io:1111/blah", - matchExpected: false, - }, - { - globUrl: "prefix.*.io/foo", - targetUrl: "prefix.kubernetes.io:1111/foo/bar", - matchExpected: false, - }, - } - for _, test := range tests { - matched, _ := urlsMatchStr(test.globUrl, test.targetUrl) - if matched != test.matchExpected { - t.Errorf("Expected match result of %s and %s to be %t, but was %t", - test.globUrl, test.targetUrl, test.matchExpected, matched) - } - } -} - -func TestDockerKeyringForGlob(t *testing.T) { - tests := []struct { - globUrl string - targetUrl string - }{ - { - globUrl: "hello.kubernetes.io", - targetUrl: "hello.kubernetes.io", - }, - { - globUrl: "*.docker.io", - targetUrl: "prefix.docker.io", - }, - { - globUrl: "prefix.*.io", - targetUrl: "prefix.docker.io", - }, - { - globUrl: "prefix.docker.*", - targetUrl: "prefix.docker.io", - }, - { - globUrl: "*.docker.io/path", - targetUrl: "prefix.docker.io/path", - }, - { - globUrl: "prefix.*.io/path", - targetUrl: "prefix.docker.io/path/subpath", - }, - { - globUrl: "prefix.docker.*/path", - targetUrl: "prefix.docker.io/path", - }, - { - globUrl: "*.docker.io:8888", - targetUrl: "prefix.docker.io:8888", - }, - { - globUrl: "prefix.*.io:8888", - targetUrl: "prefix.docker.io:8888", - }, - { - globUrl: "prefix.docker.*:8888", - targetUrl: "prefix.docker.io:8888", - }, - { - globUrl: "*.docker.io/path:1111", - targetUrl: "prefix.docker.io/path:1111", - }, - { - globUrl: "prefix.*.io/path:1111", - targetUrl: "prefix.docker.io/path/subpath:1111", - }, - { - globUrl: "prefix.docker.*/path:1111", - targetUrl: "prefix.docker.io/path:1111", - }, - } - for _, test := range tests { - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, test.globUrl, email, auth) - - keyring := &BasicDockerKeyring{} - if cfg, err := readDockerConfigFileFromBytes([]byte(sampleDockerConfig)); err != nil { - t.Errorf("Error processing json blob %q, %v", sampleDockerConfig, err) - } else { - keyring.Add(cfg) - } - - creds, ok := keyring.Lookup(test.targetUrl + "/foo/bar") - if !ok { - t.Errorf("Didn't find expected URL: %s", test.targetUrl) - return - } - val := creds[0] - - if username != val.Username { - t.Errorf("Unexpected username value, want: %s, got: %s", username, val.Username) - } - if password != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", password, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } - } -} - -func TestKeyringMiss(t *testing.T) { - tests := []struct { - globUrl string - lookupUrl string - }{ - { - globUrl: "hello.kubernetes.io", - lookupUrl: "world.mesos.org/foo/bar", - }, - { - globUrl: "*.docker.com", - lookupUrl: "prefix.docker.io", - }, - { - globUrl: "suffix.*.io", - lookupUrl: "prefix.docker.io", - }, - { - globUrl: "prefix.docker.c*", - lookupUrl: "prefix.docker.io", - }, - } - for _, test := range tests { - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, test.globUrl, email, auth) - - keyring := &BasicDockerKeyring{} - if cfg, err := readDockerConfigFileFromBytes([]byte(sampleDockerConfig)); err != nil { - t.Errorf("Error processing json blob %q, %v", sampleDockerConfig, err) - } else { - keyring.Add(cfg) - } - - _, ok := keyring.Lookup(test.lookupUrl + "/foo/bar") - if ok { - t.Errorf("Expected not to find URL %s, but found", test.lookupUrl) - } - } - -} - -func TestKeyringMissWithDockerHubCredentials(t *testing.T) { - url := defaultRegistryHost - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, url, email, auth) - - keyring := &BasicDockerKeyring{} - if cfg, err := readDockerConfigFileFromBytes([]byte(sampleDockerConfig)); err != nil { - t.Errorf("Error processing json blob %q, %v", sampleDockerConfig, err) - } else { - keyring.Add(cfg) - } - - val, ok := keyring.Lookup("world.mesos.org/foo/bar") - if ok { - t.Errorf("Found unexpected credential: %+v", val) - } -} - -func TestKeyringHitWithUnqualifiedDockerHub(t *testing.T) { - url := defaultRegistryHost - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, url, email, auth) - - keyring := &BasicDockerKeyring{} - if cfg, err := readDockerConfigFileFromBytes([]byte(sampleDockerConfig)); err != nil { - t.Errorf("Error processing json blob %q, %v", sampleDockerConfig, err) - } else { - keyring.Add(cfg) - } - - creds, ok := keyring.Lookup("google/docker-registry") - if !ok { - t.Errorf("Didn't find expected URL: %s", url) - return - } - if len(creds) > 1 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if username != val.Username { - t.Errorf("Unexpected username value, want: %s, got: %s", username, val.Username) - } - if password != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", password, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } -} - -func TestKeyringHitWithUnqualifiedLibraryDockerHub(t *testing.T) { - url := defaultRegistryHost - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, url, email, auth) - - keyring := &BasicDockerKeyring{} - if cfg, err := readDockerConfigFileFromBytes([]byte(sampleDockerConfig)); err != nil { - t.Errorf("Error processing json blob %q, %v", sampleDockerConfig, err) - } else { - keyring.Add(cfg) - } - - creds, ok := keyring.Lookup("jenkins") - if !ok { - t.Errorf("Didn't find expected URL: %s", url) - return - } - if len(creds) > 1 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if username != val.Username { - t.Errorf("Unexpected username value, want: %s, got: %s", username, val.Username) - } - if password != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", password, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } -} - -func TestKeyringHitWithQualifiedDockerHub(t *testing.T) { - url := defaultRegistryHost - email := "foo@bar.baz" - username := "foo" - password := "bar" - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) - sampleDockerConfig := fmt.Sprintf(`{ - "https://%s": { - "email": %q, - "auth": %q - } -}`, url, email, auth) - - keyring := &BasicDockerKeyring{} - if cfg, err := readDockerConfigFileFromBytes([]byte(sampleDockerConfig)); err != nil { - t.Errorf("Error processing json blob %q, %v", sampleDockerConfig, err) - } else { - keyring.Add(cfg) - } - - creds, ok := keyring.Lookup(url + "/google/docker-registry") - if !ok { - t.Errorf("Didn't find expected URL: %s", url) - return - } - if len(creds) > 2 { - t.Errorf("Got more hits than expected: %s", creds) - } - val := creds[0] - - if username != val.Username { - t.Errorf("Unexpected username value, want: %s, got: %s", username, val.Username) - } - if password != val.Password { - t.Errorf("Unexpected password value, want: %s, got: %s", password, val.Password) - } - if email != val.Email { - t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) - } -} - -func TestIsDefaultRegistryMatch(t *testing.T) { - samples := []map[bool]string{ - {true: "foo/bar"}, - {true: "docker.io/foo/bar"}, - {true: "index.docker.io/foo/bar"}, - {true: "foo"}, - {false: ""}, - {false: "registry.tld/foo/bar"}, - {false: "registry:5000/foo/bar"}, - {false: "myhostdocker.io/foo/bar"}, - } - for _, sample := range samples { - for expected, imageName := range sample { - if got := isDefaultRegistryMatch(imageName); got != expected { - t.Errorf("Expected '%s' to be %t, got %t", imageName, expected, got) - } - } - } -} - -type testProvider struct { - Count int -} - -// Enabled implements dockerConfigProvider -func (d *testProvider) Enabled() bool { - return true -} - -// Provide implements dockerConfigProvider -func (d *testProvider) Provide() DockerConfig { - d.Count += 1 - return DockerConfig{} -} - -func TestLazyKeyring(t *testing.T) { - provider := &testProvider{ - Count: 0, - } - lazy := &lazyDockerKeyring{ - Providers: []DockerConfigProvider{ - provider, - }, - } - - if provider.Count != 0 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } - lazy.Lookup("foo") - if provider.Count != 1 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } - lazy.Lookup("foo") - if provider.Count != 2 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } - lazy.Lookup("foo") - if provider.Count != 3 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/provider_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/provider_test.go deleted file mode 100644 index 099d839fb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/credentialprovider/provider_test.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package credentialprovider - -import ( - "testing" - "time" -) - -func TestCachingProvider(t *testing.T) { - provider := &testProvider{ - Count: 0, - } - - cache := &CachingDockerConfigProvider{ - Provider: provider, - Lifetime: 1 * time.Second, - } - - if provider.Count != 0 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } - cache.Provide() - cache.Provide() - cache.Provide() - cache.Provide() - if provider.Count != 1 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } - - time.Sleep(cache.Lifetime) - cache.Provide() - cache.Provide() - cache.Provide() - cache.Provide() - if provider.Count != 2 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } - - time.Sleep(cache.Lifetime) - cache.Provide() - cache.Provide() - cache.Provide() - cache.Provide() - if provider.Count != 3 { - t.Errorf("Unexpected number of Provide calls: %v", provider.Count) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fieldpath/fieldpath_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fieldpath/fieldpath_test.go deleted file mode 100644 index d510426ee..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fieldpath/fieldpath_test.go +++ /dev/null @@ -1,117 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package fieldpath - -import ( - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -func TestExtractFieldPathAsString(t *testing.T) { - cases := []struct { - name string - fieldPath string - obj interface{} - expectedValue string - expectedMessageFragment string - }{ - { - name: "not an API object", - fieldPath: "metadata.name", - obj: "", - expectedMessageFragment: "expected struct", - }, - { - name: "ok - namespace", - fieldPath: "metadata.namespace", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Namespace: "object-namespace", - }, - }, - expectedValue: "object-namespace", - }, - { - name: "ok - name", - fieldPath: "metadata.name", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "object-name", - }, - }, - expectedValue: "object-name", - }, - { - name: "ok - labels", - fieldPath: "metadata.labels", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"key": "value"}, - }, - }, - expectedValue: "key=\"value\"\n", - }, - { - name: "ok - labels bslash n", - fieldPath: "metadata.labels", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"key": "value\n"}, - }, - }, - expectedValue: "key=\"value\\n\"\n", - }, - { - name: "ok - annotations", - fieldPath: "metadata.annotations", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"builder": "john-doe"}, - }, - }, - expectedValue: "builder=\"john-doe\"\n", - }, - - { - name: "invalid expression", - fieldPath: "metadata.whoops", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Namespace: "object-namespace", - }, - }, - expectedMessageFragment: "Unsupported fieldPath", - }, - } - - for _, tc := range cases { - actual, err := ExtractFieldPathAsString(tc.obj, tc.fieldPath) - if err != nil { - if tc.expectedMessageFragment != "" { - if !strings.Contains(err.Error(), tc.expectedMessageFragment) { - t.Errorf("%v: Unexpected error message: %q, expected to contain %q", tc.name, err, tc.expectedMessageFragment) - } - } else { - t.Errorf("%v: unexpected error: %v", tc.name, err) - } - } else if e := tc.expectedValue; e != "" && e != actual { - t.Errorf("%v: Unexpected result; got %q, expected %q", tc.name, actual, e) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fields/fields_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fields/fields_test.go deleted file mode 100644 index 9f6f3fc35..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fields/fields_test.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package fields - -import ( - "testing" -) - -func matches(t *testing.T, ls Set, want string) { - if ls.String() != want { - t.Errorf("Expected '%s', but got '%s'", want, ls.String()) - } -} - -func TestSetString(t *testing.T) { - matches(t, Set{"x": "y"}, "x=y") - matches(t, Set{"foo": "bar"}, "foo=bar") - matches(t, Set{"foo": "bar", "baz": "qup"}, "baz=qup,foo=bar") -} - -func TestFieldHas(t *testing.T) { - fieldHasTests := []struct { - Ls Fields - Key string - Has bool - }{ - {Set{"x": "y"}, "x", true}, - {Set{"x": ""}, "x", true}, - {Set{"x": "y"}, "foo", false}, - } - for _, lh := range fieldHasTests { - if has := lh.Ls.Has(lh.Key); has != lh.Has { - t.Errorf("%#v.Has(%#v) => %v, expected %v", lh.Ls, lh.Key, has, lh.Has) - } - } -} - -func TestFieldGet(t *testing.T) { - ls := Set{"x": "y"} - if ls.Get("x") != "y" { - t.Errorf("Set.Get is broken") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fields/selector_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fields/selector_test.go deleted file mode 100644 index 7651ae6bb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/fields/selector_test.go +++ /dev/null @@ -1,208 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package fields - -import ( - "testing" -) - -func TestSelectorParse(t *testing.T) { - testGoodStrings := []string{ - "x=a,y=b,z=c", - "", - "x!=a,y=b", - } - testBadStrings := []string{ - "x=a||y=b", - "x==a==b", - } - for _, test := range testGoodStrings { - lq, err := ParseSelector(test) - if err != nil { - t.Errorf("%v: error %v (%#v)\n", test, err, err) - } - if test != lq.String() { - t.Errorf("%v restring gave: %v\n", test, lq.String()) - } - } - for _, test := range testBadStrings { - _, err := ParseSelector(test) - if err == nil { - t.Errorf("%v: did not get expected error\n", test) - } - } -} - -func TestDeterministicParse(t *testing.T) { - s1, err := ParseSelector("x=a,a=x") - s2, err2 := ParseSelector("a=x,x=a") - if err != nil || err2 != nil { - t.Errorf("Unexpected parse error") - } - if s1.String() != s2.String() { - t.Errorf("Non-deterministic parse") - } -} - -func expectMatch(t *testing.T, selector string, ls Set) { - lq, err := ParseSelector(selector) - if err != nil { - t.Errorf("Unable to parse %v as a selector\n", selector) - return - } - if !lq.Matches(ls) { - t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls) - } -} - -func expectNoMatch(t *testing.T, selector string, ls Set) { - lq, err := ParseSelector(selector) - if err != nil { - t.Errorf("Unable to parse %v as a selector\n", selector) - return - } - if lq.Matches(ls) { - t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) - } -} - -func TestEverything(t *testing.T) { - if !Everything().Matches(Set{"x": "y"}) { - t.Errorf("Nil selector didn't match") - } - if !Everything().Empty() { - t.Errorf("Everything was not empty") - } -} - -func TestSelectorMatches(t *testing.T) { - expectMatch(t, "", Set{"x": "y"}) - expectMatch(t, "x=y", Set{"x": "y"}) - expectMatch(t, "x=y,z=w", Set{"x": "y", "z": "w"}) - expectMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "a"}) - expectMatch(t, "notin=in", Set{"notin": "in"}) // in and notin in exactMatch - expectNoMatch(t, "x=y", Set{"x": "z"}) - expectNoMatch(t, "x=y,z=w", Set{"x": "w", "z": "w"}) - expectNoMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "w"}) - - labelset := Set{ - "foo": "bar", - "baz": "blah", - } - expectMatch(t, "foo=bar", labelset) - expectMatch(t, "baz=blah", labelset) - expectMatch(t, "foo=bar,baz=blah", labelset) - expectNoMatch(t, "foo=blah", labelset) - expectNoMatch(t, "baz=bar", labelset) - expectNoMatch(t, "foo=bar,foobar=bar,baz=blah", labelset) -} - -func TestOneTermEqualSelector(t *testing.T) { - if !OneTermEqualSelector("x", "y").Matches(Set{"x": "y"}) { - t.Errorf("No match when match expected.") - } - if OneTermEqualSelector("x", "y").Matches(Set{"x": "z"}) { - t.Errorf("Match when none expected.") - } -} - -func expectMatchDirect(t *testing.T, selector, ls Set) { - if !SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls) - } -} - -func expectNoMatchDirect(t *testing.T, selector, ls Set) { - if SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) - } -} - -func TestSetMatches(t *testing.T) { - labelset := Set{ - "foo": "bar", - "baz": "blah", - } - expectMatchDirect(t, Set{}, labelset) - expectMatchDirect(t, Set{"foo": "bar"}, labelset) - expectMatchDirect(t, Set{"baz": "blah"}, labelset) - expectMatchDirect(t, Set{"foo": "bar", "baz": "blah"}, labelset) - expectNoMatchDirect(t, Set{"foo": "=blah"}, labelset) - expectNoMatchDirect(t, Set{"baz": "=bar"}, labelset) - expectNoMatchDirect(t, Set{"foo": "=bar", "foobar": "bar", "baz": "blah"}, labelset) -} - -func TestNilMapIsValid(t *testing.T) { - selector := Set(nil).AsSelector() - if selector == nil { - t.Errorf("Selector for nil set should be Everything") - } - if !selector.Empty() { - t.Errorf("Selector for nil set should be Empty") - } -} - -func TestSetIsEmpty(t *testing.T) { - if !(Set{}).AsSelector().Empty() { - t.Errorf("Empty set should be empty") - } - if !(andTerm(nil)).Empty() { - t.Errorf("Nil andTerm should be empty") - } - if (&hasTerm{}).Empty() { - t.Errorf("hasTerm should not be empty") - } - if (¬HasTerm{}).Empty() { - t.Errorf("notHasTerm should not be empty") - } - if !(andTerm{andTerm{}}).Empty() { - t.Errorf("Nested andTerm should be empty") - } - if (andTerm{&hasTerm{"a", "b"}}).Empty() { - t.Errorf("Nested andTerm should not be empty") - } -} - -func TestRequiresExactMatch(t *testing.T) { - testCases := map[string]struct { - S Selector - Label string - Value string - Found bool - }{ - "empty set": {Set{}.AsSelector(), "test", "", false}, - "nil andTerm": {andTerm(nil), "test", "", false}, - "empty hasTerm": {&hasTerm{}, "test", "", false}, - "skipped hasTerm": {&hasTerm{"a", "b"}, "test", "", false}, - "valid hasTerm": {&hasTerm{"test", "b"}, "test", "b", true}, - "valid hasTerm no value": {&hasTerm{"test", ""}, "test", "", true}, - "valid notHasTerm": {¬HasTerm{"test", "b"}, "test", "", false}, - "valid notHasTerm no value": {¬HasTerm{"test", ""}, "test", "", false}, - "nested andTerm": {andTerm{andTerm{}}, "test", "", false}, - "nested andTerm matches": {andTerm{&hasTerm{"test", "b"}}, "test", "b", true}, - "andTerm with non-match": {andTerm{&hasTerm{}, &hasTerm{"test", "b"}}, "test", "b", true}, - } - for k, v := range testCases { - value, found := v.S.RequiresExactMatch(v.Label) - if value != v.Value { - t.Errorf("%s: expected value %s, got %s", k, v.Value, value) - } - if found != v.Found { - t.Errorf("%s: expected found %t, got %t", k, v.Found, found) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/OWNERS b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/OWNERS new file mode 100644 index 000000000..66431ddd0 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/OWNERS @@ -0,0 +1,7 @@ +assignees: + - bgrant0607 + - brendandburns + - deads2k + - janetkuo + - jlowdermilk + - smarterclayton diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/annotate.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/annotate.go deleted file mode 100644 index daebf57d1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/annotate.go +++ /dev/null @@ -1,350 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "strings" - - "github.com/golang/glog" - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/strategicpatch" -) - -// AnnotateOptions have the data required to perform the annotate operation -type AnnotateOptions struct { - resources []string - newAnnotations map[string]string - removeAnnotations []string - builder *resource.Builder - filenames []string - selector string - - overwrite bool - all bool - resourceVersion string - - changeCause string - recordChangeCause bool - - f *cmdutil.Factory - out io.Writer - cmd *cobra.Command -} - -const ( - annotate_long = `Update the annotations on one or more resources. - -An annotation is a key/value pair that can hold larger (compared to a label), and possibly not human-readable, data. -It is intended to store non-identifying auxiliary data, especially data manipulated by tools and system extensions. -If --overwrite is true, then existing annotations can be overwritten, otherwise attempting to overwrite an annotation will result in an error. -If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used. - -Possible resources include (case insensitive): pods (po), services (svc), -replicationcontrollers (rc), nodes (no), events (ev), componentstatuses (cs), -limitranges (limits), persistentvolumes (pv), persistentvolumeclaims (pvc), -horizontalpodautoscalers (hpa), resourcequotas (quota) or secrets.` - annotate_example = `# Update pod 'foo' with the annotation 'description' and the value 'my frontend'. -# If the same annotation is set multiple times, only the last value will be applied -$ kubectl annotate pods foo description='my frontend' - -# Update a pod identified by type and name in "pod.json" -$ kubectl annotate -f pod.json description='my frontend' - -# Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value. -$ kubectl annotate --overwrite pods foo description='my frontend running nginx' - -# Update all pods in the namespace -$ kubectl annotate pods --all description='my frontend running nginx' - -# Update pod 'foo' only if the resource is unchanged from version 1. -$ kubectl annotate pods foo description='my frontend running nginx' --resource-version=1 - -# Update pod 'foo' by removing an annotation named 'description' if it exists. -# Does not require the --overwrite flag. -$ kubectl annotate pods foo description-` -) - -func NewCmdAnnotate(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &AnnotateOptions{} - - cmd := &cobra.Command{ - Use: "annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]", - Short: "Update the annotations on a resource", - Long: annotate_long, - Example: annotate_example, - Run: func(cmd *cobra.Command, args []string) { - if err := options.Complete(f, out, cmd, args); err != nil { - cmdutil.CheckErr(err) - } - if err := options.Validate(args); err != nil { - cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error())) - } - if err := options.RunAnnotate(); err != nil { - cmdutil.CheckErr(err) - } - }, - } - cmdutil.AddPrinterFlags(cmd) - cmd.Flags().StringVarP(&options.selector, "selector", "l", "", "Selector (label query) to filter on") - cmd.Flags().BoolVar(&options.overwrite, "overwrite", false, "If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.") - cmd.Flags().BoolVar(&options.all, "all", false, "select all resources in the namespace of the specified resource types") - cmd.Flags().StringVar(&options.resourceVersion, "resource-version", "", "If non-empty, the annotation update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.") - usage := "Filename, directory, or URL to a file identifying the resource to update the annotation" - kubectl.AddJsonFilenameFlag(cmd, &options.filenames, usage) - cmdutil.AddRecordFlag(cmd) - return cmd -} - -// Complete adapts from the command line args and factory to the data required. -func (o *AnnotateOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) { - - namespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - // retrieves resource and annotation args from args - // also checks args to verify that all resources are specified before annotations - annotationArgs := []string{} - metAnnotaionArg := false - for _, s := range args { - isAnnotation := strings.Contains(s, "=") || strings.HasSuffix(s, "-") - switch { - case !metAnnotaionArg && isAnnotation: - metAnnotaionArg = true - fallthrough - case metAnnotaionArg && isAnnotation: - annotationArgs = append(annotationArgs, s) - case !metAnnotaionArg && !isAnnotation: - o.resources = append(o.resources, s) - case metAnnotaionArg && !isAnnotation: - return fmt.Errorf("all resources must be specified before annotation changes: %s", s) - } - } - if len(o.resources) < 1 && len(o.filenames) == 0 { - return fmt.Errorf("one or more resources must be specified as or /") - } - if len(annotationArgs) < 1 { - return fmt.Errorf("at least one annotation update is required") - } - - if o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs); err != nil { - return err - } - - o.recordChangeCause = cmdutil.GetRecordFlag(cmd) - o.changeCause = f.Command() - - mapper, typer := f.Object() - o.builder = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(namespace).DefaultNamespace(). - FilenameParam(enforceNamespace, o.filenames...). - SelectorParam(o.selector). - ResourceTypeOrNameArgs(o.all, o.resources...). - Flatten(). - Latest() - - o.f = f - o.out = out - o.cmd = cmd - - return nil -} - -// Validate checks to the AnnotateOptions to see if there is sufficient information run the command. -func (o AnnotateOptions) Validate(args []string) error { - if err := validateAnnotations(o.removeAnnotations, o.newAnnotations); err != nil { - return err - } - - // only apply resource version locking on a single resource - if len(o.resources) > 1 && len(o.resourceVersion) > 0 { - return fmt.Errorf("--resource-version may only be used with a single resource") - } - - return nil -} - -// RunAnnotate does the work -func (o AnnotateOptions) RunAnnotate() error { - r := o.builder.Do() - if err := r.Err(); err != nil { - return err - } - - return r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - - name, namespace, obj := info.Name, info.Namespace, info.Object - oldData, err := json.Marshal(obj) - if err != nil { - return err - } - // If we should record change-cause, add it to new annotations - if cmdutil.ContainsChangeCause(info) || o.recordChangeCause { - o.newAnnotations[kubectl.ChangeCauseAnnotation] = o.changeCause - } - if err := o.updateAnnotations(obj); err != nil { - return err - } - newData, err := json.Marshal(obj) - if err != nil { - return err - } - patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj) - createdPatch := err == nil - if err != nil { - glog.V(2).Infof("couldn't compute patch: %v", err) - } - - mapping := info.ResourceMapping() - client, err := o.f.ClientForMapping(mapping) - if err != nil { - return err - } - helper := resource.NewHelper(client, mapping) - - var outputObj runtime.Object - if createdPatch { - outputObj, err = helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes) - } else { - outputObj, err = helper.Replace(namespace, name, false, obj) - } - if err != nil { - return err - } - outputFormat := cmdutil.GetFlagString(o.cmd, "output") - if outputFormat != "" { - return o.f.PrintObject(o.cmd, outputObj, o.out) - } - mapper, _ := o.f.Object() - cmdutil.PrintSuccess(mapper, false, o.out, info.Mapping.Resource, info.Name, "annotated") - return nil - }) -} - -// parseAnnotations retrieves new and remove annotations from annotation args -func parseAnnotations(annotationArgs []string) (map[string]string, []string, error) { - var invalidBuf bytes.Buffer - newAnnotations := map[string]string{} - removeAnnotations := []string{} - for _, annotationArg := range annotationArgs { - if strings.Index(annotationArg, "=") != -1 { - parts := strings.SplitN(annotationArg, "=", 2) - if len(parts) != 2 || len(parts[1]) == 0 { - if invalidBuf.Len() > 0 { - invalidBuf.WriteString(", ") - } - invalidBuf.WriteString(fmt.Sprintf(annotationArg)) - } else { - newAnnotations[parts[0]] = parts[1] - } - } else if strings.HasSuffix(annotationArg, "-") { - removeAnnotations = append(removeAnnotations, annotationArg[:len(annotationArg)-1]) - } else { - if invalidBuf.Len() > 0 { - invalidBuf.WriteString(", ") - } - invalidBuf.WriteString(fmt.Sprintf(annotationArg)) - } - } - if invalidBuf.Len() > 0 { - return newAnnotations, removeAnnotations, fmt.Errorf("invalid annotation format: %s", invalidBuf.String()) - } - - return newAnnotations, removeAnnotations, nil -} - -// validateAnnotations checks the format of annotation args and checks removed annotations aren't in the new annotations map -func validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error { - var modifyRemoveBuf bytes.Buffer - for _, removeAnnotation := range removeAnnotations { - if _, found := newAnnotations[removeAnnotation]; found { - if modifyRemoveBuf.Len() > 0 { - modifyRemoveBuf.WriteString(", ") - } - modifyRemoveBuf.WriteString(fmt.Sprintf(removeAnnotation)) - } - } - if modifyRemoveBuf.Len() > 0 { - return fmt.Errorf("can not both modify and remove the following annotation(s) in the same command: %s", modifyRemoveBuf.String()) - } - - return nil -} - -// validateNoAnnotationOverwrites validates that when overwrite is false, to-be-updated annotations don't exist in the object annotation map (yet) -func validateNoAnnotationOverwrites(meta *api.ObjectMeta, annotations map[string]string) error { - var buf bytes.Buffer - for key := range annotations { - // change-cause annotation can always be overwritten - if key == kubectl.ChangeCauseAnnotation { - continue - } - if value, found := meta.Annotations[key]; found { - if buf.Len() > 0 { - buf.WriteString("; ") - } - buf.WriteString(fmt.Sprintf("'%s' already has a value (%s)", key, value)) - } - } - if buf.Len() > 0 { - return fmt.Errorf("--overwrite is false but found the following declared annotation(s): %s", buf.String()) - } - return nil -} - -// updateAnnotations updates annotations of obj -func (o AnnotateOptions) updateAnnotations(obj runtime.Object) error { - meta, err := api.ObjectMetaFor(obj) - if err != nil { - return err - } - if !o.overwrite { - if err := validateNoAnnotationOverwrites(meta, o.newAnnotations); err != nil { - return err - } - } - - if meta.Annotations == nil { - meta.Annotations = make(map[string]string) - } - - for key, value := range o.newAnnotations { - meta.Annotations[key] = value - } - for _, annotation := range o.removeAnnotations { - delete(meta.Annotations, annotation) - } - - if len(o.resourceVersion) != 0 { - meta.ResourceVersion = o.resourceVersion - } - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/annotate_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/annotate_test.go deleted file mode 100644 index d2f58bf65..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/annotate_test.go +++ /dev/null @@ -1,571 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestValidateAnnotationOverwrites(t *testing.T) { - tests := []struct { - meta *api.ObjectMeta - annotations map[string]string - expectErr bool - scenario string - }{ - { - meta: &api.ObjectMeta{ - Annotations: map[string]string{ - "a": "A", - "b": "B", - }, - }, - annotations: map[string]string{ - "a": "a", - "c": "C", - }, - scenario: "share first annotation", - expectErr: true, - }, - { - meta: &api.ObjectMeta{ - Annotations: map[string]string{ - "a": "A", - "c": "C", - }, - }, - annotations: map[string]string{ - "b": "B", - "c": "c", - }, - scenario: "share second annotation", - expectErr: true, - }, - { - meta: &api.ObjectMeta{ - Annotations: map[string]string{ - "a": "A", - "c": "C", - }, - }, - annotations: map[string]string{ - "b": "B", - "d": "D", - }, - scenario: "no overlap", - }, - { - meta: &api.ObjectMeta{}, - annotations: map[string]string{ - "a": "A", - "b": "B", - }, - scenario: "no annotations", - }, - } - for _, test := range tests { - err := validateNoAnnotationOverwrites(test.meta, test.annotations) - if test.expectErr && err == nil { - t.Errorf("%s: unexpected non-error", test.scenario) - } else if !test.expectErr && err != nil { - t.Errorf("%s: unexpected error: %v", test.scenario, err) - } - } -} - -func TestParseAnnotations(t *testing.T) { - testURL := "https://test.com/index.htm?id=123#u=user-name" - testJSON := `'{"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"ReplicationController","namespace":"default","name":"my-nginx","uid":"c544ee78-2665-11e5-8051-42010af0c213","apiVersion":"v1","resourceVersion":"61368"}}'` - tests := []struct { - annotations []string - expected map[string]string - expectedRemove []string - scenario string - expectedErr string - expectErr bool - }{ - { - annotations: []string{"a=b", "c=d"}, - expected: map[string]string{"a": "b", "c": "d"}, - expectedRemove: []string{}, - scenario: "add two annotations", - expectErr: false, - }, - { - annotations: []string{"url=" + testURL, "kubernetes.io/created-by=" + testJSON}, - expected: map[string]string{"url": testURL, "kubernetes.io/created-by": testJSON}, - expectedRemove: []string{}, - scenario: "add annotations with special characters", - expectErr: false, - }, - { - annotations: []string{}, - expected: map[string]string{}, - expectedRemove: []string{}, - scenario: "add no annotations", - expectErr: false, - }, - { - annotations: []string{"a=b", "c=d", "e-"}, - expected: map[string]string{"a": "b", "c": "d"}, - expectedRemove: []string{"e"}, - scenario: "add two annotations, remove one", - expectErr: false, - }, - { - annotations: []string{"ab", "c=d"}, - expectedErr: "invalid annotation format: ab", - scenario: "incorrect annotation input (missing =value)", - expectErr: true, - }, - { - annotations: []string{"a="}, - expectedErr: "invalid annotation format: a=", - scenario: "incorrect annotation input (missing value)", - expectErr: true, - }, - { - annotations: []string{"ab", "a="}, - expectedErr: "invalid annotation format: ab, a=", - scenario: "incorrect multiple annotation input (missing value)", - expectErr: true, - }, - } - for _, test := range tests { - annotations, remove, err := parseAnnotations(test.annotations) - switch { - case test.expectErr && err == nil: - t.Errorf("%s: unexpected non-error, should return %v", test.scenario, test.expectedErr) - case test.expectErr && err.Error() != test.expectedErr: - t.Errorf("%s: unexpected error %v, expected %v", test.scenario, err, test.expectedErr) - case !test.expectErr && err != nil: - t.Errorf("%s: unexpected error %v", test.scenario, err) - case !test.expectErr && !reflect.DeepEqual(annotations, test.expected): - t.Errorf("%s: expected %v, got %v", test.scenario, test.expected, annotations) - case !test.expectErr && !reflect.DeepEqual(remove, test.expectedRemove): - t.Errorf("%s: expected %v, got %v", test.scenario, test.expectedRemove, remove) - } - } -} - -func TestValidateAnnotations(t *testing.T) { - tests := []struct { - removeAnnotations []string - newAnnotations map[string]string - expectedErr string - scenario string - }{ - { - expectedErr: "can not both modify and remove the following annotation(s) in the same command: a", - removeAnnotations: []string{"a"}, - newAnnotations: map[string]string{"a": "b", "c": "d"}, - scenario: "remove an added annotation", - }, - { - expectedErr: "can not both modify and remove the following annotation(s) in the same command: a, c", - removeAnnotations: []string{"a", "c"}, - newAnnotations: map[string]string{"a": "b", "c": "d"}, - scenario: "remove added annotations", - }, - } - for _, test := range tests { - if err := validateAnnotations(test.removeAnnotations, test.newAnnotations); err == nil { - t.Errorf("%s: unexpected non-error", test.scenario) - } else if err.Error() != test.expectedErr { - t.Errorf("%s: expected error %s, got %s", test.scenario, test.expectedErr, err.Error()) - } - } -} - -func TestUpdateAnnotations(t *testing.T) { - tests := []struct { - obj runtime.Object - overwrite bool - version string - annotations map[string]string - remove []string - expected runtime.Object - expectErr bool - }{ - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b"}, - }, - }, - annotations: map[string]string{"a": "b"}, - expectErr: true, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b"}, - }, - }, - annotations: map[string]string{"a": "c"}, - overwrite: true, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "c"}, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b"}, - }, - }, - annotations: map[string]string{"c": "d"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b", "c": "d"}, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b"}, - }, - }, - annotations: map[string]string{"c": "d"}, - version: "2", - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b", "c": "d"}, - ResourceVersion: "2", - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b"}, - }, - }, - annotations: map[string]string{}, - remove: []string{"a"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{}, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b", "c": "d"}, - }, - }, - annotations: map[string]string{"e": "f"}, - remove: []string{"a"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{ - "c": "d", - "e": "f", - }, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b", "c": "d"}, - }, - }, - annotations: map[string]string{"e": "f"}, - remove: []string{"g"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{ - "a": "b", - "c": "d", - "e": "f", - }, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b", "c": "d"}, - }, - }, - remove: []string{"e"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{ - "a": "b", - "c": "d", - }, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{}, - }, - annotations: map[string]string{"a": "b"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{"a": "b"}, - }, - }, - }, - } - for _, test := range tests { - options := &AnnotateOptions{ - overwrite: test.overwrite, - newAnnotations: test.annotations, - removeAnnotations: test.remove, - resourceVersion: test.version, - } - err := options.updateAnnotations(test.obj) - if test.expectErr { - if err == nil { - t.Errorf("unexpected non-error: %v", test) - } - continue - } - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v %v", err, test) - } - if !reflect.DeepEqual(test.obj, test.expected) { - t.Errorf("expected: %v, got %v", test.expected, test.obj) - } - } -} - -func TestAnnotateErrors(t *testing.T) { - testCases := map[string]struct { - args []string - flags map[string]string - errFn func(error) bool - }{ - "no args": { - args: []string{}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") }, - }, - "not enough annotations": { - args: []string{"pods"}, - errFn: func(err error) bool { - return strings.Contains(err.Error(), "at least one annotation update is required") - }, - }, - "no resources remove annotations": { - args: []string{"pods-"}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") }, - }, - "no resources add annotations": { - args: []string{"pods=bar"}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") }, - }, - } - - for k, testCase := range testCases { - f, tf, _ := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdAnnotate(f, buf) - cmd.SetOutput(buf) - - for k, v := range testCase.flags { - cmd.Flags().Set(k, v) - } - options := &AnnotateOptions{} - err := options.Complete(f, buf, cmd, testCase.args) - if !testCase.errFn(err) { - t.Errorf("%s: unexpected error: %v", k, err) - continue - } - if tf.Printer.(*testPrinter).Objects != nil { - t.Errorf("unexpected print to default printer") - } - if buf.Len() > 0 { - t.Errorf("buffer should be empty: %s", string(buf.Bytes())) - } - } -} - -func TestAnnotateObject(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.Method { - case "GET": - switch req.URL.Path { - case "/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - case "PATCH": - switch req.URL.Path { - case "/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - default: - t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdAnnotate(f, buf) - cmd.SetOutput(buf) - options := &AnnotateOptions{} - args := []string{"pods/foo", "a=b", "c-"} - if err := options.Complete(f, buf, cmd, args); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if err := options.Validate(args); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if err := options.RunAnnotate(); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestAnnotateObjectFromFile(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.Method { - case "GET": - switch req.URL.Path { - case "/namespaces/test/pods/cassandra": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - case "PATCH": - switch req.URL.Path { - case "/namespaces/test/pods/cassandra": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - default: - t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdAnnotate(f, buf) - cmd.SetOutput(buf) - options := &AnnotateOptions{} - options.filenames = []string{"../../../examples/cassandra/cassandra.yaml"} - args := []string{"a=b", "c-"} - if err := options.Complete(f, buf, cmd, args); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if err := options.Validate(args); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if err := options.RunAnnotate(); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestAnnotateMultipleObjects(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.Method { - case "GET": - switch req.URL.Path { - case "/namespaces/test/pods": - return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - case "PATCH": - switch req.URL.Path { - case "/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - case "/namespaces/test/pods/bar": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[1])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - default: - t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdAnnotate(f, buf) - cmd.SetOutput(buf) - options := &AnnotateOptions{} - options.all = true - args := []string{"pods", "a=b", "c-"} - if err := options.Complete(f, buf, cmd, args); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if err := options.Validate(args); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if err := options.RunAnnotate(); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apiversions.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apiversions.go deleted file mode 100644 index bc04d3eb5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apiversions.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "os" - "sort" - - "github.com/spf13/cobra" - - unversioned_client "k8s.io/kubernetes/pkg/client/unversioned" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -func NewCmdApiVersions(f *cmdutil.Factory, out io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "api-versions", - // apiversions is deprecated. - Aliases: []string{"apiversions"}, - Short: "Print the supported API versions on the server, in the form of \"group/version\".", - Run: func(cmd *cobra.Command, args []string) { - err := RunApiVersions(f, out) - cmdutil.CheckErr(err) - }, - } - return cmd -} - -func RunApiVersions(f *cmdutil.Factory, w io.Writer) error { - if len(os.Args) > 1 && os.Args[1] == "apiversions" { - printDeprecationWarning("api-versions", "apiversions") - } - - client, err := f.Client() - if err != nil { - return err - } - - groupList, err := client.Discovery().ServerGroups() - if err != nil { - return fmt.Errorf("Couldn't get available api versions from server: %v\n", err) - } - apiVersions := unversioned_client.ExtractGroupVersions(groupList) - sort.Strings(apiVersions) - for _, v := range apiVersions { - fmt.Fprintln(w, v) - } - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apply.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apply.go deleted file mode 100644 index 54aabc86b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apply.go +++ /dev/null @@ -1,213 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/strategicpatch" -) - -// ApplyOptions stores cmd.Flag values for apply. As new fields are added, -// add them here instead of referencing the cmd.Flags() -type ApplyOptions struct { - Filenames []string -} - -const ( - apply_long = `Apply a configuration to a resource by filename or stdin. -The resource will be created if it doesn't exist yet. - -JSON and YAML formats are accepted.` - apply_example = `# Apply the configuration in pod.json to a pod. -$ kubectl apply -f ./pod.json - -# Apply the JSON passed into stdin to a pod. -$ cat pod.json | kubectl apply -f -` -) - -func NewCmdApply(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &ApplyOptions{} - - cmd := &cobra.Command{ - Use: "apply -f FILENAME", - Short: "Apply a configuration to a resource by filename or stdin", - Long: apply_long, - Example: apply_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(validateArgs(cmd, args)) - cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) - cmdutil.CheckErr(RunApply(f, cmd, out, options)) - }, - } - - usage := "Filename, directory, or URL to file that contains the configuration to apply" - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.MarkFlagRequired("filename") - cmdutil.AddValidateFlags(cmd) - cmdutil.AddOutputFlagsForMutation(cmd) - cmdutil.AddRecordFlag(cmd) - return cmd -} - -func validateArgs(cmd *cobra.Command, args []string) error { - if len(args) != 0 { - return cmdutil.UsageError(cmd, "Unexpected args: %v", args) - } - - return nil -} - -func RunApply(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, options *ApplyOptions) error { - shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" - schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) - if err != nil { - return err - } - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - Schema(schema). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - encoder := f.JSONEncoder() - decoder := f.Decoder(false) - - count := 0 - err = r.Visit(func(info *resource.Info, err error) error { - // In this method, info.Object contains the object retrieved from the server - // and info.VersionedObject contains the object decoded from the input source. - if err != nil { - return err - } - - // Get the modified configuration of the object. Embed the result - // as an annotation in the modified configuration, so that it will appear - // in the patch sent to the server. - modified, err := kubectl.GetModifiedConfiguration(info, true, encoder) - if err != nil { - return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving modified configuration from:\n%v\nfor:", info), info.Source, err) - } - - if err := info.Get(); err != nil { - if !errors.IsNotFound(err) { - return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%v\nfrom server for:", info), info.Source, err) - } - // Create the resource if it doesn't exist - // First, update the annotation used by kubectl apply - if err := kubectl.CreateApplyAnnotation(info, encoder); err != nil { - return cmdutil.AddSourceToErr("creating", info.Source, err) - } - - if cmdutil.ShouldRecord(cmd, info) { - if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil { - return cmdutil.AddSourceToErr("creating", info.Source, err) - } - } - - // Then create the resource and skip the three-way merge - if err := createAndRefresh(info); err != nil { - return cmdutil.AddSourceToErr("creating", info.Source, err) - } - count++ - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "created") - return nil - } - - // Serialize the current configuration of the object from the server. - current, err := runtime.Encode(encoder, info.Object) - if err != nil { - return cmdutil.AddSourceToErr(fmt.Sprintf("serializing current configuration from:\n%v\nfor:", info), info.Source, err) - } - - // Retrieve the original configuration of the object from the annotation. - original, err := kubectl.GetOriginalConfiguration(info) - if err != nil { - return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving original configuration from:\n%v\nfor:", info), info.Source, err) - } - - // Create the versioned struct from the original from the server for - // strategic patch. - // TODO: Move all structs in apply to use raw data. Can be done once - // builder has a RawResult method which delivers raw data instead of - // internal objects. - versionedObject, _, err := decoder.Decode(current, nil, nil) - if err != nil { - return cmdutil.AddSourceToErr(fmt.Sprintf("converting encoded server-side object back to versioned struct:\n%v\nfor:", info), info.Source, err) - } - - // Compute a three way strategic merge patch to send to server. - patch, err := strategicpatch.CreateThreeWayMergePatch(original, modified, current, versionedObject, true) - if err != nil { - format := "creating patch with:\noriginal:\n%s\nmodified:\n%s\ncurrent:\n%s\nfrom:\n%v\nfor:" - return cmdutil.AddSourceToErr(fmt.Sprintf(format, original, modified, current, info), info.Source, err) - } - - helper := resource.NewHelper(info.Client, info.Mapping) - _, err = helper.Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch) - if err != nil { - return cmdutil.AddSourceToErr(fmt.Sprintf("applying patch:\n%s\nto:\n%v\nfor:", patch, info), info.Source, err) - } - - if cmdutil.ShouldRecord(cmd, info) { - patch, err = cmdutil.ChangeResourcePatch(info, f.Command()) - if err != nil { - return err - } - _, err = helper.Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch) - if err != nil { - return cmdutil.AddSourceToErr(fmt.Sprintf("applying patch:\n%s\nto:\n%v\nfor:", patch, info), info.Source, err) - } - } - - count++ - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "configured") - return nil - }) - - if err != nil { - return err - } - - if count == 0 { - return fmt.Errorf("no objects passed to apply") - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apply_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apply_test.go deleted file mode 100644 index 93a4d304e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/apply_test.go +++ /dev/null @@ -1,313 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - "os" - "testing" - - "github.com/ghodss/yaml" - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestApplyExtraArgsFail(t *testing.T) { - buf := bytes.NewBuffer([]byte{}) - - f, _, _ := NewAPIFactory() - c := NewCmdApply(f, buf) - if validateApplyArgs(c, []string{"rc"}) == nil { - t.Fatalf("unexpected non-error") - } -} - -func validateApplyArgs(cmd *cobra.Command, args []string) error { - if len(args) != 0 { - return cmdutil.UsageError(cmd, "Unexpected args: %v", args) - } - return nil -} - -const ( - filenameRC = "../../../test/fixtures/pkg/kubectl/cmd/apply/rc.yaml" - filenameSVC = "../../../test/fixtures/pkg/kubectl/cmd/apply/service.yaml" - filenameRCSVC = "../../../test/fixtures/pkg/kubectl/cmd/apply/rc-service.yaml" -) - -func readBytesFromFile(t *testing.T, filename string) []byte { - file, err := os.Open(filename) - if err != nil { - t.Fatal(err) - } - - data, err := ioutil.ReadAll(file) - if err != nil { - t.Fatal(err) - } - - return data -} - -func readReplicationControllerFromFile(t *testing.T, filename string) *api.ReplicationController { - data := readBytesFromFile(t, filename) - rc := api.ReplicationController{} - // TODO(jackgr): Replace with a call to testapi.Codec().Decode(). - if err := yaml.Unmarshal(data, &rc); err != nil { - t.Fatal(err) - } - - return &rc -} - -func readServiceFromFile(t *testing.T, filename string) *api.Service { - data := readBytesFromFile(t, filename) - svc := api.Service{} - // TODO(jackgr): Replace with a call to testapi.Codec().Decode(). - if err := yaml.Unmarshal(data, &svc); err != nil { - t.Fatal(err) - } - - return &svc -} - -func annotateRuntimeObject(t *testing.T, originalObj, currentObj runtime.Object, kind string) (string, []byte) { - originalMeta, err := api.ObjectMetaFor(originalObj) - if err != nil { - t.Fatal(err) - } - - originalMeta.Labels["DELETE_ME"] = "DELETE_ME" - original, err := json.Marshal(originalObj) - if err != nil { - t.Fatal(err) - } - - currentMeta, err := api.ObjectMetaFor(currentObj) - if err != nil { - t.Fatal(err) - } - - if currentMeta.Annotations == nil { - currentMeta.Annotations = map[string]string{} - } - - currentMeta.Annotations[kubectl.LastAppliedConfigAnnotation] = string(original) - current, err := json.Marshal(currentObj) - if err != nil { - t.Fatal(err) - } - - return currentMeta.Name, current -} - -func readAndAnnotateReplicationController(t *testing.T, filename string) (string, []byte) { - rc1 := readReplicationControllerFromFile(t, filename) - rc2 := readReplicationControllerFromFile(t, filename) - return annotateRuntimeObject(t, rc1, rc2, "ReplicationController") -} - -func readAndAnnotateService(t *testing.T, filename string) (string, []byte) { - svc1 := readServiceFromFile(t, filename) - svc2 := readServiceFromFile(t, filename) - return annotateRuntimeObject(t, svc1, svc2, "Service") -} - -func validatePatchApplication(t *testing.T, req *http.Request) { - patch, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatal(err) - } - - patchMap := map[string]interface{}{} - if err := json.Unmarshal(patch, &patchMap); err != nil { - t.Fatal(err) - } - - annotationsMap := walkMapPath(t, patchMap, []string{"metadata", "annotations"}) - if _, ok := annotationsMap[kubectl.LastAppliedConfigAnnotation]; !ok { - t.Fatalf("patch does not contain annotation:\n%s\n", patch) - } - - labelMap := walkMapPath(t, patchMap, []string{"metadata", "labels"}) - if deleteMe, ok := labelMap["DELETE_ME"]; !ok || deleteMe != nil { - t.Fatalf("patch does not remove deleted key: DELETE_ME:\n%s\n", patch) - } -} - -func walkMapPath(t *testing.T, start map[string]interface{}, path []string) map[string]interface{} { - finish := start - for i := 0; i < len(path); i++ { - var ok bool - finish, ok = finish[path[i]].(map[string]interface{}) - if !ok { - t.Fatalf("key:%s of path:%v not found in map:%v", path[i], path, start) - } - } - - return finish -} - -func TestApplyObject(t *testing.T) { - initTestErrorHandler(t) - nameRC, currentRC := readAndAnnotateReplicationController(t, filenameRC) - pathRC := "/namespaces/test/replicationcontrollers/" + nameRC - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == pathRC && m == "GET": - bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) - return &http.Response{StatusCode: 200, Body: bodyRC}, nil - case p == pathRC && m == "PATCH": - validatePatchApplication(t, req) - bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) - return &http.Response{StatusCode: 200, Body: bodyRC}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdApply(f, buf) - cmd.Flags().Set("filename", filenameRC) - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - // uses the name from the file, not the response - expectRC := "replicationcontroller/" + nameRC + "\n" - if buf.String() != expectRC { - t.Fatalf("unexpected output: %s\nexpected: %s", buf.String(), expectRC) - } -} - -func TestApplyNonExistObject(t *testing.T) { - nameRC, currentRC := readAndAnnotateReplicationController(t, filenameRC) - pathRC := "/namespaces/test/replicationcontrollers" - pathNameRC := pathRC + "/" + nameRC - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == pathNameRC && m == "GET": - return &http.Response{StatusCode: 404, Body: ioutil.NopCloser(bytes.NewReader(nil))}, nil - case p == pathRC && m == "POST": - bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) - return &http.Response{StatusCode: 201, Body: bodyRC}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdApply(f, buf) - cmd.Flags().Set("filename", filenameRC) - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - // uses the name from the file, not the response - expectRC := "replicationcontroller/" + nameRC + "\n" - if buf.String() != expectRC { - t.Errorf("unexpected output: %s\nexpected: %s", buf.String(), expectRC) - } -} - -func TestApplyMultipleObjectsAsList(t *testing.T) { - testApplyMultipleObjects(t, true) -} - -func TestApplyMultipleObjectsAsFiles(t *testing.T) { - testApplyMultipleObjects(t, false) -} - -func testApplyMultipleObjects(t *testing.T, asList bool) { - nameRC, currentRC := readAndAnnotateReplicationController(t, filenameRC) - pathRC := "/namespaces/test/replicationcontrollers/" + nameRC - - nameSVC, currentSVC := readAndAnnotateService(t, filenameSVC) - pathSVC := "/namespaces/test/services/" + nameSVC - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == pathRC && m == "GET": - bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) - return &http.Response{StatusCode: 200, Body: bodyRC}, nil - case p == pathRC && m == "PATCH": - validatePatchApplication(t, req) - bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) - return &http.Response{StatusCode: 200, Body: bodyRC}, nil - case p == pathSVC && m == "GET": - bodySVC := ioutil.NopCloser(bytes.NewReader(currentSVC)) - return &http.Response{StatusCode: 200, Body: bodySVC}, nil - case p == pathSVC && m == "PATCH": - validatePatchApplication(t, req) - bodySVC := ioutil.NopCloser(bytes.NewReader(currentSVC)) - return &http.Response{StatusCode: 200, Body: bodySVC}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdApply(f, buf) - if asList { - cmd.Flags().Set("filename", filenameRCSVC) - } else { - cmd.Flags().Set("filename", filenameRC) - cmd.Flags().Set("filename", filenameSVC) - } - cmd.Flags().Set("output", "name") - - cmd.Run(cmd, []string{}) - - // Names should come from the REST response, NOT the files - expectRC := "replicationcontroller/" + nameRC + "\n" - expectSVC := "service/" + nameSVC + "\n" - // Test both possible orders since output is non-deterministic. - expectOne := expectRC + expectSVC - expectTwo := expectSVC + expectRC - if buf.String() != expectOne && buf.String() != expectTwo { - t.Fatalf("unexpected output: %s\nexpected: %s OR %s", buf.String(), expectOne, expectTwo) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/attach.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/attach.go deleted file mode 100644 index 22f1ddb3b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/attach.go +++ /dev/null @@ -1,251 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "net/url" - "os" - "os/signal" - "syscall" - - "github.com/docker/docker/pkg/term" - "github.com/golang/glog" - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/remotecommand" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - utilerrors "k8s.io/kubernetes/pkg/util/errors" -) - -const ( - attach_example = `# Get output from running pod 123456-7890, using the first container by default -$ kubectl attach 123456-7890 - -# Get output from ruby-container from pod 123456-7890 -$ kubectl attach 123456-7890 -c ruby-container - -# Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890 -# and sends stdout/stderr from 'bash' back to the client -$ kubectl attach 123456-7890 -c ruby-container -i -t` -) - -func NewCmdAttach(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer) *cobra.Command { - options := &AttachOptions{ - In: cmdIn, - Out: cmdOut, - Err: cmdErr, - - Attach: &DefaultRemoteAttach{}, - } - cmd := &cobra.Command{ - Use: "attach POD -c CONTAINER", - Short: "Attach to a running container.", - Long: "Attach to a process that is already running inside an existing container.", - Example: attach_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(options.Complete(f, cmd, args)) - cmdutil.CheckErr(options.Validate()) - cmdutil.CheckErr(options.Run()) - }, - } - // TODO support UID - cmd.Flags().StringVarP(&options.ContainerName, "container", "c", "", "Container name. If omitted, the first container in the pod will be chosen") - cmd.Flags().BoolVarP(&options.Stdin, "stdin", "i", false, "Pass stdin to the container") - cmd.Flags().BoolVarP(&options.TTY, "tty", "t", false, "Stdin is a TTY") - return cmd -} - -// RemoteAttach defines the interface accepted by the Attach command - provided for test stubbing -type RemoteAttach interface { - Attach(method string, url *url.URL, config *client.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool) error -} - -// DefaultRemoteAttach is the standard implementation of attaching -type DefaultRemoteAttach struct{} - -func (*DefaultRemoteAttach) Attach(method string, url *url.URL, config *client.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool) error { - exec, err := remotecommand.NewExecutor(config, method, url) - if err != nil { - return err - } - return exec.Stream(stdin, stdout, stderr, tty) -} - -// AttachOptions declare the arguments accepted by the Exec command -type AttachOptions struct { - Namespace string - PodName string - ContainerName string - Stdin bool - TTY bool - - In io.Reader - Out io.Writer - Err io.Writer - - Attach RemoteAttach - Client *client.Client - Config *client.Config -} - -// Complete verifies command line arguments and loads data from the command environment -func (p *AttachOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string) error { - if len(argsIn) == 0 { - return cmdutil.UsageError(cmd, "POD is required for attach") - } - if len(argsIn) > 1 { - return cmdutil.UsageError(cmd, fmt.Sprintf("expected a single argument: POD, saw %d: %s", len(argsIn), argsIn)) - } - p.PodName = argsIn[0] - - namespace, _, err := f.DefaultNamespace() - if err != nil { - return err - } - p.Namespace = namespace - - config, err := f.ClientConfig() - if err != nil { - return err - } - p.Config = config - - client, err := f.Client() - if err != nil { - return err - } - p.Client = client - - return nil -} - -// Validate checks that the provided attach options are specified. -func (p *AttachOptions) Validate() error { - allErrs := []error{} - if len(p.PodName) == 0 { - allErrs = append(allErrs, fmt.Errorf("pod name must be specified")) - } - if p.Out == nil || p.Err == nil { - allErrs = append(allErrs, fmt.Errorf("both output and error output must be provided")) - } - if p.Attach == nil || p.Client == nil || p.Config == nil { - allErrs = append(allErrs, fmt.Errorf("client, client config, and attach must be provided")) - } - return utilerrors.NewAggregate(allErrs) -} - -// Run executes a validated remote execution against a pod. -func (p *AttachOptions) Run() error { - pod, err := p.Client.Pods(p.Namespace).Get(p.PodName) - if err != nil { - return err - } - - if pod.Status.Phase != api.PodRunning { - return fmt.Errorf("pod %s is not running and cannot be attached to; current phase is %s", p.PodName, pod.Status.Phase) - } - - var stdin io.Reader - tty := p.TTY - - containerToAttach := p.GetContainer(pod) - if tty && !containerToAttach.TTY { - tty = false - fmt.Fprintf(p.Err, "Unable to use a TTY - container %s doesn't allocate one\n", containerToAttach.Name) - } - - // TODO: refactor with terminal helpers from the edit utility once that is merged - if p.Stdin { - stdin = p.In - if tty { - if file, ok := stdin.(*os.File); ok { - inFd := file.Fd() - if term.IsTerminal(inFd) { - oldState, err := term.SetRawTerminal(inFd) - if err != nil { - glog.Fatal(err) - } - fmt.Fprintln(p.Out, "\nHit enter for command prompt") - // this handles a clean exit, where the command finished - defer term.RestoreTerminal(inFd, oldState) - - // SIGINT is handled by term.SetRawTerminal (it runs a goroutine that listens - // for SIGINT and restores the terminal before exiting) - - // this handles SIGTERM - sigChan := make(chan os.Signal, 1) - signal.Notify(sigChan, syscall.SIGTERM) - go func() { - <-sigChan - term.RestoreTerminal(inFd, oldState) - os.Exit(0) - }() - } else { - fmt.Fprintln(p.Err, "STDIN is not a terminal") - } - } else { - tty = false - fmt.Fprintln(p.Err, "Unable to use a TTY - input is not the right kind of file") - } - } - } - - // TODO: consider abstracting into a client invocation or client helper - req := p.Client.RESTClient.Post(). - Resource("pods"). - Name(pod.Name). - Namespace(pod.Namespace). - SubResource("attach") - req.VersionedParams(&api.PodAttachOptions{ - Container: containerToAttach.Name, - Stdin: stdin != nil, - Stdout: p.Out != nil, - Stderr: p.Err != nil, - TTY: tty, - }, api.ParameterCodec) - - err = p.Attach.Attach("POST", req.URL(), p.Config, stdin, p.Out, p.Err, tty) - if err != nil { - return err - } - if p.Stdin && tty && pod.Spec.RestartPolicy == api.RestartPolicyAlways { - fmt.Fprintf(p.Out, "Session ended, resume using 'kubectl attach %s -c %s -i -t' command when the pod is running\n", pod.Name, containerToAttach.Name) - } - return nil -} - -// GetContainer returns the container to attach to, with a fallback. -func (p *AttachOptions) GetContainer(pod *api.Pod) api.Container { - if len(p.ContainerName) > 0 { - for _, container := range pod.Spec.Containers { - if container.Name == p.ContainerName { - return container - } - } - } - - glog.V(4).Infof("defaulting container name to %s", pod.Spec.Containers[0].Name) - return pod.Spec.Containers[0] -} - -// GetContainerName returns the name of the container to attach to, with a fallback. -func (p *AttachOptions) GetContainerName(pod *api.Pod) string { - return p.GetContainer(pod).Name -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/attach_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/attach_test.go deleted file mode 100644 index 7fc4b7fe6..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/attach_test.go +++ /dev/null @@ -1,279 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -type fakeRemoteAttach struct { - method string - url *url.URL - attachErr error -} - -func (f *fakeRemoteAttach) Attach(method string, url *url.URL, config *client.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool) error { - f.method = method - f.url = url - return f.attachErr -} - -func TestPodAndContainerAttach(t *testing.T) { - tests := []struct { - args []string - p *AttachOptions - name string - expectError bool - expectedPod string - expectedContainer string - }{ - { - p: &AttachOptions{}, - expectError: true, - name: "empty", - }, - { - p: &AttachOptions{}, - args: []string{"foo", "bar"}, - expectError: true, - name: "too many args", - }, - { - p: &AttachOptions{}, - args: []string{"foo"}, - expectedPod: "foo", - name: "no container, no flags", - }, - { - p: &AttachOptions{ContainerName: "bar"}, - args: []string{"foo"}, - expectedPod: "foo", - expectedContainer: "bar", - name: "container in flag", - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { return nil, nil }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{} - - cmd := &cobra.Command{} - options := test.p - err := options.Complete(f, cmd, test.args) - if test.expectError && err == nil { - t.Errorf("unexpected non-error (%s)", test.name) - } - if !test.expectError && err != nil { - t.Errorf("unexpected error: %v (%s)", err, test.name) - } - if err != nil { - continue - } - if options.PodName != test.expectedPod { - t.Errorf("expected: %s, got: %s (%s)", test.expectedPod, options.PodName, test.name) - } - if options.ContainerName != test.expectedContainer { - t.Errorf("expected: %s, got: %s (%s)", test.expectedContainer, options.ContainerName, test.name) - } - } -} - -func TestAttach(t *testing.T) { - version := testapi.Default.GroupVersion().Version - tests := []struct { - name, version, podPath, attachPath, container string - pod *api.Pod - attachErr bool - }{ - { - name: "pod attach", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - attachPath: "/api/" + version + "/namespaces/test/pods/foo/attach", - pod: attachPod(), - }, - { - name: "pod attach error", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - attachPath: "/api/" + version + "/namespaces/test/pods/foo/attach", - pod: attachPod(), - attachErr: true, - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == test.podPath && m == "GET": - body := objBody(codec, test.pod) - return &http.Response{StatusCode: 200, Body: body}, nil - default: - // Ensures no GET is performed when deleting by name - t.Errorf("%s: unexpected request: %s %#v\n%#v", test.name, req.Method, req.URL, req) - return nil, fmt.Errorf("unexpected request") - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}} - bufOut := bytes.NewBuffer([]byte{}) - bufErr := bytes.NewBuffer([]byte{}) - bufIn := bytes.NewBuffer([]byte{}) - ex := &fakeRemoteAttach{} - if test.attachErr { - ex.attachErr = fmt.Errorf("attach error") - } - params := &AttachOptions{ - ContainerName: "bar", - In: bufIn, - Out: bufOut, - Err: bufErr, - Attach: ex, - } - cmd := &cobra.Command{} - if err := params.Complete(f, cmd, []string{"foo"}); err != nil { - t.Fatal(err) - } - err := params.Run() - if test.attachErr && err != ex.attachErr { - t.Errorf("%s: Unexpected exec error: %v", test.name, err) - continue - } - if !test.attachErr && err != nil { - t.Errorf("%s: Unexpected error: %v", test.name, err) - continue - } - if test.attachErr { - continue - } - if ex.url.Path != test.attachPath { - t.Errorf("%s: Did not get expected path for exec request", test.name) - continue - } - if ex.method != "POST" { - t.Errorf("%s: Did not get method for attach request: %s", test.name, ex.method) - } - if ex.url.Query().Get("container") != "bar" { - t.Errorf("%s: Did not have query parameters: %s", test.name, ex.url.Query()) - } - } -} - -func TestAttachWarnings(t *testing.T) { - version := testapi.Default.GroupVersion().Version - tests := []struct { - name, container, version, podPath, expectedErr, expectedOut string - pod *api.Pod - stdin, tty bool - }{ - { - name: "fallback tty if not supported", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - pod: attachPod(), - stdin: true, - tty: true, - expectedErr: "Unable to use a TTY - container bar doesn't allocate one", - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == test.podPath && m == "GET": - body := objBody(codec, test.pod) - return &http.Response{StatusCode: 200, Body: body}, nil - default: - t.Errorf("%s: unexpected request: %s %#v\n%#v", test.name, req.Method, req.URL, req) - return nil, fmt.Errorf("unexpected request") - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}} - bufOut := bytes.NewBuffer([]byte{}) - bufErr := bytes.NewBuffer([]byte{}) - bufIn := bytes.NewBuffer([]byte{}) - ex := &fakeRemoteAttach{} - params := &AttachOptions{ - ContainerName: test.container, - In: bufIn, - Out: bufOut, - Err: bufErr, - Stdin: test.stdin, - TTY: test.tty, - Attach: ex, - } - cmd := &cobra.Command{} - if err := params.Complete(f, cmd, []string{"foo"}); err != nil { - t.Fatal(err) - } - if err := params.Run(); err != nil { - t.Fatal(err) - } - - if test.stdin && test.tty { - if !test.pod.Spec.Containers[0].TTY { - if !strings.Contains(bufErr.String(), test.expectedErr) { - t.Errorf("%s: Expected TTY fallback warning for attach request: %s", test.name, bufErr.String()) - continue - } - } - } - } -} - -func attachPod() *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"}, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{ - { - Name: "bar", - }, - }, - }, - Status: api.PodStatus{ - Phase: api.PodRunning, - }, - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/autoscale.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/autoscale.go deleted file mode 100644 index 343c3a8a5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/autoscale.go +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/util/errors" - - "github.com/spf13/cobra" -) - -const ( - autoscaleLong = `Creates an autoscaler that automatically chooses and sets the number of pods that run in a kubernetes cluster. - -Looks up a deployment or replication controller by name and creates an autoscaler that uses this deployment or replication controller as a reference. -An autoscaler can automatically increase or decrease number of pods deployed within the system as needed.` - - autoscaleExample = `# Auto scale a deployment "foo", with the number of pods between 2 to 10, target CPU utilization at a default value that server applies: -$ kubectl autoscale deployment foo --min=2 --max=10 - -# Auto scale a replication controller "foo", with the number of pods between 1 to 5, target CPU utilization at 80%: -$ kubectl autoscale rc foo --max=5 --cpu-percent=80` -) - -func NewCmdAutoscale(f *cmdutil.Factory, out io.Writer) *cobra.Command { - filenames := []string{} - cmd := &cobra.Command{ - Use: "autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]", - Short: "Auto-scale a deployment or replication controller", - Long: autoscaleLong, - Example: autoscaleExample, - Run: func(cmd *cobra.Command, args []string) { - err := RunAutoscale(f, out, cmd, args, filenames) - cmdutil.CheckErr(err) - }, - } - cmdutil.AddPrinterFlags(cmd) - cmd.Flags().String("generator", "horizontalpodautoscaler/v1beta1", "The name of the API generator to use. Currently there is only 1 generator.") - cmd.Flags().Int("min", -1, "The lower limit for the number of pods that can be set by the autoscaler. If it's not specified or negative, the server will apply a default value.") - cmd.Flags().Int("max", -1, "The upper limit for the number of pods that can be set by the autoscaler. Required.") - cmd.MarkFlagRequired("max") - cmd.Flags().Int("cpu-percent", -1, fmt.Sprintf("The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, the server will apply a default value.")) - cmd.Flags().String("name", "", "The name for the newly created object. If not specified, the name of the input resource will be used.") - cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without creating it.") - usage := "Filename, directory, or URL to a file identifying the resource to autoscale." - kubectl.AddJsonFilenameFlag(cmd, &filenames, usage) - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddRecordFlag(cmd) - return cmd -} - -func RunAutoscale(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames []string) error { - namespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - // validate flags - if err := validateFlags(cmd); err != nil { - return err - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(namespace).DefaultNamespace(). - FilenameParam(enforceNamespace, filenames...). - ResourceTypeOrNameArgs(false, args...). - Flatten(). - Do() - infos, err := r.Infos() - if err != nil { - return err - } - if len(infos) > 1 { - return fmt.Errorf("multiple resources provided: %v", args) - } - info := infos[0] - mapping := info.ResourceMapping() - if err := f.CanBeAutoscaled(mapping.GroupVersionKind.GroupKind()); err != nil { - return err - } - - // Get the generator, setup and validate all required parameters - generatorName := cmdutil.GetFlagString(cmd, "generator") - generators := f.Generators("autoscale") - generator, found := generators[generatorName] - if !found { - return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName)) - } - names := generator.ParamNames() - params := kubectl.MakeParams(cmd, names) - name := info.Name - params["default-name"] = name - - params["scaleRef-kind"] = mapping.GroupVersionKind.Kind - params["scaleRef-name"] = name - params["scaleRef-apiVersion"] = mapping.GroupVersionKind.GroupVersion().String() - - if err = kubectl.ValidateParams(names, params); err != nil { - return err - } - // Check for invalid flags used against the present generator. - if err := kubectl.EnsureFlagsValid(cmd, generators, generatorName); err != nil { - return err - } - - // Generate new object - object, err := generator.Generate(params) - if err != nil { - return err - } - - resourceMapper := &resource.Mapper{ - ObjectTyper: typer, - RESTMapper: mapper, - ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), - Decoder: f.Decoder(true), - } - hpa, err := resourceMapper.InfoForObject(object) - if err != nil { - return err - } - if cmdutil.ShouldRecord(cmd, hpa) { - if err := cmdutil.RecordChangeCause(hpa.Object, f.Command()); err != nil { - return err - } - object = hpa.Object - } - // TODO: extract this flag to a central location, when such a location exists. - if cmdutil.GetFlagBool(cmd, "dry-run") { - return f.PrintObject(cmd, object, out) - } - - if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), hpa, f.JSONEncoder()); err != nil { - return err - } - - object, err = resource.NewHelper(hpa.Client, hpa.Mapping).Create(namespace, false, object) - if err != nil { - return err - } - - if len(cmdutil.GetFlagString(cmd, "output")) > 0 { - return f.PrintObject(cmd, object, out) - } - cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, "autoscaled") - return nil -} - -func validateFlags(cmd *cobra.Command) error { - errs := []error{} - max, min, cpu := cmdutil.GetFlagInt(cmd, "max"), cmdutil.GetFlagInt(cmd, "min"), cmdutil.GetFlagInt(cmd, "cpu-percent") - if max < 1 || max < min { - errs = append(errs, fmt.Errorf("--max=MAXPODS is required, and must be at least 1 and --min=MINPODS")) - } - if cpu > 100 { - errs = append(errs, fmt.Errorf("CPU utilization (%%) cannot exceed 100")) - } - return errors.NewAggregate(errs) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/clusterinfo.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/clusterinfo.go deleted file mode 100644 index c76e28f7c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/clusterinfo.go +++ /dev/null @@ -1,117 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "os" - "strconv" - - "k8s.io/kubernetes/pkg/api" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - - "github.com/daviddengcn/go-colortext" - "github.com/spf13/cobra" -) - -func NewCmdClusterInfo(f *cmdutil.Factory, out io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "cluster-info", - // clusterinfo is deprecated. - Aliases: []string{"clusterinfo"}, - Short: "Display cluster info", - Long: "Display addresses of the master and services with label kubernetes.io/cluster-service=true", - Run: func(cmd *cobra.Command, args []string) { - err := RunClusterInfo(f, out, cmd) - cmdutil.CheckErr(err) - }, - } - return cmd -} - -func RunClusterInfo(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { - if len(os.Args) > 1 && os.Args[1] == "clusterinfo" { - printDeprecationWarning("cluster-info", "clusterinfo") - } - - client, err := f.ClientConfig() - if err != nil { - return err - } - printService(out, "Kubernetes master", client.Host) - - mapper, typer := f.Object() - cmdNamespace := cmdutil.GetFlagString(cmd, "namespace") - if cmdNamespace == "" { - cmdNamespace = api.NamespaceSystem - } - - // TODO use generalized labels once they are implemented (#341) - b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace(). - SelectorParam("kubernetes.io/cluster-service=true"). - ResourceTypeOrNameArgs(false, []string{"services"}...). - Latest() - b.Do().Visit(func(r *resource.Info, err error) error { - if err != nil { - return err - } - services := r.Object.(*api.ServiceList).Items - for _, service := range services { - var link string - if len(service.Status.LoadBalancer.Ingress) > 0 { - ingress := service.Status.LoadBalancer.Ingress[0] - ip := ingress.IP - if ip == "" { - ip = ingress.Hostname - } - for _, port := range service.Spec.Ports { - link += "http://" + ip + ":" + strconv.Itoa(port.Port) + " " - } - } else { - if len(client.GroupVersion.Group) == 0 { - link = client.Host + "/api/" + client.GroupVersion.Version + "/proxy/namespaces/" + service.ObjectMeta.Namespace + "/services/" + service.ObjectMeta.Name - } else { - link = client.Host + "/api/" + client.GroupVersion.Group + "/" + client.GroupVersion.Version + "/proxy/namespaces/" + service.ObjectMeta.Namespace + "/services/" + service.ObjectMeta.Name - - } - } - name := service.ObjectMeta.Labels["kubernetes.io/name"] - if len(name) == 0 { - name = service.ObjectMeta.Name - } - printService(out, name, link) - } - return nil - }) - return nil - - // TODO consider printing more information about cluster -} - -func printService(out io.Writer, name, link string) { - ct.ChangeColor(ct.Green, false, ct.None, false) - fmt.Fprint(out, name) - ct.ResetColor() - fmt.Fprintf(out, " is running at ") - ct.ChangeColor(ct.Yellow, false, ct.None, false) - fmt.Fprint(out, link) - ct.ResetColor() - fmt.Fprintln(out, "") -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/cmd.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/cmd.go deleted file mode 100644 index 2abffaf37..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/cmd.go +++ /dev/null @@ -1,201 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "io" - - "github.com/golang/glog" - cmdconfig "k8s.io/kubernetes/pkg/kubectl/cmd/config" - "k8s.io/kubernetes/pkg/kubectl/cmd/rollout" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/util" - - "github.com/spf13/cobra" -) - -const ( - bash_completion_func = `# call kubectl get $1, -__kubectl_parse_get() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" "$1" 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out[*]}" -- "$cur" ) ) - fi -} - -__kubectl_get_resource() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - return 1 - fi - __kubectl_parse_get "${nouns[${#nouns[@]} -1]}" -} - -__kubectl_get_resource_pod() -{ - __kubectl_parse_get "pod" -} - -__kubectl_get_resource_rc() -{ - __kubectl_parse_get "rc" -} - -# $1 is the name of the pod we want to get the list of containers inside -__kubectl_get_containers() -{ - local template - template="{{ range .spec.containers }}{{ .name }} {{ end }}" - __debug "${FUNCNAME} nouns are ${nouns[*]}" - - local len="${#nouns[@]}" - if [[ ${len} -ne 1 ]]; then - return - fi - local last=${nouns[${len} -1]} - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" pods "${last}" 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out[*]}" -- "$cur" ) ) - fi -} - -# Require both a pod and a container to be specified -__kubectl_require_pod_and_container() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - __kubectl_parse_get pods - return 0 - fi; - __kubectl_get_containers - return 0 -} - -__custom_func() { - case ${last_command} in - kubectl_get | kubectl_describe | kubectl_delete | kubectl_label | kubectl_stop) - __kubectl_get_resource - return - ;; - kubectl_logs) - __kubectl_require_pod_and_container - return - ;; - kubectl_exec) - __kubectl_get_resource_pod - return - ;; - kubectl_rolling-update) - __kubectl_get_resource_rc - return - ;; - *) - ;; - esac -} -` - valid_resources = `Valid resource types include: - * componentstatuses (aka 'cs') - * events (aka 'ev') - * endpoints (aka 'ep') - * horizontalpodautoscalers (aka 'hpa') - * ingress (aka 'ing') - * jobs - * limitranges (aka 'limits') - * nodes (aka 'no') - * namespaces (aka 'ns') - * pods (aka 'po') - * persistentvolumes (aka 'pv') - * persistentvolumeclaims (aka 'pvc') - * quota - * resourcequotas (aka 'quota') - * replicasets (aka 'rs') - * replicationcontrollers (aka 'rc') - * secrets - * serviceaccounts - * services (aka 'svc') -` -) - -// NewKubectlCommand creates the `kubectl` command and its nested children. -func NewKubectlCommand(f *cmdutil.Factory, in io.Reader, out, err io.Writer) *cobra.Command { - // Parent command to which all subcommands are added. - cmds := &cobra.Command{ - Use: "kubectl", - Short: "kubectl controls the Kubernetes cluster manager", - Long: `kubectl controls the Kubernetes cluster manager. - -Find more information at https://github.com/kubernetes/kubernetes.`, - Run: runHelp, - BashCompletionFunction: bash_completion_func, - } - - f.BindFlags(cmds.PersistentFlags()) - - // From this point and forward we get warnings on flags that contain "_" separators - cmds.SetGlobalNormalizationFunc(util.WarnWordSepNormalizeFunc) - - cmds.AddCommand(NewCmdGet(f, out)) - cmds.AddCommand(NewCmdDescribe(f, out)) - cmds.AddCommand(NewCmdCreate(f, out)) - cmds.AddCommand(NewCmdReplace(f, out)) - cmds.AddCommand(NewCmdPatch(f, out)) - cmds.AddCommand(NewCmdDelete(f, out)) - cmds.AddCommand(NewCmdEdit(f, out)) - cmds.AddCommand(NewCmdApply(f, out)) - - cmds.AddCommand(NewCmdNamespace(out)) - cmds.AddCommand(NewCmdLogs(f, out)) - cmds.AddCommand(NewCmdRollingUpdate(f, out)) - cmds.AddCommand(NewCmdScale(f, out)) - cmds.AddCommand(NewCmdCordon(f, out)) - cmds.AddCommand(NewCmdDrain(f, out)) - cmds.AddCommand(NewCmdUncordon(f, out)) - - cmds.AddCommand(NewCmdAttach(f, in, out, err)) - cmds.AddCommand(NewCmdExec(f, in, out, err)) - cmds.AddCommand(NewCmdPortForward(f)) - cmds.AddCommand(NewCmdProxy(f, out)) - - cmds.AddCommand(NewCmdRun(f, in, out, err)) - cmds.AddCommand(NewCmdStop(f, out)) - cmds.AddCommand(NewCmdExposeService(f, out)) - cmds.AddCommand(NewCmdAutoscale(f, out)) - cmds.AddCommand(rollout.NewCmdRollout(f, out)) - - cmds.AddCommand(NewCmdLabel(f, out)) - cmds.AddCommand(NewCmdAnnotate(f, out)) - - cmds.AddCommand(cmdconfig.NewCmdConfig(cmdconfig.NewDefaultPathOptions(), out)) - cmds.AddCommand(NewCmdClusterInfo(f, out)) - cmds.AddCommand(NewCmdApiVersions(f, out)) - cmds.AddCommand(NewCmdVersion(f, out)) - cmds.AddCommand(NewCmdExplain(f, out)) - cmds.AddCommand(NewCmdConvert(f, out)) - - return cmds -} - -func runHelp(cmd *cobra.Command, args []string) { - cmd.Help() -} - -func printDeprecationWarning(command, alias string) { - glog.Warningf("%s is DEPRECATED and will be removed in a future version. Use %s instead.", alias, command) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/cmd_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/cmd_test.go deleted file mode 100644 index 82783c34f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/cmd_test.go +++ /dev/null @@ -1,709 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "reflect" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/validation" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/runtime/serializer" - "k8s.io/kubernetes/pkg/util" -) - -func initTestErrorHandler(t *testing.T) { - cmdutil.BehaviorOnFatal(func(str string) { - t.Errorf("Error running command: %s", str) - }) -} - -type internalType struct { - Kind string - APIVersion string - - Name string -} - -type externalType struct { - Kind string `json:"kind"` - APIVersion string `json:"apiVersion"` - - Name string `json:"name"` -} - -type ExternalType2 struct { - Kind string `json:"kind"` - APIVersion string `json:"apiVersion"` - - Name string `json:"name"` -} - -func (obj *internalType) GetObjectKind() unversioned.ObjectKind { return obj } -func (obj *internalType) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { - obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind() -} -func (obj *internalType) GroupVersionKind() *unversioned.GroupVersionKind { - return unversioned.FromAPIVersionAndKind(obj.APIVersion, obj.Kind) -} -func (obj *externalType) GetObjectKind() unversioned.ObjectKind { return obj } -func (obj *externalType) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { - obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind() -} -func (obj *externalType) GroupVersionKind() *unversioned.GroupVersionKind { - return unversioned.FromAPIVersionAndKind(obj.APIVersion, obj.Kind) -} -func (obj *ExternalType2) GetObjectKind() unversioned.ObjectKind { return obj } -func (obj *ExternalType2) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { - obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind() -} -func (obj *ExternalType2) GroupVersionKind() *unversioned.GroupVersionKind { - return unversioned.FromAPIVersionAndKind(obj.APIVersion, obj.Kind) -} - -var versionErr = errors.New("not a version") - -func versionErrIfFalse(b bool) error { - if b { - return nil - } - return versionErr -} - -var validVersion = testapi.Default.GroupVersion().Version -var internalGV = unversioned.GroupVersion{Group: "apitest", Version: runtime.APIVersionInternal} -var unlikelyGV = unversioned.GroupVersion{Group: "apitest", Version: "unlikelyversion"} -var validVersionGV = unversioned.GroupVersion{Group: "apitest", Version: validVersion} - -func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) { - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGV.WithKind("Type"), &internalType{}) - scheme.AddKnownTypeWithName(unlikelyGV.WithKind("Type"), &externalType{}) - //This tests that kubectl will not confuse the external scheme with the internal scheme, even when they accidentally have versions of the same name. - scheme.AddKnownTypeWithName(validVersionGV.WithKind("Type"), &ExternalType2{}) - - codecs := serializer.NewCodecFactory(scheme) - codec := codecs.LegacyCodec(unlikelyGV) - mapper := meta.NewDefaultRESTMapper([]unversioned.GroupVersion{unlikelyGV, validVersionGV}, func(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) { - return &meta.VersionInterfaces{ - ObjectConvertor: scheme, - MetadataAccessor: meta.NewAccessor(), - }, versionErrIfFalse(version == validVersionGV || version == unlikelyGV) - }) - for _, gv := range []unversioned.GroupVersion{unlikelyGV, validVersionGV} { - for kind := range scheme.KnownTypes(gv) { - gvk := gv.WithKind(kind) - - scope := meta.RESTScopeNamespace - mapper.Add(gvk, scope) - } - } - - return scheme, mapper, codec -} - -type testPrinter struct { - Objects []runtime.Object - Err error -} - -func (t *testPrinter) PrintObj(obj runtime.Object, out io.Writer) error { - t.Objects = append(t.Objects, obj) - fmt.Fprintf(out, "%#v", obj) - return t.Err -} - -// TODO: implement HandledResources() -func (t *testPrinter) HandledResources() []string { - return []string{} -} - -type testDescriber struct { - Name, Namespace string - Output string - Err error -} - -func (t *testDescriber) Describe(namespace, name string) (output string, err error) { - t.Namespace, t.Name = namespace, name - return t.Output, t.Err -} - -type testFactory struct { - Mapper meta.RESTMapper - Typer runtime.ObjectTyper - Client kubectl.RESTClient - Describer kubectl.Describer - Printer kubectl.ResourcePrinter - Validator validation.Schema - Namespace string - ClientConfig *client.Config - Err error -} - -func NewTestFactory() (*cmdutil.Factory, *testFactory, runtime.Codec) { - scheme, mapper, codec := newExternalScheme() - t := &testFactory{ - Validator: validation.NullSchema{}, - Mapper: mapper, - Typer: scheme, - } - return &cmdutil.Factory{ - Object: func() (meta.RESTMapper, runtime.ObjectTyper) { - return t.Mapper, t.Typer - }, - ClientForMapping: func(*meta.RESTMapping) (resource.RESTClient, error) { - return t.Client, t.Err - }, - Decoder: func(bool) runtime.Decoder { - return codec - }, - JSONEncoder: func() runtime.Encoder { - return codec - }, - Describer: func(*meta.RESTMapping) (kubectl.Describer, error) { - return t.Describer, t.Err - }, - Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, showLabels bool, absoluteTimestamps bool, columnLabels []string) (kubectl.ResourcePrinter, error) { - return t.Printer, t.Err - }, - Validator: func(validate bool, cacheDir string) (validation.Schema, error) { - return t.Validator, t.Err - }, - DefaultNamespace: func() (string, bool, error) { - return t.Namespace, false, t.Err - }, - ClientConfig: func() (*client.Config, error) { - return t.ClientConfig, t.Err - }, - }, t, codec -} - -func NewMixedFactory(apiClient resource.RESTClient) (*cmdutil.Factory, *testFactory, runtime.Codec) { - f, t, c := NewTestFactory() - f.Object = func() (meta.RESTMapper, runtime.ObjectTyper) { - return meta.MultiRESTMapper{t.Mapper, testapi.Default.RESTMapper()}, runtime.MultiObjectTyper{t.Typer, api.Scheme} - } - f.ClientForMapping = func(m *meta.RESTMapping) (resource.RESTClient, error) { - if m.ObjectConvertor == api.Scheme { - return apiClient, t.Err - } - return t.Client, t.Err - } - return f, t, c -} - -func NewAPIFactory() (*cmdutil.Factory, *testFactory, runtime.Codec) { - t := &testFactory{ - Validator: validation.NullSchema{}, - } - - f := &cmdutil.Factory{ - Object: func() (meta.RESTMapper, runtime.ObjectTyper) { - return testapi.Default.RESTMapper(), api.Scheme - }, - Client: func() (*client.Client, error) { - // Swap out the HTTP client out of the client with the fake's version. - fakeClient := t.Client.(*fake.RESTClient) - c := client.NewOrDie(t.ClientConfig) - c.Client = fakeClient.Client - c.ExtensionsClient.Client = fakeClient.Client - return c, t.Err - }, - ClientForMapping: func(*meta.RESTMapping) (resource.RESTClient, error) { - return t.Client, t.Err - }, - Decoder: func(bool) runtime.Decoder { - return testapi.Default.Codec() - }, - JSONEncoder: func() runtime.Encoder { - return testapi.Default.Codec() - }, - Describer: func(*meta.RESTMapping) (kubectl.Describer, error) { - return t.Describer, t.Err - }, - Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, showLabels bool, absoluteTimestamps bool, columnLabels []string) (kubectl.ResourcePrinter, error) { - return t.Printer, t.Err - }, - Validator: func(validate bool, cacheDir string) (validation.Schema, error) { - return t.Validator, t.Err - }, - DefaultNamespace: func() (string, bool, error) { - return t.Namespace, false, t.Err - }, - ClientConfig: func() (*client.Config, error) { - return t.ClientConfig, t.Err - }, - Generators: func(cmdName string) map[string]kubectl.Generator { - return cmdutil.DefaultGenerators(cmdName) - }, - LogsForObject: func(object, options runtime.Object) (*client.Request, error) { - fakeClient := t.Client.(*fake.RESTClient) - c := client.NewOrDie(t.ClientConfig) - c.Client = fakeClient.Client - - switch t := object.(type) { - case *api.Pod: - opts, ok := options.(*api.PodLogOptions) - if !ok { - return nil, errors.New("provided options object is not a PodLogOptions") - } - return c.Pods(t.Namespace).GetLogs(t.Name, opts), nil - default: - fqKind, err := api.Scheme.ObjectKind(object) - if err != nil { - return nil, err - } - return nil, fmt.Errorf("cannot get the logs from %v", fqKind) - } - }, - } - rf := cmdutil.NewFactory(nil) - f.PodSelectorForObject = rf.PodSelectorForObject - f.MapBasedSelectorForObject = rf.MapBasedSelectorForObject - f.PortsForObject = rf.PortsForObject - f.LabelsForObject = rf.LabelsForObject - f.CanBeExposed = rf.CanBeExposed - return f, t, testapi.Default.Codec() -} - -func objBody(codec runtime.Codec, obj runtime.Object) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, obj)))) -} - -func stringBody(body string) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(body))) -} - -// TODO(jlowdermilk): refactor the Factory so we can test client versions properly, -// with different client/server version skew scenarios. -// Verify that resource.RESTClients constructed from a factory respect mapping.APIVersion -//func TestClientVersions(t *testing.T) { -// f := cmdutil.NewFactory(nil) -// -// version := testapi.Default.Version() -// mapping := &meta.RESTMapping{ -// APIVersion: version, -// } -// c, err := f.ClientForMapping(mapping) -// if err != nil { -// t.Errorf("unexpected error: %v", err) -// } -// client := c.(*client.RESTClient) -// if client.APIVersion() != version { -// t.Errorf("unexpected Client APIVersion: %s %v", client.APIVersion, client) -// } -//} - -func ExamplePrintReplicationControllerWithNamespace() { - f, tf, codec := NewAPIFactory() - tf.Printer = kubectl.NewHumanReadablePrinter(false, true, false, false, false, false, []string{}) - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: nil, - } - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - ctrl := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "beep", - Labels: map[string]string{"foo": "bar"}, - CreationTimestamp: unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"foo": "bar"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"foo": "bar"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - }, - }, - }, - }, - }, - } - err := f.PrintObject(cmd, ctrl, os.Stdout) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - // Output: - // NAMESPACE CONTROLLER REPLICAS AGE - // beep foo 1 10y -} - -func ExamplePrintReplicationControllerWithWide() { - f, tf, codec := NewAPIFactory() - tf.Printer = kubectl.NewHumanReadablePrinter(false, false, true, false, false, false, []string{}) - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: nil, - } - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - ctrl := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar"}, - CreationTimestamp: unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"foo": "bar"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"foo": "bar"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - }, - }, - }, - }, - }, - } - err := f.PrintObject(cmd, ctrl, os.Stdout) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - // Output: - // CONTROLLER REPLICAS AGE CONTAINER(S) IMAGE(S) SELECTOR - // foo 1 10y foo someimage foo=bar -} - -func ExamplePrintPodWithWideFormat() { - f, tf, codec := NewAPIFactory() - tf.Printer = kubectl.NewHumanReadablePrinter(false, false, true, false, false, false, []string{}) - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: nil, - } - nodeName := "kubernetes-minion-abcd" - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - CreationTimestamp: unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.PodSpec{ - Containers: make([]api.Container, 2), - NodeName: nodeName, - }, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - } - err := f.PrintObject(cmd, pod, os.Stdout) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - // Output: - // NAME READY STATUS RESTARTS AGE NODE - // test1 1/2 podPhase 6 10y kubernetes-minion-abcd -} - -func ExamplePrintPodWithShowLabels() { - f, tf, codec := NewAPIFactory() - tf.Printer = kubectl.NewHumanReadablePrinter(false, false, false, false, true, false, []string{}) - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: nil, - } - nodeName := "kubernetes-minion-abcd" - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - CreationTimestamp: unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}, - Labels: map[string]string{ - "l1": "key", - "l2": "value", - }, - }, - Spec: api.PodSpec{ - Containers: make([]api.Container, 2), - NodeName: nodeName, - }, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - } - err := f.PrintObject(cmd, pod, os.Stdout) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - // Output: - // NAME READY STATUS RESTARTS AGE LABELS - // test1 1/2 podPhase 6 10y l1=key,l2=value -} - -func newAllPhasePodList() *api.PodList { - nodeName := "kubernetes-minion-abcd" - return &api.PodList{ - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{ - Name: "test1", - CreationTimestamp: unversioned.Time{time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.PodSpec{ - Containers: make([]api.Container, 2), - NodeName: nodeName, - }, - Status: api.PodStatus{ - Phase: api.PodPending, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "test2", - CreationTimestamp: unversioned.Time{time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.PodSpec{ - Containers: make([]api.Container, 2), - NodeName: nodeName, - }, - Status: api.PodStatus{ - Phase: api.PodRunning, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "test3", - CreationTimestamp: unversioned.Time{time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.PodSpec{ - Containers: make([]api.Container, 2), - NodeName: nodeName, - }, - Status: api.PodStatus{ - Phase: api.PodSucceeded, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "test4", - CreationTimestamp: unversioned.Time{time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.PodSpec{ - Containers: make([]api.Container, 2), - NodeName: nodeName, - }, - Status: api.PodStatus{ - Phase: api.PodFailed, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "test5", - CreationTimestamp: unversioned.Time{time.Now().AddDate(-10, 0, 0)}, - }, - Spec: api.PodSpec{ - Containers: make([]api.Container, 2), - NodeName: nodeName, - }, - Status: api.PodStatus{ - Phase: api.PodUnknown, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }}, - } -} - -func ExamplePrintPodHideTerminated() { - f, tf, codec := NewAPIFactory() - tf.Printer = kubectl.NewHumanReadablePrinter(false, false, false, false, false, false, []string{}) - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: nil, - } - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - podList := newAllPhasePodList() - err := f.PrintObject(cmd, podList, os.Stdout) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - // Output: - // NAME READY STATUS RESTARTS AGE - // test1 1/2 Pending 6 10y - // test2 1/2 Running 6 10y - // test5 1/2 Unknown 6 10y -} - -func ExamplePrintPodShowAll() { - f, tf, codec := NewAPIFactory() - tf.Printer = kubectl.NewHumanReadablePrinter(false, false, false, true, false, false, []string{}) - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: nil, - } - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - podList := newAllPhasePodList() - err := f.PrintObject(cmd, podList, os.Stdout) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - // Output: - // NAME READY STATUS RESTARTS AGE - // test1 1/2 Pending 6 10y - // test2 1/2 Running 6 10y - // test3 1/2 Succeeded 6 10y - // test4 1/2 Failed 6 10y - // test5 1/2 Unknown 6 10y -} - -func ExamplePrintServiceWithNamespacesAndLabels() { - f, tf, codec := NewAPIFactory() - tf.Printer = kubectl.NewHumanReadablePrinter(false, true, false, false, false, false, []string{"l1"}) - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: nil, - } - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - svc := &api.ServiceList{ - Items: []api.Service{ - { - ObjectMeta: api.ObjectMeta{ - Name: "svc1", - Namespace: "ns1", - CreationTimestamp: unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}, - Labels: map[string]string{ - "l1": "value", - }, - }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Protocol: "UDP", Port: 53}, - {Protocol: "TCP", Port: 53}, - }, - Selector: map[string]string{ - "s": "magic", - }, - ClusterIP: "10.1.1.1", - }, - Status: api.ServiceStatus{}, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "svc2", - Namespace: "ns2", - CreationTimestamp: unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}, - Labels: map[string]string{ - "l1": "dolla-bill-yall", - }, - }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Protocol: "TCP", Port: 80}, - {Protocol: "TCP", Port: 8080}, - }, - Selector: map[string]string{ - "s": "kazam", - }, - ClusterIP: "10.1.1.2", - }, - Status: api.ServiceStatus{}, - }}, - } - ld := util.NewLineDelimiter(os.Stdout, "|") - defer ld.Flush() - err := f.PrintObject(cmd, svc, ld) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - // Output: - // |NAMESPACE NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE L1| - // |ns1 svc1 10.1.1.1 unknown 53/UDP,53/TCP 10y value| - // |ns2 svc2 10.1.1.2 unknown 80/TCP,8080/TCP 10y dolla-bill-yall| - // || -} - -func TestNormalizationFuncGlobalExistence(t *testing.T) { - // This test can be safely deleted when we will not support multiple flag formats - root := NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr) - - if root.Parent() != nil { - t.Fatal("We expect the root command to be returned") - } - if root.GlobalNormalizationFunc() == nil { - t.Fatal("We expect that root command has a global normalization function") - } - - if reflect.ValueOf(root.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(root.Flags().GetNormalizeFunc()).Pointer() { - t.Fatal("root command seems to have a wrong normalization function") - } - - sub := root - for sub.HasSubCommands() { - sub = sub.Commands()[0] - } - - // In case of failure of this test check this PR: spf13/cobra#110 - if reflect.ValueOf(sub.Flags().GetNormalizeFunc()).Pointer() != reflect.ValueOf(root.Flags().GetNormalizeFunc()).Pointer() { - t.Fatal("child and root commands should have the same normalization functions") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/config.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/config.go deleted file mode 100644 index 47eeecf5c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/config.go +++ /dev/null @@ -1,448 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "io" - "os" - "path" - "path/filepath" - "reflect" - "strconv" - - "github.com/golang/glog" - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" -) - -type PathOptions struct { - // GlobalFile is the full path to the file to load as the global (final) option - GlobalFile string - // EnvVar is the env var name that points to the list of kubeconfig files to load - EnvVar string - // ExplicitFileFlag is the name of the flag to use for prompting for the kubeconfig file - ExplicitFileFlag string - - // GlobalFileSubpath is an optional value used for displaying help - GlobalFileSubpath string - - LoadingRules *clientcmd.ClientConfigLoadingRules -} - -// ConfigAccess is used by subcommands and methods in this package to load and modify the appropriate config files -type ConfigAccess interface { - // GetLoadingPrecedence returns the slice of files that should be used for loading and inspecting the config - GetLoadingPrecedence() []string - // GetStartingConfig returns the config that subcommands should being operating against. It may or may not be merged depending on loading rules - GetStartingConfig() (*clientcmdapi.Config, error) - // GetDefaultFilename returns the name of the file you should write into (create if necessary), if you're trying to create a new stanza as opposed to updating an existing one. - GetDefaultFilename() string - // IsExplicitFile indicates whether or not this command is interested in exactly one file. This implementation only ever does that via a flag, but implementations that handle local, global, and flags may have more - IsExplicitFile() bool - // GetExplicitFile returns the particular file this command is operating against. This implementation only ever has one, but implementations that handle local, global, and flags may have more - GetExplicitFile() string -} - -func NewCmdConfig(pathOptions *PathOptions, out io.Writer) *cobra.Command { - if len(pathOptions.ExplicitFileFlag) == 0 { - pathOptions.ExplicitFileFlag = clientcmd.RecommendedConfigPathFlag - } - - cmd := &cobra.Command{ - Use: "config SUBCOMMAND", - Short: "config modifies kubeconfig files", - Long: `config modifies kubeconfig files using subcommands like "kubectl config set current-context my-context" - -The loading order follows these rules: -1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place. -2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used a list of paths (normal path delimitting rules for your system). These paths are merged together. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list. -3. Otherwise, ` + path.Join("${HOME}", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place. -`, - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, - } - - // file paths are common to all sub commands - cmd.PersistentFlags().StringVar(&pathOptions.LoadingRules.ExplicitPath, pathOptions.ExplicitFileFlag, pathOptions.LoadingRules.ExplicitPath, "use a particular kubeconfig file") - - cmd.AddCommand(NewCmdConfigView(out, pathOptions)) - cmd.AddCommand(NewCmdConfigSetCluster(out, pathOptions)) - cmd.AddCommand(NewCmdConfigSetAuthInfo(out, pathOptions)) - cmd.AddCommand(NewCmdConfigSetContext(out, pathOptions)) - cmd.AddCommand(NewCmdConfigSet(out, pathOptions)) - cmd.AddCommand(NewCmdConfigUnset(out, pathOptions)) - cmd.AddCommand(NewCmdConfigCurrentContext(out, pathOptions)) - cmd.AddCommand(NewCmdConfigUseContext(out, pathOptions)) - - return cmd -} - -func NewDefaultPathOptions() *PathOptions { - ret := &PathOptions{ - GlobalFile: clientcmd.RecommendedHomeFile, - EnvVar: clientcmd.RecommendedConfigPathEnvVar, - ExplicitFileFlag: clientcmd.RecommendedConfigPathFlag, - - GlobalFileSubpath: path.Join(clientcmd.RecommendedHomeDir, clientcmd.RecommendedFileName), - - LoadingRules: clientcmd.NewDefaultClientConfigLoadingRules(), - } - ret.LoadingRules.DoNotResolvePaths = true - - return ret -} - -func (o *PathOptions) GetEnvVarFiles() []string { - if len(o.EnvVar) == 0 { - return []string{} - } - - envVarValue := os.Getenv(o.EnvVar) - if len(envVarValue) == 0 { - return []string{} - } - - return filepath.SplitList(envVarValue) -} - -func (o *PathOptions) GetLoadingPrecedence() []string { - if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { - return envVarFiles - } - - return []string{o.GlobalFile} -} - -func (o *PathOptions) GetStartingConfig() (*clientcmdapi.Config, error) { - // don't mutate the original - loadingRules := *o.LoadingRules - loadingRules.Precedence = o.GetLoadingPrecedence() - - clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(&loadingRules, &clientcmd.ConfigOverrides{}) - rawConfig, err := clientConfig.RawConfig() - if os.IsNotExist(err) { - return clientcmdapi.NewConfig(), nil - } - if err != nil { - return nil, err - } - - return &rawConfig, nil -} - -func (o *PathOptions) GetDefaultFilename() string { - if o.IsExplicitFile() { - return o.GetExplicitFile() - } - - if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { - if len(envVarFiles) == 1 { - return envVarFiles[0] - } - - // if any of the envvar files already exists, return it - for _, envVarFile := range envVarFiles { - if _, err := os.Stat(envVarFile); err == nil { - return envVarFile - } - } - - // otherwise, return the last one in the list - return envVarFiles[len(envVarFiles)-1] - } - - return o.GlobalFile -} - -func (o *PathOptions) IsExplicitFile() bool { - if len(o.LoadingRules.ExplicitPath) > 0 { - return true - } - - return false -} - -func (o *PathOptions) GetExplicitFile() string { - return o.LoadingRules.ExplicitPath -} - -// ModifyConfig takes a Config object, iterates through Clusters, AuthInfos, and Contexts, uses the LocationOfOrigin if specified or -// uses the default destination file to write the results into. This results in multiple file reads, but it's very easy to follow. -// Preferences and CurrentContext should always be set in the default destination file. Since we can't distinguish between empty and missing values -// (no nil strings), we're forced have separate handling for them. In the kubeconfig cases, newConfig should have at most one difference, -// that means that this code will only write into a single file. If you want to relativizePaths, you must provide a fully qualified path in any -// modified element. -func ModifyConfig(configAccess ConfigAccess, newConfig clientcmdapi.Config, relativizePaths bool) error { - startingConfig, err := configAccess.GetStartingConfig() - if err != nil { - return err - } - - // We need to find all differences, locate their original files, read a partial config to modify only that stanza and write out the file. - // Special case the test for current context and preferences since those always write to the default file. - if reflect.DeepEqual(*startingConfig, newConfig) { - // nothing to do - return nil - } - - if startingConfig.CurrentContext != newConfig.CurrentContext { - if err := writeCurrentContext(configAccess, newConfig.CurrentContext); err != nil { - return err - } - } - - if !reflect.DeepEqual(startingConfig.Preferences, newConfig.Preferences) { - if err := writePreferences(configAccess, newConfig.Preferences); err != nil { - return err - } - } - - // Search every cluster, authInfo, and context. First from new to old for differences, then from old to new for deletions - for key, cluster := range newConfig.Clusters { - startingCluster, exists := startingConfig.Clusters[key] - if !reflect.DeepEqual(cluster, startingCluster) || !exists { - destinationFile := cluster.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite := getConfigFromFileOrDie(destinationFile) - t := *cluster - - configToWrite.Clusters[key] = &t - configToWrite.Clusters[key].LocationOfOrigin = destinationFile - if relativizePaths { - if err := clientcmd.RelativizeClusterLocalPaths(configToWrite.Clusters[key]); err != nil { - return err - } - } - - if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, context := range newConfig.Contexts { - startingContext, exists := startingConfig.Contexts[key] - if !reflect.DeepEqual(context, startingContext) || !exists { - destinationFile := context.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite := getConfigFromFileOrDie(destinationFile) - configToWrite.Contexts[key] = context - - if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, authInfo := range newConfig.AuthInfos { - startingAuthInfo, exists := startingConfig.AuthInfos[key] - if !reflect.DeepEqual(authInfo, startingAuthInfo) || !exists { - destinationFile := authInfo.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite := getConfigFromFileOrDie(destinationFile) - t := *authInfo - configToWrite.AuthInfos[key] = &t - configToWrite.AuthInfos[key].LocationOfOrigin = destinationFile - if relativizePaths { - if err := clientcmd.RelativizeAuthInfoLocalPaths(configToWrite.AuthInfos[key]); err != nil { - return err - } - } - - if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, cluster := range startingConfig.Clusters { - if _, exists := newConfig.Clusters[key]; !exists { - destinationFile := cluster.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite := getConfigFromFileOrDie(destinationFile) - delete(configToWrite.Clusters, key) - - if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, context := range startingConfig.Contexts { - if _, exists := newConfig.Contexts[key]; !exists { - destinationFile := context.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite := getConfigFromFileOrDie(destinationFile) - delete(configToWrite.Contexts, key) - - if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, authInfo := range startingConfig.AuthInfos { - if _, exists := newConfig.AuthInfos[key]; !exists { - destinationFile := authInfo.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite := getConfigFromFileOrDie(destinationFile) - delete(configToWrite.AuthInfos, key) - - if err := clientcmd.WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - return nil -} - -// writeCurrentContext takes three possible paths. -// If newCurrentContext is the same as the startingConfig's current context, then we exit. -// If newCurrentContext has a value, then that value is written into the default destination file. -// If newCurrentContext is empty, then we find the config file that is setting the CurrentContext and clear the value from that file -func writeCurrentContext(configAccess ConfigAccess, newCurrentContext string) error { - if startingConfig, err := configAccess.GetStartingConfig(); err != nil { - return err - } else if startingConfig.CurrentContext == newCurrentContext { - return nil - } - - if configAccess.IsExplicitFile() { - file := configAccess.GetExplicitFile() - currConfig := getConfigFromFileOrDie(file) - currConfig.CurrentContext = newCurrentContext - if err := clientcmd.WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - - if len(newCurrentContext) > 0 { - destinationFile := configAccess.GetDefaultFilename() - config := getConfigFromFileOrDie(destinationFile) - config.CurrentContext = newCurrentContext - - if err := clientcmd.WriteToFile(*config, destinationFile); err != nil { - return err - } - - return nil - } - - // we're supposed to be clearing the current context. We need to find the first spot in the chain that is setting it and clear it - for _, file := range configAccess.GetLoadingPrecedence() { - if _, err := os.Stat(file); err == nil { - currConfig := getConfigFromFileOrDie(file) - - if len(currConfig.CurrentContext) > 0 { - currConfig.CurrentContext = newCurrentContext - if err := clientcmd.WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - } - } - - return errors.New("no config found to write context") -} - -func writePreferences(configAccess ConfigAccess, newPrefs clientcmdapi.Preferences) error { - if startingConfig, err := configAccess.GetStartingConfig(); err != nil { - return err - } else if reflect.DeepEqual(startingConfig.Preferences, newPrefs) { - return nil - } - - if configAccess.IsExplicitFile() { - file := configAccess.GetExplicitFile() - currConfig := getConfigFromFileOrDie(file) - currConfig.Preferences = newPrefs - if err := clientcmd.WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - - for _, file := range configAccess.GetLoadingPrecedence() { - currConfig := getConfigFromFileOrDie(file) - - if !reflect.DeepEqual(currConfig.Preferences, newPrefs) { - currConfig.Preferences = newPrefs - if err := clientcmd.WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - } - - return errors.New("no config found to write preferences") -} - -// getConfigFromFileOrDie tries to read a kubeconfig file and if it can't, it calls exit. One exception, missing files result in empty configs, not an exit -func getConfigFromFileOrDie(filename string) *clientcmdapi.Config { - config, err := clientcmd.LoadFromFile(filename) - if err != nil && !os.IsNotExist(err) { - glog.FatalDepth(1, err) - } - - if config == nil { - return clientcmdapi.NewConfig() - } - - return config -} - -func toBool(propertyValue string) (bool, error) { - boolValue := false - if len(propertyValue) != 0 { - var err error - boolValue, err = strconv.ParseBool(propertyValue) - if err != nil { - return false, err - } - } - - return boolValue, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/config_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/config_test.go deleted file mode 100644 index 8f33734a0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/config_test.go +++ /dev/null @@ -1,783 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "path" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/util" -) - -func newRedFederalCowHammerConfig() clientcmdapi.Config { - return clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "red-user": {Token: "red-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "cow-cluster": {Server: "http://cow.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "federal-context": {AuthInfo: "red-user", Cluster: "cow-cluster"}}, - CurrentContext: "federal-context", - } -} - -func ExampleView() { - expectedConfig := newRedFederalCowHammerConfig() - test := configCommandTest{ - args: []string{"view"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - output := test.run(nil) - fmt.Printf("%v", output) - // Output: - // apiVersion: v1 - // clusters: - // - cluster: - // server: http://cow.org:8080 - // name: cow-cluster - // contexts: - // - context: - // cluster: cow-cluster - // user: red-user - // name: federal-context - // current-context: federal-context - // kind: Config - // preferences: {} - // users: - // - name: red-user - // user: - // token: red-token -} - -func TestCurrentContext(t *testing.T) { - startingConfig := newRedFederalCowHammerConfig() - test := configCommandTest{ - args: []string{"current-context"}, - startingConfig: startingConfig, - expectedConfig: startingConfig, - expectedOutputs: []string{startingConfig.CurrentContext}, - } - test.run(t) -} - -func TestSetCurrentContext(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - startingConfig := newRedFederalCowHammerConfig() - - newContextName := "the-new-context" - - startingConfig.Contexts[newContextName] = clientcmdapi.NewContext() - expectedConfig.Contexts[newContextName] = clientcmdapi.NewContext() - - expectedConfig.CurrentContext = newContextName - - test := configCommandTest{ - args: []string{"use-context", "the-new-context"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestSetNonExistentContext(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - test := configCommandTest{ - args: []string{"use-context", "non-existent-config"}, - startingConfig: expectedConfig, - expectedConfig: expectedConfig, - expectedOutputs: []string{`no context exists with the name: "non-existent-config"`}, - } - test.run(t) -} - -func TestSetIntoExistingStruct(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.AuthInfos["red-user"].Password = "new-path-value" - test := configCommandTest{ - args: []string{"set", "users.red-user.password", "new-path-value"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestSetWithPathPrefixIntoExistingStruct(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.Clusters["cow-cluster"].Server = "http://cow.org:8080/foo/baz" - test := configCommandTest{ - args: []string{"set", "clusters.cow-cluster.server", "http://cow.org:8080/foo/baz"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) - - dc := clientcmd.NewDefaultClientConfig(expectedConfig, &clientcmd.ConfigOverrides{}) - dcc, err := dc.ClientConfig() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - expectedHost := "http://cow.org:8080/foo/baz" - if expectedHost != dcc.Host { - t.Fatalf("expected client.Config.Host = %q instead of %q", expectedHost, dcc.Host) - } -} - -func TestUnsetStruct(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - delete(expectedConfig.AuthInfos, "red-user") - test := configCommandTest{ - args: []string{"unset", "users.red-user"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestUnsetField(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.AuthInfos["red-user"] = clientcmdapi.NewAuthInfo() - test := configCommandTest{ - args: []string{"unset", "users.red-user.token"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestSetIntoNewStruct(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - cluster := clientcmdapi.NewCluster() - cluster.Server = "new-server-value" - expectedConfig.Clusters["big-cluster"] = cluster - test := configCommandTest{ - args: []string{"set", "clusters.big-cluster.server", "new-server-value"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestSetBoolean(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - cluster := clientcmdapi.NewCluster() - cluster.InsecureSkipTLSVerify = true - expectedConfig.Clusters["big-cluster"] = cluster - test := configCommandTest{ - args: []string{"set", "clusters.big-cluster.insecure-skip-tls-verify", "true"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestSetIntoNewConfig(t *testing.T) { - expectedConfig := *clientcmdapi.NewConfig() - context := clientcmdapi.NewContext() - context.AuthInfo = "fake-user" - expectedConfig.Contexts["new-context"] = context - test := configCommandTest{ - args: []string{"set", "contexts.new-context.user", "fake-user"}, - startingConfig: *clientcmdapi.NewConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestNewEmptyAuth(t *testing.T) { - expectedConfig := *clientcmdapi.NewConfig() - expectedConfig.AuthInfos["the-user-name"] = clientcmdapi.NewAuthInfo() - test := configCommandTest{ - args: []string{"set-credentials", "the-user-name"}, - startingConfig: *clientcmdapi.NewConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestAdditionalAuth(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - authInfo := clientcmdapi.NewAuthInfo() - authInfo.Token = "token" - expectedConfig.AuthInfos["another-user"] = authInfo - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagBearerToken + "=token"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestEmbedClientCert(t *testing.T) { - fakeCertFile, _ := ioutil.TempFile("", "") - defer os.Remove(fakeCertFile.Name()) - fakeData := []byte("fake-data") - ioutil.WriteFile(fakeCertFile.Name(), fakeData, 0600) - expectedConfig := newRedFederalCowHammerConfig() - authInfo := clientcmdapi.NewAuthInfo() - authInfo.ClientCertificateData = fakeData - expectedConfig.AuthInfos["another-user"] = authInfo - - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagCertFile + "=" + fakeCertFile.Name(), "--" + clientcmd.FlagEmbedCerts + "=true"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestEmbedClientKey(t *testing.T) { - fakeKeyFile, _ := ioutil.TempFile("", "") - defer os.Remove(fakeKeyFile.Name()) - fakeData := []byte("fake-data") - ioutil.WriteFile(fakeKeyFile.Name(), fakeData, 0600) - expectedConfig := newRedFederalCowHammerConfig() - authInfo := clientcmdapi.NewAuthInfo() - authInfo.ClientKeyData = fakeData - expectedConfig.AuthInfos["another-user"] = authInfo - - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagKeyFile + "=" + fakeKeyFile.Name(), "--" + clientcmd.FlagEmbedCerts + "=true"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestEmbedNoKeyOrCertDisallowed(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagEmbedCerts + "=true"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - expectedOutputs: []string{"--client-certificate", "--client-key", "embed"}, - } - - test.run(t) -} - -func TestEmptyTokenAndCertAllowed(t *testing.T) { - fakeCertFile, _ := ioutil.TempFile("", "cert-file") - - expectedConfig := newRedFederalCowHammerConfig() - authInfo := clientcmdapi.NewAuthInfo() - authInfo.ClientCertificate = path.Base(fakeCertFile.Name()) - expectedConfig.AuthInfos["another-user"] = authInfo - - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagCertFile + "=" + fakeCertFile.Name(), "--" + clientcmd.FlagBearerToken + "="}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestTokenAndCertAllowed(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - authInfo := clientcmdapi.NewAuthInfo() - authInfo.Token = "token" - authInfo.ClientCertificate = "/cert-file" - expectedConfig.AuthInfos["another-user"] = authInfo - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagCertFile + "=/cert-file", "--" + clientcmd.FlagBearerToken + "=token"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestTokenAndBasicDisallowed(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagUsername + "=myuser", "--" + clientcmd.FlagBearerToken + "=token"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - expectedOutputs: []string{"--token", "--username"}, - } - - test.run(t) -} - -func TestBasicClearsToken(t *testing.T) { - authInfoWithToken := clientcmdapi.NewAuthInfo() - authInfoWithToken.Token = "token" - - authInfoWithBasic := clientcmdapi.NewAuthInfo() - authInfoWithBasic.Username = "myuser" - authInfoWithBasic.Password = "mypass" - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.AuthInfos["another-user"] = authInfoWithToken - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.AuthInfos["another-user"] = authInfoWithBasic - - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagUsername + "=myuser", "--" + clientcmd.FlagPassword + "=mypass"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestTokenClearsBasic(t *testing.T) { - authInfoWithBasic := clientcmdapi.NewAuthInfo() - authInfoWithBasic.Username = "myuser" - authInfoWithBasic.Password = "mypass" - - authInfoWithToken := clientcmdapi.NewAuthInfo() - authInfoWithToken.Token = "token" - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.AuthInfos["another-user"] = authInfoWithBasic - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.AuthInfos["another-user"] = authInfoWithToken - - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagBearerToken + "=token"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestTokenLeavesCert(t *testing.T) { - authInfoWithCerts := clientcmdapi.NewAuthInfo() - authInfoWithCerts.ClientCertificate = "cert" - authInfoWithCerts.ClientCertificateData = []byte("certdata") - authInfoWithCerts.ClientKey = "key" - authInfoWithCerts.ClientKeyData = []byte("keydata") - - authInfoWithTokenAndCerts := clientcmdapi.NewAuthInfo() - authInfoWithTokenAndCerts.Token = "token" - authInfoWithTokenAndCerts.ClientCertificate = "cert" - authInfoWithTokenAndCerts.ClientCertificateData = []byte("certdata") - authInfoWithTokenAndCerts.ClientKey = "key" - authInfoWithTokenAndCerts.ClientKeyData = []byte("keydata") - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.AuthInfos["another-user"] = authInfoWithCerts - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.AuthInfos["another-user"] = authInfoWithTokenAndCerts - - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagBearerToken + "=token"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestCertLeavesToken(t *testing.T) { - authInfoWithToken := clientcmdapi.NewAuthInfo() - authInfoWithToken.Token = "token" - - authInfoWithTokenAndCerts := clientcmdapi.NewAuthInfo() - authInfoWithTokenAndCerts.Token = "token" - authInfoWithTokenAndCerts.ClientCertificate = "/cert" - authInfoWithTokenAndCerts.ClientKey = "/key" - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.AuthInfos["another-user"] = authInfoWithToken - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.AuthInfos["another-user"] = authInfoWithTokenAndCerts - - test := configCommandTest{ - args: []string{"set-credentials", "another-user", "--" + clientcmd.FlagCertFile + "=/cert", "--" + clientcmd.FlagKeyFile + "=/key"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestCAClearsInsecure(t *testing.T) { - fakeCAFile, _ := ioutil.TempFile("", "ca-file") - - clusterInfoWithInsecure := clientcmdapi.NewCluster() - clusterInfoWithInsecure.InsecureSkipTLSVerify = true - - clusterInfoWithCA := clientcmdapi.NewCluster() - clusterInfoWithCA.CertificateAuthority = path.Base(fakeCAFile.Name()) - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.Clusters["another-cluster"] = clusterInfoWithInsecure - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.Clusters["another-cluster"] = clusterInfoWithCA - - test := configCommandTest{ - args: []string{"set-cluster", "another-cluster", "--" + clientcmd.FlagCAFile + "=" + fakeCAFile.Name()}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestCAClearsCAData(t *testing.T) { - clusterInfoWithCAData := clientcmdapi.NewCluster() - clusterInfoWithCAData.CertificateAuthorityData = []byte("cadata") - - clusterInfoWithCA := clientcmdapi.NewCluster() - clusterInfoWithCA.CertificateAuthority = "/cafile" - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.Clusters["another-cluster"] = clusterInfoWithCAData - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.Clusters["another-cluster"] = clusterInfoWithCA - - test := configCommandTest{ - args: []string{"set-cluster", "another-cluster", "--" + clientcmd.FlagCAFile + "=/cafile", "--" + clientcmd.FlagInsecure + "=false"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestInsecureClearsCA(t *testing.T) { - clusterInfoWithInsecure := clientcmdapi.NewCluster() - clusterInfoWithInsecure.InsecureSkipTLSVerify = true - - clusterInfoWithCA := clientcmdapi.NewCluster() - clusterInfoWithCA.CertificateAuthority = "cafile" - clusterInfoWithCA.CertificateAuthorityData = []byte("cadata") - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.Clusters["another-cluster"] = clusterInfoWithCA - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.Clusters["another-cluster"] = clusterInfoWithInsecure - - test := configCommandTest{ - args: []string{"set-cluster", "another-cluster", "--" + clientcmd.FlagInsecure + "=true"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestCADataClearsCA(t *testing.T) { - fakeCAFile, _ := ioutil.TempFile("", "") - defer os.Remove(fakeCAFile.Name()) - fakeData := []byte("cadata") - ioutil.WriteFile(fakeCAFile.Name(), fakeData, 0600) - - clusterInfoWithCAData := clientcmdapi.NewCluster() - clusterInfoWithCAData.CertificateAuthorityData = fakeData - - clusterInfoWithCA := clientcmdapi.NewCluster() - clusterInfoWithCA.CertificateAuthority = "cafile" - - startingConfig := newRedFederalCowHammerConfig() - startingConfig.Clusters["another-cluster"] = clusterInfoWithCA - - expectedConfig := newRedFederalCowHammerConfig() - expectedConfig.Clusters["another-cluster"] = clusterInfoWithCAData - - test := configCommandTest{ - args: []string{"set-cluster", "another-cluster", "--" + clientcmd.FlagCAFile + "=" + fakeCAFile.Name(), "--" + clientcmd.FlagEmbedCerts + "=true"}, - startingConfig: startingConfig, - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestEmbedNoCADisallowed(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - test := configCommandTest{ - args: []string{"set-cluster", "another-cluster", "--" + clientcmd.FlagEmbedCerts + "=true"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - expectedOutputs: []string{"--certificate-authority", "embed"}, - } - - test.run(t) -} - -func TestCAAndInsecureDisallowed(t *testing.T) { - test := configCommandTest{ - args: []string{"set-cluster", "another-cluster", "--" + clientcmd.FlagCAFile + "=cafile", "--" + clientcmd.FlagInsecure + "=true"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: newRedFederalCowHammerConfig(), - expectedOutputs: []string{"certificate", "insecure"}, - } - - test.run(t) -} - -func TestMergeExistingAuth(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - authInfo := expectedConfig.AuthInfos["red-user"] - authInfo.ClientKey = "/key" - expectedConfig.AuthInfos["red-user"] = authInfo - test := configCommandTest{ - args: []string{"set-credentials", "red-user", "--" + clientcmd.FlagKeyFile + "=/key"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestNewEmptyCluster(t *testing.T) { - expectedConfig := *clientcmdapi.NewConfig() - expectedConfig.Clusters["new-cluster"] = clientcmdapi.NewCluster() - test := configCommandTest{ - args: []string{"set-cluster", "new-cluster"}, - startingConfig: *clientcmdapi.NewConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestAdditionalCluster(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - cluster := clientcmdapi.NewCluster() - cluster.APIVersion = testapi.Default.GroupVersion().String() - cluster.CertificateAuthority = "/ca-location" - cluster.InsecureSkipTLSVerify = false - cluster.Server = "serverlocation" - expectedConfig.Clusters["different-cluster"] = cluster - test := configCommandTest{ - args: []string{"set-cluster", "different-cluster", "--" + clientcmd.FlagAPIServer + "=serverlocation", "--" + clientcmd.FlagInsecure + "=false", "--" + clientcmd.FlagCAFile + "=/ca-location", "--" + clientcmd.FlagAPIVersion + "=" + testapi.Default.GroupVersion().String()}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestOverwriteExistingCluster(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - cluster := clientcmdapi.NewCluster() - cluster.Server = "serverlocation" - expectedConfig.Clusters["cow-cluster"] = cluster - - test := configCommandTest{ - args: []string{"set-cluster", "cow-cluster", "--" + clientcmd.FlagAPIServer + "=serverlocation"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestNewEmptyContext(t *testing.T) { - expectedConfig := *clientcmdapi.NewConfig() - expectedConfig.Contexts["new-context"] = clientcmdapi.NewContext() - test := configCommandTest{ - args: []string{"set-context", "new-context"}, - startingConfig: *clientcmdapi.NewConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestAdditionalContext(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - context := clientcmdapi.NewContext() - context.Cluster = "some-cluster" - context.AuthInfo = "some-user" - context.Namespace = "different-namespace" - expectedConfig.Contexts["different-context"] = context - test := configCommandTest{ - args: []string{"set-context", "different-context", "--" + clientcmd.FlagClusterName + "=some-cluster", "--" + clientcmd.FlagAuthInfoName + "=some-user", "--" + clientcmd.FlagNamespace + "=different-namespace"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestMergeExistingContext(t *testing.T) { - expectedConfig := newRedFederalCowHammerConfig() - context := expectedConfig.Contexts["federal-context"] - context.Namespace = "hammer" - expectedConfig.Contexts["federal-context"] = context - - test := configCommandTest{ - args: []string{"set-context", "federal-context", "--" + clientcmd.FlagNamespace + "=hammer"}, - startingConfig: newRedFederalCowHammerConfig(), - expectedConfig: expectedConfig, - } - - test.run(t) -} - -func TestToBool(t *testing.T) { - type test struct { - in string - out bool - err string - } - - tests := []test{ - {"", false, ""}, - {"true", true, ""}, - {"on", false, `strconv.ParseBool: parsing "on": invalid syntax`}, - } - - for _, curr := range tests { - b, err := toBool(curr.in) - if (len(curr.err) != 0) && err == nil { - t.Errorf("Expected error: %v, but got nil", curr.err) - } - if (len(curr.err) == 0) && err != nil { - t.Errorf("Unexpected error: %v", err) - } - if (err != nil) && (err.Error() != curr.err) { - t.Errorf("Expected %v, got %v", curr.err, err) - - } - if b != curr.out { - t.Errorf("Expected %v, got %v", curr.out, b) - } - } - -} - -func testConfigCommand(args []string, startingConfig clientcmdapi.Config, t *testing.T) (string, clientcmdapi.Config) { - fakeKubeFile, _ := ioutil.TempFile("", "") - defer os.Remove(fakeKubeFile.Name()) - err := clientcmd.WriteToFile(startingConfig, fakeKubeFile.Name()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - argsToUse := make([]string, 0, 2+len(args)) - argsToUse = append(argsToUse, "--kubeconfig="+fakeKubeFile.Name()) - argsToUse = append(argsToUse, args...) - - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdConfig(NewDefaultPathOptions(), buf) - cmd.SetArgs(argsToUse) - cmd.Execute() - - // outBytes, _ := ioutil.ReadFile(fakeKubeFile.Name()) - config := getConfigFromFileOrDie(fakeKubeFile.Name()) - - return buf.String(), *config -} - -type configCommandTest struct { - args []string - startingConfig clientcmdapi.Config - expectedConfig clientcmdapi.Config - expectedOutputs []string -} - -func (test configCommandTest) run(t *testing.T) string { - out, actualConfig := testConfigCommand(test.args, test.startingConfig, t) - - testSetNilMapsToEmpties(reflect.ValueOf(&test.expectedConfig)) - testSetNilMapsToEmpties(reflect.ValueOf(&actualConfig)) - testClearLocationOfOrigin(&actualConfig) - - if !api.Semantic.DeepEqual(test.expectedConfig, actualConfig) { - t.Errorf("diff: %v", util.ObjectDiff(test.expectedConfig, actualConfig)) - t.Errorf("expected: %#v\n actual: %#v", test.expectedConfig, actualConfig) - } - - for _, expectedOutput := range test.expectedOutputs { - if !strings.Contains(out, expectedOutput) { - t.Errorf("expected '%s' in output, got '%s'", expectedOutput, out) - } - } - - return out -} -func testClearLocationOfOrigin(config *clientcmdapi.Config) { - for key, obj := range config.AuthInfos { - obj.LocationOfOrigin = "" - config.AuthInfos[key] = obj - } - for key, obj := range config.Clusters { - obj.LocationOfOrigin = "" - config.Clusters[key] = obj - } - for key, obj := range config.Contexts { - obj.LocationOfOrigin = "" - config.Contexts[key] = obj - } -} -func testSetNilMapsToEmpties(curr reflect.Value) { - actualCurrValue := curr - if curr.Kind() == reflect.Ptr { - actualCurrValue = curr.Elem() - } - - switch actualCurrValue.Kind() { - case reflect.Map: - for _, mapKey := range actualCurrValue.MapKeys() { - currMapValue := actualCurrValue.MapIndex(mapKey) - testSetNilMapsToEmpties(currMapValue) - } - - case reflect.Struct: - for fieldIndex := 0; fieldIndex < actualCurrValue.NumField(); fieldIndex++ { - currFieldValue := actualCurrValue.Field(fieldIndex) - - if currFieldValue.Kind() == reflect.Map && currFieldValue.IsNil() { - newValue := reflect.MakeMap(currFieldValue.Type()) - currFieldValue.Set(newValue) - } else { - testSetNilMapsToEmpties(currFieldValue.Addr()) - } - } - - } - -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_authinfo.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_authinfo.go deleted file mode 100644 index c61cd8c12..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_authinfo.go +++ /dev/null @@ -1,234 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "path/filepath" - "strings" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/util" -) - -type createAuthInfoOptions struct { - configAccess ConfigAccess - name string - authPath util.StringFlag - clientCertificate util.StringFlag - clientKey util.StringFlag - token util.StringFlag - username util.StringFlag - password util.StringFlag - embedCertData util.BoolFlag -} - -var create_authinfo_long = fmt.Sprintf(`Sets a user entry in kubeconfig -Specifying a name that already exists will merge new fields on top of existing values. - - Client-certificate flags: - --%v=certfile --%v=keyfile - - Bearer token flags: - --%v=bearer_token - - Basic auth flags: - --%v=basic_user --%v=basic_password - - Bearer token and basic auth are mutually exclusive. -`, clientcmd.FlagCertFile, clientcmd.FlagKeyFile, clientcmd.FlagBearerToken, clientcmd.FlagUsername, clientcmd.FlagPassword) - -const create_authinfo_example = `# Set only the "client-key" field on the "cluster-admin" -# entry, without touching other values: -$ kubectl config set-credentials cluster-admin --client-key=~/.kube/admin.key - -# Set basic auth for the "cluster-admin" entry -$ kubectl config set-credentials cluster-admin --username=admin --password=uXFGweU9l35qcif - -# Embed client certificate data in the "cluster-admin" entry -$ kubectl config set-credentials cluster-admin --client-certificate=~/.kube/admin.crt --embed-certs=true` - -func NewCmdConfigSetAuthInfo(out io.Writer, configAccess ConfigAccess) *cobra.Command { - options := &createAuthInfoOptions{configAccess: configAccess} - - cmd := &cobra.Command{ - Use: fmt.Sprintf("set-credentials NAME [--%v=path/to/certfile] [--%v=path/to/keyfile] [--%v=bearer_token] [--%v=basic_user] [--%v=basic_password]", clientcmd.FlagCertFile, clientcmd.FlagKeyFile, clientcmd.FlagBearerToken, clientcmd.FlagUsername, clientcmd.FlagPassword), - Short: "Sets a user entry in kubeconfig", - Long: create_authinfo_long, - Example: create_authinfo_example, - Run: func(cmd *cobra.Command, args []string) { - if !options.complete(cmd) { - return - } - - err := options.run() - if err != nil { - fmt.Fprintf(out, "%v\n", err) - } else { - fmt.Fprintf(out, "user %q set.\n", options.name) - } - }, - } - - cmd.Flags().Var(&options.clientCertificate, clientcmd.FlagCertFile, "path to "+clientcmd.FlagCertFile+" for the user entry in kubeconfig") - cmd.Flags().Var(&options.clientKey, clientcmd.FlagKeyFile, "path to "+clientcmd.FlagKeyFile+" for the user entry in kubeconfig") - cmd.Flags().Var(&options.token, clientcmd.FlagBearerToken, clientcmd.FlagBearerToken+" for the user entry in kubeconfig") - cmd.Flags().Var(&options.username, clientcmd.FlagUsername, clientcmd.FlagUsername+" for the user entry in kubeconfig") - cmd.Flags().Var(&options.password, clientcmd.FlagPassword, clientcmd.FlagPassword+" for the user entry in kubeconfig") - f := cmd.Flags().VarPF(&options.embedCertData, clientcmd.FlagEmbedCerts, "", "embed client cert/key for the user entry in kubeconfig") - f.NoOptDefVal = "true" - - return cmd -} - -func (o createAuthInfoOptions) run() error { - err := o.validate() - if err != nil { - return err - } - - config, err := o.configAccess.GetStartingConfig() - if err != nil { - return err - } - - startingStanza, exists := config.AuthInfos[o.name] - if !exists { - startingStanza = clientcmdapi.NewAuthInfo() - } - authInfo := o.modifyAuthInfo(*startingStanza) - config.AuthInfos[o.name] = &authInfo - - if err := ModifyConfig(o.configAccess, *config, true); err != nil { - return err - } - - return nil -} - -// authInfo builds an AuthInfo object from the options -func (o *createAuthInfoOptions) modifyAuthInfo(existingAuthInfo clientcmdapi.AuthInfo) clientcmdapi.AuthInfo { - modifiedAuthInfo := existingAuthInfo - - var setToken, setBasic bool - - if o.clientCertificate.Provided() { - certPath := o.clientCertificate.Value() - if o.embedCertData.Value() { - modifiedAuthInfo.ClientCertificateData, _ = ioutil.ReadFile(certPath) - modifiedAuthInfo.ClientCertificate = "" - } else { - certPath, _ = filepath.Abs(certPath) - modifiedAuthInfo.ClientCertificate = certPath - if len(modifiedAuthInfo.ClientCertificate) > 0 { - modifiedAuthInfo.ClientCertificateData = nil - } - } - } - if o.clientKey.Provided() { - keyPath := o.clientKey.Value() - if o.embedCertData.Value() { - modifiedAuthInfo.ClientKeyData, _ = ioutil.ReadFile(keyPath) - modifiedAuthInfo.ClientKey = "" - } else { - keyPath, _ = filepath.Abs(keyPath) - modifiedAuthInfo.ClientKey = keyPath - if len(modifiedAuthInfo.ClientKey) > 0 { - modifiedAuthInfo.ClientKeyData = nil - } - } - } - - if o.token.Provided() { - modifiedAuthInfo.Token = o.token.Value() - setToken = len(modifiedAuthInfo.Token) > 0 - } - - if o.username.Provided() { - modifiedAuthInfo.Username = o.username.Value() - setBasic = setBasic || len(modifiedAuthInfo.Username) > 0 - } - if o.password.Provided() { - modifiedAuthInfo.Password = o.password.Value() - setBasic = setBasic || len(modifiedAuthInfo.Password) > 0 - } - - // If any auth info was set, make sure any other existing auth types are cleared - if setToken || setBasic { - if !setToken { - modifiedAuthInfo.Token = "" - } - if !setBasic { - modifiedAuthInfo.Username = "" - modifiedAuthInfo.Password = "" - } - } - - return modifiedAuthInfo -} - -func (o *createAuthInfoOptions) complete(cmd *cobra.Command) bool { - args := cmd.Flags().Args() - if len(args) != 1 { - cmd.Help() - return false - } - - o.name = args[0] - return true -} - -func (o createAuthInfoOptions) validate() error { - if len(o.name) == 0 { - return errors.New("you must specify a non-empty user name") - } - methods := []string{} - if len(o.token.Value()) > 0 { - methods = append(methods, fmt.Sprintf("--%v", clientcmd.FlagBearerToken)) - } - if len(o.username.Value()) > 0 || len(o.password.Value()) > 0 { - methods = append(methods, fmt.Sprintf("--%v/--%v", clientcmd.FlagUsername, clientcmd.FlagPassword)) - } - if len(methods) > 1 { - return fmt.Errorf("you cannot specify more than one authentication method at the same time: %v", strings.Join(methods, ", ")) - } - if o.embedCertData.Value() { - certPath := o.clientCertificate.Value() - keyPath := o.clientKey.Value() - if certPath == "" && keyPath == "" { - return fmt.Errorf("you must specify a --%s or --%s to embed", clientcmd.FlagCertFile, clientcmd.FlagKeyFile) - } - if certPath != "" { - if _, err := ioutil.ReadFile(certPath); err != nil { - return fmt.Errorf("error reading %s data from %s: %v", clientcmd.FlagCertFile, certPath, err) - } - } - if keyPath != "" { - if _, err := ioutil.ReadFile(keyPath); err != nil { - return fmt.Errorf("error reading %s data from %s: %v", clientcmd.FlagKeyFile, keyPath, err) - } - } - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_cluster.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_cluster.go deleted file mode 100644 index 6f463a1b4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_cluster.go +++ /dev/null @@ -1,183 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "path/filepath" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/util" -) - -type createClusterOptions struct { - configAccess ConfigAccess - name string - server util.StringFlag - apiVersion util.StringFlag - insecureSkipTLSVerify util.BoolFlag - certificateAuthority util.StringFlag - embedCAData util.BoolFlag -} - -const ( - create_cluster_long = `Sets a cluster entry in kubeconfig. -Specifying a name that already exists will merge new fields on top of existing values for those fields.` - create_cluster_example = `# Set only the server field on the e2e cluster entry without touching other values. -$ kubectl config set-cluster e2e --server=https://1.2.3.4 - -# Embed certificate authority data for the e2e cluster entry -$ kubectl config set-cluster e2e --certificate-authority=~/.kube/e2e/kubernetes.ca.crt - -# Disable cert checking for the dev cluster entry -$ kubectl config set-cluster e2e --insecure-skip-tls-verify=true` -) - -func NewCmdConfigSetCluster(out io.Writer, configAccess ConfigAccess) *cobra.Command { - options := &createClusterOptions{configAccess: configAccess} - - cmd := &cobra.Command{ - Use: fmt.Sprintf("set-cluster NAME [--%v=server] [--%v=path/to/certficate/authority] [--%v=apiversion] [--%v=true]", clientcmd.FlagAPIServer, clientcmd.FlagCAFile, clientcmd.FlagAPIVersion, clientcmd.FlagInsecure), - Short: "Sets a cluster entry in kubeconfig", - Long: create_cluster_long, - Example: create_cluster_example, - Run: func(cmd *cobra.Command, args []string) { - if !options.complete(cmd) { - return - } - - err := options.run() - if err != nil { - fmt.Fprintf(out, "%v\n", err) - } else { - fmt.Fprintf(out, "cluster %q set.\n", options.name) - } - }, - } - - options.insecureSkipTLSVerify.Default(false) - - cmd.Flags().Var(&options.server, clientcmd.FlagAPIServer, clientcmd.FlagAPIServer+" for the cluster entry in kubeconfig") - cmd.Flags().Var(&options.apiVersion, clientcmd.FlagAPIVersion, clientcmd.FlagAPIVersion+" for the cluster entry in kubeconfig") - f := cmd.Flags().VarPF(&options.insecureSkipTLSVerify, clientcmd.FlagInsecure, "", clientcmd.FlagInsecure+" for the cluster entry in kubeconfig") - f.NoOptDefVal = "true" - cmd.Flags().Var(&options.certificateAuthority, clientcmd.FlagCAFile, "path to "+clientcmd.FlagCAFile+" for the cluster entry in kubeconfig") - f = cmd.Flags().VarPF(&options.embedCAData, clientcmd.FlagEmbedCerts, "", clientcmd.FlagEmbedCerts+" for the cluster entry in kubeconfig") - f.NoOptDefVal = "true" - - return cmd -} - -func (o createClusterOptions) run() error { - err := o.validate() - if err != nil { - return err - } - - config, err := o.configAccess.GetStartingConfig() - if err != nil { - return err - } - - startingStanza, exists := config.Clusters[o.name] - if !exists { - startingStanza = clientcmdapi.NewCluster() - } - cluster := o.modifyCluster(*startingStanza) - config.Clusters[o.name] = &cluster - - if err := ModifyConfig(o.configAccess, *config, true); err != nil { - return err - } - - return nil -} - -// cluster builds a Cluster object from the options -func (o *createClusterOptions) modifyCluster(existingCluster clientcmdapi.Cluster) clientcmdapi.Cluster { - modifiedCluster := existingCluster - - if o.server.Provided() { - modifiedCluster.Server = o.server.Value() - } - if o.apiVersion.Provided() { - modifiedCluster.APIVersion = o.apiVersion.Value() - } - if o.insecureSkipTLSVerify.Provided() { - modifiedCluster.InsecureSkipTLSVerify = o.insecureSkipTLSVerify.Value() - // Specifying insecure mode clears any certificate authority - if modifiedCluster.InsecureSkipTLSVerify { - modifiedCluster.CertificateAuthority = "" - modifiedCluster.CertificateAuthorityData = nil - } - } - if o.certificateAuthority.Provided() { - caPath := o.certificateAuthority.Value() - if o.embedCAData.Value() { - modifiedCluster.CertificateAuthorityData, _ = ioutil.ReadFile(caPath) - modifiedCluster.InsecureSkipTLSVerify = false - modifiedCluster.CertificateAuthority = "" - } else { - caPath, _ = filepath.Abs(caPath) - modifiedCluster.CertificateAuthority = caPath - // Specifying a certificate authority file clears certificate authority data and insecure mode - if caPath != "" { - modifiedCluster.InsecureSkipTLSVerify = false - modifiedCluster.CertificateAuthorityData = nil - } - } - } - - return modifiedCluster -} - -func (o *createClusterOptions) complete(cmd *cobra.Command) bool { - args := cmd.Flags().Args() - if len(args) != 1 { - cmd.Help() - return false - } - - o.name = args[0] - return true -} - -func (o createClusterOptions) validate() error { - if len(o.name) == 0 { - return errors.New("you must specify a non-empty cluster name") - } - if o.insecureSkipTLSVerify.Value() && o.certificateAuthority.Value() != "" { - return errors.New("you cannot specify a certificate authority and insecure mode at the same time") - } - if o.embedCAData.Value() { - caPath := o.certificateAuthority.Value() - if caPath == "" { - return fmt.Errorf("you must specify a --%s to embed", clientcmd.FlagCAFile) - } - if _, err := ioutil.ReadFile(caPath); err != nil { - return fmt.Errorf("could not read %s data from %s: %v", clientcmd.FlagCAFile, caPath, err) - } - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_context.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_context.go deleted file mode 100644 index 093ce944c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/create_context.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/util" -) - -type createContextOptions struct { - configAccess ConfigAccess - name string - cluster util.StringFlag - authInfo util.StringFlag - namespace util.StringFlag -} - -const ( - create_context_long = `Sets a context entry in kubeconfig -Specifying a name that already exists will merge new fields on top of existing values for those fields.` - create_context_example = `# Set the user field on the gce context entry without touching other values -$ kubectl config set-context gce --user=cluster-admin` -) - -func NewCmdConfigSetContext(out io.Writer, configAccess ConfigAccess) *cobra.Command { - options := &createContextOptions{configAccess: configAccess} - - cmd := &cobra.Command{ - Use: fmt.Sprintf("set-context NAME [--%v=cluster_nickname] [--%v=user_nickname] [--%v=namespace]", clientcmd.FlagClusterName, clientcmd.FlagAuthInfoName, clientcmd.FlagNamespace), - Short: "Sets a context entry in kubeconfig", - Long: create_context_long, - Example: create_context_example, - Run: func(cmd *cobra.Command, args []string) { - if !options.complete(cmd) { - return - } - - err := options.run() - if err != nil { - fmt.Fprintf(out, "%v\n", err) - } else { - fmt.Fprintf(out, "context %q set.\n", options.name) - } - }, - } - - cmd.Flags().Var(&options.cluster, clientcmd.FlagClusterName, clientcmd.FlagClusterName+" for the context entry in kubeconfig") - cmd.Flags().Var(&options.authInfo, clientcmd.FlagAuthInfoName, clientcmd.FlagAuthInfoName+" for the context entry in kubeconfig") - cmd.Flags().Var(&options.namespace, clientcmd.FlagNamespace, clientcmd.FlagNamespace+" for the context entry in kubeconfig") - - return cmd -} - -func (o createContextOptions) run() error { - err := o.validate() - if err != nil { - return err - } - - config, err := o.configAccess.GetStartingConfig() - if err != nil { - return err - } - - startingStanza, exists := config.Contexts[o.name] - if !exists { - startingStanza = clientcmdapi.NewContext() - } - context := o.modifyContext(*startingStanza) - config.Contexts[o.name] = &context - - if err := ModifyConfig(o.configAccess, *config, true); err != nil { - return err - } - - return nil -} - -func (o *createContextOptions) modifyContext(existingContext clientcmdapi.Context) clientcmdapi.Context { - modifiedContext := existingContext - - if o.cluster.Provided() { - modifiedContext.Cluster = o.cluster.Value() - } - if o.authInfo.Provided() { - modifiedContext.AuthInfo = o.authInfo.Value() - } - if o.namespace.Provided() { - modifiedContext.Namespace = o.namespace.Value() - } - - return modifiedContext -} - -func (o *createContextOptions) complete(cmd *cobra.Command) bool { - args := cmd.Flags().Args() - if len(args) != 1 { - cmd.Help() - return false - } - - o.name = args[0] - return true -} - -func (o createContextOptions) validate() error { - if len(o.name) == 0 { - return errors.New("you must specify a non-empty context name") - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/current_context.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/current_context.go deleted file mode 100644 index 66e8f78b3..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/current_context.go +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "fmt" - "io" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - - "github.com/spf13/cobra" -) - -type CurrentContextOptions struct { - ConfigAccess ConfigAccess -} - -const ( - current_context_long = `Displays the current-context` - current_context_example = `# Display the current-context -$ kubectl config current-context` -) - -func NewCmdConfigCurrentContext(out io.Writer, configAccess ConfigAccess) *cobra.Command { - options := &CurrentContextOptions{ConfigAccess: configAccess} - - cmd := &cobra.Command{ - Use: "current-context", - Short: "Displays the current-context", - Long: current_context_long, - Example: current_context_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunCurrentContext(out, args, options) - cmdutil.CheckErr(err) - }, - } - - return cmd -} - -func RunCurrentContext(out io.Writer, args []string, options *CurrentContextOptions) error { - config, err := options.ConfigAccess.GetStartingConfig() - if err != nil { - return err - } - - if config.CurrentContext == "" { - err = fmt.Errorf("current-context is not set\n") - return err - } - - fmt.Fprintf(out, "%s\n", config.CurrentContext) - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/current_context_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/current_context_test.go deleted file mode 100644 index 169c65443..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/current_context_test.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "bytes" - "io/ioutil" - "os" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" -) - -type currentContextTest struct { - startingConfig clientcmdapi.Config - expectedError string -} - -func newFederalContextConfig() clientcmdapi.Config { - return clientcmdapi.Config{ - CurrentContext: "federal-context", - } -} - -func TestCurrentContextWithSetContext(t *testing.T) { - test := currentContextTest{ - startingConfig: newFederalContextConfig(), - expectedError: "", - } - - test.run(t) -} - -func TestCurrentContextWithUnsetContext(t *testing.T) { - test := currentContextTest{ - startingConfig: *clientcmdapi.NewConfig(), - expectedError: "current-context is not set", - } - - test.run(t) -} - -func (test currentContextTest) run(t *testing.T) { - fakeKubeFile, _ := ioutil.TempFile("", "") - defer os.Remove(fakeKubeFile.Name()) - err := clientcmd.WriteToFile(test.startingConfig, fakeKubeFile.Name()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - pathOptions := NewDefaultPathOptions() - pathOptions.GlobalFile = fakeKubeFile.Name() - pathOptions.EnvVar = "" - options := CurrentContextOptions{ - ConfigAccess: pathOptions, - } - - buf := bytes.NewBuffer([]byte{}) - err = RunCurrentContext(buf, []string{}, &options) - if len(test.expectedError) != 0 { - if err == nil { - t.Errorf("Did not get %v", test.expectedError) - } else { - if !strings.Contains(err.Error(), test.expectedError) { - t.Errorf("Expected %v, but got %v", test.expectedError, err) - } - } - return - } - - if err != nil { - t.Errorf("Unexpected error: %v", err) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/navigation_step_parser.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/navigation_step_parser.go deleted file mode 100644 index 0be5f241e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/navigation_step_parser.go +++ /dev/null @@ -1,152 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "fmt" - "reflect" - "strings" - - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/util/sets" -) - -type navigationSteps struct { - steps []navigationStep - currentStepIndex int -} - -type navigationStep struct { - stepValue string - stepType reflect.Type -} - -func newNavigationSteps(path string) (*navigationSteps, error) { - steps := []navigationStep{} - individualParts := strings.Split(path, ".") - - currType := reflect.TypeOf(clientcmdapi.Config{}) - currPartIndex := 0 - for currPartIndex < len(individualParts) { - switch currType.Kind() { - case reflect.Map: - // if we're in a map, we need to locate a name. That name may contain dots, so we need to know what tokens are legal for the map's value type - // for example, we could have a set request like: `set clusters.10.10.12.56.insecure-skip-tls-verify true`. We enter this case with - // steps representing 10, 10, 12, 56, insecure-skip-tls-verify. The name is "10.10.12.56", so we want to collect all those parts together and - // store them as a single step. In order to do that, we need to determine what set of tokens is a legal step AFTER the name of the map key - // This set of reflective code pulls the type of the map values, uses that type to look up the set of legal tags. Those legal tags are used to - // walk the list of remaining parts until we find a match to a legal tag or the end of the string. That name is used to burn all the used parts. - mapValueType := currType.Elem().Elem() - mapValueOptions, err := getPotentialTypeValues(mapValueType) - if err != nil { - return nil, err - } - nextPart := findNameStep(individualParts[currPartIndex:], sets.StringKeySet(mapValueOptions)) - - steps = append(steps, navigationStep{nextPart, mapValueType}) - currPartIndex += len(strings.Split(nextPart, ".")) - currType = mapValueType - - case reflect.Struct: - nextPart := individualParts[currPartIndex] - - options, err := getPotentialTypeValues(currType) - if err != nil { - return nil, err - } - fieldType, exists := options[nextPart] - if !exists { - return nil, fmt.Errorf("unable to parse %v after %v at %v", path, steps, currType) - } - - steps = append(steps, navigationStep{nextPart, fieldType}) - currPartIndex += len(strings.Split(nextPart, ".")) - currType = fieldType - } - } - - return &navigationSteps{steps, 0}, nil -} - -func (s *navigationSteps) pop() navigationStep { - if s.moreStepsRemaining() { - s.currentStepIndex++ - return s.steps[s.currentStepIndex-1] - } - return navigationStep{} -} - -func (s *navigationSteps) peek() navigationStep { - if s.moreStepsRemaining() { - return s.steps[s.currentStepIndex] - } - return navigationStep{} -} - -func (s *navigationSteps) moreStepsRemaining() bool { - return len(s.steps) > s.currentStepIndex -} - -// findNameStep takes the list of parts and a set of valid tags that can be used after the name. It then walks the list of parts -// until it find a valid "next" tag or until it reaches the end of the parts and then builds the name back up out of the individual parts -func findNameStep(parts []string, typeOptions sets.String) string { - if len(parts) == 0 { - return "" - } - - numberOfPartsInStep := findKnownValue(parts[1:], typeOptions) + 1 - // if we didn't find a known value, then the entire thing must be a name - if numberOfPartsInStep == 0 { - numberOfPartsInStep = len(parts) - } - nextParts := parts[0:numberOfPartsInStep] - - return strings.Join(nextParts, ".") -} - -// getPotentialTypeValues takes a type and looks up the tags used to represent its fields when serialized. -func getPotentialTypeValues(typeValue reflect.Type) (map[string]reflect.Type, error) { - if typeValue.Kind() == reflect.Ptr { - typeValue = typeValue.Elem() - } - - if typeValue.Kind() != reflect.Struct { - return nil, fmt.Errorf("%v is not of type struct", typeValue) - } - - ret := make(map[string]reflect.Type) - - for fieldIndex := 0; fieldIndex < typeValue.NumField(); fieldIndex++ { - fieldType := typeValue.Field(fieldIndex) - yamlTag := fieldType.Tag.Get("json") - yamlTagName := strings.Split(yamlTag, ",")[0] - - ret[yamlTagName] = fieldType.Type - } - - return ret, nil -} - -func findKnownValue(parts []string, valueOptions sets.String) int { - for i := range parts { - if valueOptions.Has(parts[i]) { - return i - } - } - - return -1 -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/navigation_step_parser_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/navigation_step_parser_test.go deleted file mode 100644 index 3ec3c40ff..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/navigation_step_parser_test.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "reflect" - "strings" - "testing" - - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/util" -) - -type stepParserTest struct { - path string - expectedNavigationSteps navigationSteps - expectedError string -} - -func TestParseWithDots(t *testing.T) { - test := stepParserTest{ - path: "clusters.my.dot.delimited.name.server", - expectedNavigationSteps: navigationSteps{ - steps: []navigationStep{ - {"clusters", reflect.TypeOf(make(map[string]*clientcmdapi.Cluster))}, - {"my.dot.delimited.name", reflect.TypeOf(clientcmdapi.Cluster{})}, - {"server", reflect.TypeOf("")}, - }, - }, - } - - test.run(t) -} - -func TestParseWithDotsEndingWithName(t *testing.T) { - test := stepParserTest{ - path: "contexts.10.12.12.12", - expectedNavigationSteps: navigationSteps{ - steps: []navigationStep{ - {"contexts", reflect.TypeOf(make(map[string]*clientcmdapi.Context))}, - {"10.12.12.12", reflect.TypeOf(clientcmdapi.Context{})}, - }, - }, - } - - test.run(t) -} - -func TestParseWithBadValue(t *testing.T) { - test := stepParserTest{ - path: "user.bad", - expectedNavigationSteps: navigationSteps{ - steps: []navigationStep{}, - }, - expectedError: "unable to parse user.bad after [] at api.Config", - } - - test.run(t) -} - -func (test stepParserTest) run(t *testing.T) { - actualSteps, err := newNavigationSteps(test.path) - if len(test.expectedError) != 0 { - if err == nil { - t.Errorf("Did not get %v", test.expectedError) - } else { - if !strings.Contains(err.Error(), test.expectedError) { - t.Errorf("Expected %v, but got %v", test.expectedError, err) - } - } - return - } - - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if !reflect.DeepEqual(test.expectedNavigationSteps, *actualSteps) { - t.Errorf("diff: %v", util.ObjectDiff(test.expectedNavigationSteps, *actualSteps)) - t.Errorf("expected: %#v\n actual: %#v", test.expectedNavigationSteps, *actualSteps) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/set.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/set.go deleted file mode 100644 index c175a23c2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/set.go +++ /dev/null @@ -1,208 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "fmt" - "io" - "reflect" - "strings" - - "github.com/spf13/cobra" -) - -const ( - cannotHaveStepsAfterError = "Cannot have steps after %v. %v are remaining" - additionStepRequiredUnlessUnsettingError = "Must have additional steps after %v unless you are unsetting it" -) - -type setOptions struct { - configAccess ConfigAccess - propertyName string - propertyValue string -} - -const set_long = `Sets an individual value in a kubeconfig file -PROPERTY_NAME is a dot delimited name where each token represents either a attribute name or a map key. Map keys may not contain dots. -PROPERTY_VALUE is the new value you wish to set.` - -func NewCmdConfigSet(out io.Writer, configAccess ConfigAccess) *cobra.Command { - options := &setOptions{configAccess: configAccess} - - cmd := &cobra.Command{ - Use: "set PROPERTY_NAME PROPERTY_VALUE", - Short: "Sets an individual value in a kubeconfig file", - Long: set_long, - Run: func(cmd *cobra.Command, args []string) { - if !options.complete(cmd) { - return - } - - err := options.run() - if err != nil { - fmt.Fprintf(out, "%v\n", err) - } else { - fmt.Fprintf(out, "property %q set.\n", options.propertyName) - } - }, - } - - return cmd -} - -func (o setOptions) run() error { - err := o.validate() - if err != nil { - return err - } - - config, err := o.configAccess.GetStartingConfig() - if err != nil { - return err - } - steps, err := newNavigationSteps(o.propertyName) - if err != nil { - return err - } - err = modifyConfig(reflect.ValueOf(config), steps, o.propertyValue, false) - if err != nil { - return err - } - - if err := ModifyConfig(o.configAccess, *config, false); err != nil { - return err - } - - return nil -} - -func (o *setOptions) complete(cmd *cobra.Command) bool { - endingArgs := cmd.Flags().Args() - if len(endingArgs) != 2 { - cmd.Help() - return false - } - - o.propertyValue = endingArgs[1] - o.propertyName = endingArgs[0] - return true -} - -func (o setOptions) validate() error { - if len(o.propertyValue) == 0 { - return errors.New("you cannot use set to unset a property") - } - - if len(o.propertyName) == 0 { - return errors.New("you must specify a property") - } - - return nil -} - -func modifyConfig(curr reflect.Value, steps *navigationSteps, propertyValue string, unset bool) error { - currStep := steps.pop() - - actualCurrValue := curr - if curr.Kind() == reflect.Ptr { - actualCurrValue = curr.Elem() - } - - switch actualCurrValue.Kind() { - case reflect.Map: - if !steps.moreStepsRemaining() && !unset { - return fmt.Errorf("can't set a map to a value: %v", actualCurrValue) - } - - mapKey := reflect.ValueOf(currStep.stepValue) - mapValueType := curr.Type().Elem().Elem() - - if !steps.moreStepsRemaining() && unset { - actualCurrValue.SetMapIndex(mapKey, reflect.Value{}) - return nil - } - - currMapValue := actualCurrValue.MapIndex(mapKey) - - needToSetNewMapValue := currMapValue.Kind() == reflect.Invalid - if needToSetNewMapValue { - currMapValue = reflect.New(mapValueType.Elem()).Elem().Addr() - actualCurrValue.SetMapIndex(mapKey, currMapValue) - } - - err := modifyConfig(currMapValue, steps, propertyValue, unset) - if err != nil { - return err - } - - return nil - - case reflect.String: - if steps.moreStepsRemaining() { - return fmt.Errorf("can't have more steps after a string. %v", steps) - } - actualCurrValue.SetString(propertyValue) - return nil - - case reflect.Bool: - if steps.moreStepsRemaining() { - return fmt.Errorf("can't have more steps after a bool. %v", steps) - } - boolValue, err := toBool(propertyValue) - if err != nil { - return err - } - actualCurrValue.SetBool(boolValue) - return nil - - case reflect.Struct: - for fieldIndex := 0; fieldIndex < actualCurrValue.NumField(); fieldIndex++ { - currFieldValue := actualCurrValue.Field(fieldIndex) - currFieldType := actualCurrValue.Type().Field(fieldIndex) - currYamlTag := currFieldType.Tag.Get("json") - currFieldTypeYamlName := strings.Split(currYamlTag, ",")[0] - - if currFieldTypeYamlName == currStep.stepValue { - thisMapHasNoValue := (currFieldValue.Kind() == reflect.Map && currFieldValue.IsNil()) - - if thisMapHasNoValue { - newValue := reflect.MakeMap(currFieldValue.Type()) - currFieldValue.Set(newValue) - - if !steps.moreStepsRemaining() && unset { - return nil - } - } - - if !steps.moreStepsRemaining() && unset { - // if we're supposed to unset the value or if the value is a map that doesn't exist, create a new value and overwrite - newValue := reflect.New(currFieldValue.Type()).Elem() - currFieldValue.Set(newValue) - return nil - } - - return modifyConfig(currFieldValue.Addr(), steps, propertyValue, unset) - } - } - - return fmt.Errorf("unable to locate path %#v under %v", currStep, actualCurrValue) - - } - - panic(fmt.Errorf("unrecognized type: %v", actualCurrValue)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/unset.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/unset.go deleted file mode 100644 index 555309ccb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/unset.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "fmt" - "io" - "reflect" - - "github.com/spf13/cobra" -) - -type unsetOptions struct { - configAccess ConfigAccess - propertyName string -} - -const unset_long = `Unsets an individual value in a kubeconfig file -PROPERTY_NAME is a dot delimited name where each token represents either a attribute name or a map key. Map keys may not contain dots.` - -func NewCmdConfigUnset(out io.Writer, configAccess ConfigAccess) *cobra.Command { - options := &unsetOptions{configAccess: configAccess} - - cmd := &cobra.Command{ - Use: "unset PROPERTY_NAME", - Short: "Unsets an individual value in a kubeconfig file", - Long: unset_long, - Run: func(cmd *cobra.Command, args []string) { - if !options.complete(cmd) { - return - } - - err := options.run() - if err != nil { - fmt.Fprintf(out, "%v\n", err) - } else { - fmt.Fprintf(out, "property %q unset.\n", options.propertyName) - } - }, - } - - return cmd -} - -func (o unsetOptions) run() error { - err := o.validate() - if err != nil { - return err - } - - config, err := o.configAccess.GetStartingConfig() - if err != nil { - return err - } - - steps, err := newNavigationSteps(o.propertyName) - if err != nil { - return err - } - err = modifyConfig(reflect.ValueOf(config), steps, "", true) - if err != nil { - return err - } - - if err := ModifyConfig(o.configAccess, *config, false); err != nil { - return err - } - - return nil -} - -func (o *unsetOptions) complete(cmd *cobra.Command) bool { - endingArgs := cmd.Flags().Args() - if len(endingArgs) != 1 { - cmd.Help() - return false - } - - o.propertyName = endingArgs[0] - return true -} - -func (o unsetOptions) validate() error { - if len(o.propertyName) == 0 { - return errors.New("you must specify a property") - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/use_context.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/use_context.go deleted file mode 100644 index a6a5c26d5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/use_context.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "fmt" - "io" - - "github.com/spf13/cobra" - - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" -) - -type useContextOptions struct { - configAccess ConfigAccess - contextName string -} - -func NewCmdConfigUseContext(out io.Writer, configAccess ConfigAccess) *cobra.Command { - options := &useContextOptions{configAccess: configAccess} - - cmd := &cobra.Command{ - Use: "use-context CONTEXT_NAME", - Short: "Sets the current-context in a kubeconfig file", - Long: `Sets the current-context in a kubeconfig file`, - Run: func(cmd *cobra.Command, args []string) { - if !options.complete(cmd) { - return - } - - err := options.run() - if err != nil { - fmt.Fprintf(out, "%v\n", err) - } else { - fmt.Fprintf(out, "switched to context %q.\n", options.contextName) - } - }, - } - - return cmd -} - -func (o useContextOptions) run() error { - config, err := o.configAccess.GetStartingConfig() - if err != nil { - return err - } - - err = o.validate(config) - if err != nil { - return err - } - - config.CurrentContext = o.contextName - - if err := ModifyConfig(o.configAccess, *config, true); err != nil { - return err - } - - return nil -} - -func (o *useContextOptions) complete(cmd *cobra.Command) bool { - endingArgs := cmd.Flags().Args() - if len(endingArgs) != 1 { - cmd.Help() - return false - } - - o.contextName = endingArgs[0] - return true -} - -func (o useContextOptions) validate(config *clientcmdapi.Config) error { - if len(o.contextName) == 0 { - return errors.New("you must specify a current-context") - } - - for name := range config.Contexts { - if name == o.contextName { - return nil - } - } - - return fmt.Errorf("no context exists with the name: %q.", o.contextName) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/view.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/view.go deleted file mode 100644 index 50bdb30ad..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/config/view.go +++ /dev/null @@ -1,158 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "errors" - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/util" -) - -type ViewOptions struct { - ConfigAccess ConfigAccess - Merge util.BoolFlag - Flatten bool - Minify bool - RawByteData bool -} - -const ( - view_long = `Displays merged kubeconfig settings or a specified kubeconfig file. - -You can use --output jsonpath={...} to extract specific values using a jsonpath expression.` - view_example = `# Show Merged kubeconfig settings. -$ kubectl config view - -# Get the password for the e2e user -$ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'` -) - -func NewCmdConfigView(out io.Writer, ConfigAccess ConfigAccess) *cobra.Command { - options := &ViewOptions{ConfigAccess: ConfigAccess} - // Default to yaml - defaultOutputFormat := "yaml" - - cmd := &cobra.Command{ - Use: "view", - Short: "Displays merged kubeconfig settings or a specified kubeconfig file.", - Long: view_long, - Example: view_example, - Run: func(cmd *cobra.Command, args []string) { - options.Complete() - outputFormat := cmdutil.GetFlagString(cmd, "output") - if outputFormat == "wide" { - fmt.Printf("--output wide is not available in kubectl config view; reset to default output format (%s)\n\n", defaultOutputFormat) - cmd.Flags().Set("output", defaultOutputFormat) - } - - printer, _, err := cmdutil.PrinterForCommand(cmd) - cmdutil.CheckErr(err) - version, err := cmdutil.OutputVersion(cmd, &latest.ExternalVersion) - cmdutil.CheckErr(err) - printer = kubectl.NewVersionedPrinter(printer, clientcmdapi.Scheme, version) - - cmdutil.CheckErr(options.Run(out, printer)) - }, - } - - cmdutil.AddPrinterFlags(cmd) - cmd.Flags().Set("output", defaultOutputFormat) - - options.Merge.Default(true) - f := cmd.Flags().VarPF(&options.Merge, "merge", "", "merge together the full hierarchy of kubeconfig files") - f.NoOptDefVal = "true" - cmd.Flags().BoolVar(&options.RawByteData, "raw", false, "display raw byte data") - cmd.Flags().BoolVar(&options.Flatten, "flatten", false, "flatten the resulting kubeconfig file into self contained output (useful for creating portable kubeconfig files)") - cmd.Flags().BoolVar(&options.Minify, "minify", false, "remove all information not used by current-context from the output") - return cmd -} - -func (o ViewOptions) Run(out io.Writer, printer kubectl.ResourcePrinter) error { - config, err := o.loadConfig() - if err != nil { - return err - } - - if o.Minify { - if err := clientcmdapi.MinifyConfig(config); err != nil { - return err - } - } - - if o.Flatten { - if err := clientcmdapi.FlattenConfig(config); err != nil { - return err - } - } else if !o.RawByteData { - clientcmdapi.ShortenConfig(config) - } - - err = printer.PrintObj(config, out) - if err != nil { - return err - } - - return nil -} - -func (o *ViewOptions) Complete() bool { - if o.ConfigAccess.IsExplicitFile() { - if !o.Merge.Provided() { - o.Merge.Set("false") - } - } - - return true -} - -func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error) { - err := o.Validate() - if err != nil { - return nil, err - } - - config, err := o.getStartingConfig() - return config, err -} - -func (o ViewOptions) Validate() error { - if !o.Merge.Value() && !o.ConfigAccess.IsExplicitFile() { - return errors.New("if merge==false a precise file must to specified") - } - - return nil -} - -// getStartingConfig returns the Config object built from the sources specified by the options, the filename read (only if it was a single file), and an error if something goes wrong -func (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error) { - switch { - case !o.Merge.Value(): - return clientcmd.LoadFromFile(o.ConfigAccess.GetExplicitFile()) - - default: - return o.ConfigAccess.GetStartingConfig() - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/convert.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/convert.go deleted file mode 100644 index e7e04d5b9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/convert.go +++ /dev/null @@ -1,164 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - - "github.com/spf13/cobra" -) - -const ( - convert_long = `Convert config files between different API versions. Both YAML -and JSON formats are accepted. - -The command takes filename, directory, or URL as input, and convert it into format -of version specified by --output-version flag. If target version is not specified or -not supported, convert to latest version. - -The default output will be printed to stdout in YAML format. One can use -o option -to change to output destination. -` - convert_example = `# Convert 'pod.yaml' to latest version and print to stdout. -$ kubectl convert -f pod.yaml - -# Convert the live state of the resource specified by 'pod.yaml' to the latest version -# and print to stdout in json format. -$ kubectl convert -f pod.yaml --local -o json - -# Convert all files under current directory to latest version and create them all. -$ kubectl convert -f . | kubectl create -f - -` -) - -// NewCmdConvert creates a command object for the generic "convert" action, which -// translates the config file into a given version. -func NewCmdConvert(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &ConvertOptions{} - - cmd := &cobra.Command{ - Use: "convert -f FILENAME", - Short: "Convert config files between different API versions", - Long: convert_long, - Example: convert_example, - Run: func(cmd *cobra.Command, args []string) { - err := options.Complete(f, out, cmd, args) - cmdutil.CheckErr(err) - err = options.RunConvert() - cmdutil.CheckErr(err) - }, - } - - usage := "Filename, directory, or URL to file to need to get converted." - kubectl.AddJsonFilenameFlag(cmd, &options.filenames, usage) - cmd.MarkFlagRequired("filename") - cmdutil.AddValidateFlags(cmd) - cmdutil.AddPrinterFlags(cmd) - cmd.Flags().BoolVar(&options.local, "local", true, "If true, convert will NOT try to contact api-server but run locally.") - - return cmd -} - -// ConvertOptions have the data required to perform the convert operation -type ConvertOptions struct { - builder *resource.Builder - filenames []string - local bool - - encoder runtime.Encoder - out io.Writer - printer kubectl.ResourcePrinter - - outputVersion unversioned.GroupVersion -} - -// Complete collects information required to run Convert command from command line. -func (o *ConvertOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) { - o.outputVersion, err = cmdutil.OutputVersion(cmd, ®istered.EnabledVersionsForGroup(api.GroupName)[0]) - if err != nil { - return err - } - if !registered.IsEnabledVersion(o.outputVersion) { - cmdutil.UsageError(cmd, "'%s' is not a registered version.", o.outputVersion) - } - - // build the builder - mapper, typer := f.Object() - clientMapper := resource.ClientMapperFunc(f.ClientForMapping) - if o.local { - fmt.Fprintln(out, "running in local mode...") - o.builder = resource.NewBuilder(mapper, typer, resource.DisabledClientForMapping{clientMapper}, f.Decoder(true)) - } else { - o.builder = resource.NewBuilder(mapper, typer, clientMapper, f.Decoder(true)) - schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) - if err != nil { - return err - } - o.builder = o.builder.Schema(schema) - } - cmdNamespace, _, err := f.DefaultNamespace() - if err != nil { - return err - } - o.builder = o.builder.NamespaceParam(cmdNamespace). - ContinueOnError(). - FilenameParam(false, o.filenames...). - Flatten() - - // build the printer - o.out = out - outputFormat := cmdutil.GetFlagString(cmd, "output") - templateFile := cmdutil.GetFlagString(cmd, "template") - if len(outputFormat) == 0 { - if len(templateFile) == 0 { - outputFormat = "yaml" - } else { - outputFormat = "template" - } - } - o.encoder = f.JSONEncoder() - o.printer, _, err = kubectl.GetPrinter(outputFormat, templateFile) - if err != nil { - return err - } - - return nil -} - -// RunConvert implements the generic Convert command -func (o *ConvertOptions) RunConvert() error { - infos, err := o.builder.Do().Infos() - if err != nil { - return err - } - - objects, err := resource.AsVersionedObject(infos, false, o.outputVersion.String(), o.encoder) - if err != nil { - return err - } - - return o.printer.PrintObj(objects, o.out) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create.go deleted file mode 100644 index 612ebd191..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create.go +++ /dev/null @@ -1,258 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "strings" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" -) - -// CreateOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type CreateOptions struct { - Filenames []string -} - -const ( - create_long = `Create a resource by filename or stdin. - -JSON and YAML formats are accepted.` - create_example = `# Create a pod using the data in pod.json. -$ kubectl create -f ./pod.json - -# Create a pod based on the JSON passed into stdin. -$ cat pod.json | kubectl create -f -` -) - -func NewCmdCreate(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &CreateOptions{} - - cmd := &cobra.Command{ - Use: "create -f FILENAME", - Short: "Create a resource by filename or stdin", - Long: create_long, - Example: create_example, - Run: func(cmd *cobra.Command, args []string) { - if len(options.Filenames) == 0 { - cmd.Help() - return - } - cmdutil.CheckErr(ValidateArgs(cmd, args)) - cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) - cmdutil.CheckErr(RunCreate(f, cmd, out, options)) - }, - } - - usage := "Filename, directory, or URL to file to use to create the resource" - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.MarkFlagRequired("filename") - cmdutil.AddValidateFlags(cmd) - cmdutil.AddOutputFlagsForMutation(cmd) - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddRecordFlag(cmd) - - // create subcommands - cmd.AddCommand(NewCmdCreateNamespace(f, out)) - cmd.AddCommand(NewCmdCreateSecret(f, out)) - cmd.AddCommand(NewCmdCreateConfigMap(f, out)) - return cmd -} - -func ValidateArgs(cmd *cobra.Command, args []string) error { - if len(args) != 0 { - return cmdutil.UsageError(cmd, "Unexpected args: %v", args) - } - return nil -} - -func RunCreate(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, options *CreateOptions) error { - schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) - if err != nil { - return err - } - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - Schema(schema). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - count := 0 - err = r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { - return cmdutil.AddSourceToErr("creating", info.Source, err) - } - - if cmdutil.ShouldRecord(cmd, info) { - if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil { - return cmdutil.AddSourceToErr("creating", info.Source, err) - } - } - - if err := createAndRefresh(info); err != nil { - return cmdutil.AddSourceToErr("creating", info.Source, err) - } - - count++ - shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" - if !shortOutput { - printObjectSpecificMessage(info.Object, out) - } - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "created") - return nil - }) - if err != nil { - return err - } - if count == 0 { - return fmt.Errorf("no objects passed to create") - } - return nil -} - -func printObjectSpecificMessage(obj runtime.Object, out io.Writer) { - switch obj := obj.(type) { - case *api.Service: - if obj.Spec.Type == api.ServiceTypeNodePort { - msg := fmt.Sprintf( - `You have exposed your service on an external port on all nodes in your -cluster. If you want to expose this service to the external internet, you may -need to set up firewall rules for the service port(s) (%s) to serve traffic. - -See http://releases.k8s.io/HEAD/docs/user-guide/services-firewalls.md for more details. -`, - makePortsString(obj.Spec.Ports, true)) - out.Write([]byte(msg)) - } - } -} - -func makePortsString(ports []api.ServicePort, useNodePort bool) string { - pieces := make([]string, len(ports)) - for ix := range ports { - var port int - if useNodePort { - port = ports[ix].NodePort - } else { - port = ports[ix].Port - } - pieces[ix] = fmt.Sprintf("%s:%d", strings.ToLower(string(ports[ix].Protocol)), port) - } - return strings.Join(pieces, ",") -} - -// createAndRefresh creates an object from input info and refreshes info with that object -func createAndRefresh(info *resource.Info) error { - obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, info.Object) - if err != nil { - return err - } - info.Refresh(obj, true) - return nil -} - -// NameFromCommandArgs is a utility function for commands that assume the first argument is a resource name -func NameFromCommandArgs(cmd *cobra.Command, args []string) (string, error) { - if len(args) == 0 { - return "", cmdutil.UsageError(cmd, "NAME is required") - } - return args[0], nil -} - -// CreateSubcommandOptions is an options struct to support create subcommands -type CreateSubcommandOptions struct { - // Name of resource being created - Name string - // StructuredGenerator is the resource generator for the object being created - StructuredGenerator kubectl.StructuredGenerator - // DryRun is true if the command should be simulated but not run against the server - DryRun bool - // OutputFormat - OutputFormat string -} - -// RunCreateSubcommand executes a create subcommand using the specified options -func RunCreateSubcommand(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, options *CreateSubcommandOptions) error { - namespace, _, err := f.DefaultNamespace() - if err != nil { - return err - } - obj, err := options.StructuredGenerator.StructuredGenerate() - if err != nil { - return err - } - mapper, typer := f.Object() - gvk, err := typer.ObjectKind(obj) - mapping, err := mapper.RESTMapping(unversioned.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version) - if err != nil { - return err - } - client, err := f.ClientForMapping(mapping) - if err != nil { - return err - } - resourceMapper := &resource.Mapper{ - ObjectTyper: typer, - RESTMapper: mapper, - ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), - } - info, err := resourceMapper.InfoForObject(obj) - if err != nil { - return err - } - if err := kubectl.UpdateApplyAnnotation(info, f.JSONEncoder()); err != nil { - return err - } - if !options.DryRun { - obj, err = resource.NewHelper(client, mapping).Create(namespace, false, info.Object) - if err != nil { - return err - } - } - - if useShortOutput := options.OutputFormat == "name"; useShortOutput || len(options.OutputFormat) == 0 { - cmdutil.PrintSuccess(mapper, useShortOutput, out, mapping.Resource, options.Name, "created") - return nil - } - - return f.PrintObject(cmd, obj, out) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_configmap.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_configmap.go deleted file mode 100644 index 99a7dcc2c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_configmap.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -const ( - configMapLong = `Create a configmap based on a file, directory, or specified literal value. - -A single configmap may package one or more key/value pairs. - -When creating a configmap based on a file, the key will default to the basename of the file, and the value will -default to the file content. If the basename is an invalid key, you may specify an alternate key. - -When creating a configmap based on a directory, each file whose basename is a valid key in the directory will be -packaged into the configmap. Any directory entries except regular files are ignored (e.g. subdirectories, -symlinks, devices, pipes, etc). -` - - configMapExample = ` # Create a new configmap named my-config with keys for each file in folder bar - $ kubectl create configmap generic my-config --from-file=path/to/bar - - # Create a new configmap named my-config with specified keys instead of names on disk - $ kubectl create configmap generic my-config --from-file=ssh-privatekey=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub - - # Create a new configMap named my-config with key1=config1 and key2=config2 - $ kubectl create configmap generic my-config --from-literal=key1=config1 --from-literal=key2=config2` -) - -// ConfigMap is a command to ease creating ConfigMaps. -func NewCmdCreateConfigMap(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "configmap NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]", - Short: "Create a configMap from a local file, directory or literal value.", - Long: configMapLong, - Example: configMapExample, - Run: func(cmd *cobra.Command, args []string) { - err := CreateConfigMap(f, cmdOut, cmd, args) - cmdutil.CheckErr(err) - }, - } - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddValidateFlags(cmd) - cmdutil.AddPrinterFlags(cmd) - cmdutil.AddGeneratorFlags(cmd, cmdutil.ConfigMapV1GeneratorName) - cmd.Flags().StringSlice("from-file", []string{}, "Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid configmap key.") - cmd.Flags().StringSlice("from-literal", []string{}, "Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)") - return cmd -} - -// CreateConfigMap is the implementation of the create configmap generic command. -func CreateConfigMap(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error { - name, err := NameFromCommandArgs(cmd, args) - if err != nil { - return err - } - var generator kubectl.StructuredGenerator - switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName { - case cmdutil.ConfigMapV1GeneratorName: - generator = &kubectl.ConfigMapGeneratorV1{ - Name: name, - FileSources: cmdutil.GetFlagStringSlice(cmd, "from-file"), - LiteralSources: cmdutil.GetFlagStringSlice(cmd, "from-literal"), - } - default: - return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName)) - } - return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{ - Name: name, - StructuredGenerator: generator, - DryRun: cmdutil.GetFlagBool(cmd, "dry-run"), - OutputFormat: cmdutil.GetFlagString(cmd, "output"), - }) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_configmap_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_configmap_test.go deleted file mode 100644 index 9c3971e36..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_configmap_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func TestCreateConfigMap(t *testing.T) { - configMap := &api.ConfigMap{} - configMap.Name = "my-configmap" - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/configmaps" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, configMap)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdCreateConfigMap(f, buf) - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{configMap.Name}) - expectedOutput := "configmap/" + configMap.Name + "\n" - if buf.String() != expectedOutput { - t.Errorf("expected output: %s, but got: %s", buf.String(), expectedOutput) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_namespace.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_namespace.go deleted file mode 100644 index a66055fb1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_namespace.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -const ( - namespaceLong = ` -Create a namespace with the specified name.` - - namespaceExample = ` # Create a new namespace named my-namespace - $ kubectl create namespace my-namespace` -) - -// NewCmdCreateNamespace is a macro command to create a new namespace -func NewCmdCreateNamespace(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "namespace NAME [--dry-run]", - Aliases: []string{"ns"}, - Short: "Create a namespace with the specified name.", - Long: namespaceLong, - Example: namespaceExample, - Run: func(cmd *cobra.Command, args []string) { - err := CreateNamespace(f, cmdOut, cmd, args) - cmdutil.CheckErr(err) - }, - } - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddValidateFlags(cmd) - cmdutil.AddPrinterFlags(cmd) - cmdutil.AddGeneratorFlags(cmd, cmdutil.NamespaceV1GeneratorName) - return cmd -} - -// CreateNamespace implements the behavior to run the create namespace command -func CreateNamespace(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error { - name, err := NameFromCommandArgs(cmd, args) - if err != nil { - return err - } - var generator kubectl.StructuredGenerator - switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName { - case cmdutil.NamespaceV1GeneratorName: - generator = &kubectl.NamespaceGeneratorV1{Name: name} - default: - return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName)) - } - return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{ - Name: name, - StructuredGenerator: generator, - DryRun: cmdutil.GetFlagBool(cmd, "dry-run"), - OutputFormat: cmdutil.GetFlagString(cmd, "output"), - }) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_namespace_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_namespace_test.go deleted file mode 100644 index dd74eec4b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_namespace_test.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func TestCreateNamespace(t *testing.T) { - namespaceObject := &api.Namespace{} - namespaceObject.Name = "my-namespace" - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, namespaceObject)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdCreateNamespace(f, buf) - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{namespaceObject.Name}) - expectedOutput := "namespace/" + namespaceObject.Name + "\n" - if buf.String() != expectedOutput { - t.Errorf("expected output: %s, but got: %s", buf.String(), expectedOutput) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_secret.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_secret.go deleted file mode 100644 index 6cba3ba07..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_secret.go +++ /dev/null @@ -1,192 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -// NewCmdCreateSecret groups subcommands to create various types of secrets -func NewCmdCreateSecret(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "secret", - Short: "Create a secret using specified subcommand.", - Long: "Create a secret using specified subcommand.", - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, - } - cmd.AddCommand(NewCmdCreateSecretDockerRegistry(f, cmdOut)) - cmd.AddCommand(NewCmdCreateSecretGeneric(f, cmdOut)) - return cmd -} - -const ( - secretLong = ` -Create a secret based on a file, directory, or specified literal value. - -A single secret may package one or more key/value pairs. - -When creating a secret based on a file, the key will default to the basename of the file, and the value will -default to the file content. If the basename is an invalid key, you may specify an alternate key. - -When creating a secret based on a directory, each file whose basename is a valid key in the directory will be -packaged into the secret. Any directory entries except regular files are ignored (e.g. subdirectories, -symlinks, devices, pipes, etc). -` - - secretExample = ` # Create a new secret named my-secret with keys for each file in folder bar - $ kubectl create secret generic my-secret --from-file=path/to/bar - - # Create a new secret named my-secret with specified keys instead of names on disk - $ kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub - - # Create a new secret named my-secret with key1=supersecret and key2=topsecret - $ kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret` -) - -// NewCmdCreateSecretGeneric is a command to create generic secrets from files, directories, or literal values -func NewCmdCreateSecretGeneric(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]", - Short: "Create a secret from a local file, directory or literal value.", - Long: secretLong, - Example: secretExample, - Run: func(cmd *cobra.Command, args []string) { - err := CreateSecretGeneric(f, cmdOut, cmd, args) - cmdutil.CheckErr(err) - }, - } - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddValidateFlags(cmd) - cmdutil.AddPrinterFlags(cmd) - cmdutil.AddGeneratorFlags(cmd, cmdutil.SecretV1GeneratorName) - cmd.Flags().StringSlice("from-file", []string{}, "Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key.") - cmd.Flags().StringSlice("from-literal", []string{}, "Specify a key and literal value to insert in secret (i.e. mykey=somevalue)") - cmd.Flags().String("type", "", "The type of secret to create") - return cmd -} - -// CreateSecretGeneric is the implementation of the create secret generic command -func CreateSecretGeneric(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error { - name, err := NameFromCommandArgs(cmd, args) - if err != nil { - return err - } - var generator kubectl.StructuredGenerator - switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName { - case cmdutil.SecretV1GeneratorName: - generator = &kubectl.SecretGeneratorV1{ - Name: name, - Type: cmdutil.GetFlagString(cmd, "type"), - FileSources: cmdutil.GetFlagStringSlice(cmd, "from-file"), - LiteralSources: cmdutil.GetFlagStringSlice(cmd, "from-literal"), - } - default: - return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName)) - } - return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{ - Name: name, - StructuredGenerator: generator, - DryRun: cmdutil.GetFlagBool(cmd, "dry-run"), - OutputFormat: cmdutil.GetFlagString(cmd, "output"), - }) -} - -const ( - secretForDockerRegistryLong = ` -Create a new secret for use with Docker registries. - -Dockercfg secrets are used to authenticate against Docker registries. - -When using the Docker command line to push images, you can authenticate to a given registry by running - 'docker login DOCKER_REGISTRY_SERVER --username=DOCKER_USER --password=DOCKER_PASSWORD --email=DOCKER_EMAIL'. -That produces a ~/.dockercfg file that is used by subsequent 'docker push' and 'docker pull' commands to -authenticate to the registry. - -When creating applications, you may have a Docker registry that requires authentication. In order for the -nodes to pull images on your behalf, they have to have the credentials. You can provide this information -by creating a dockercfg secret and attaching it to your service account.` - - secretForDockerRegistryExample = ` # If you don't already have a .dockercfg file, you can create a dockercfg secret directly by using: - $ kubectl create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL` -) - -// NewCmdCreateSecretDockerRegistry is a macro command for creating secrets to work with Docker registries -func NewCmdCreateSecretDockerRegistry(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-literal=key1=value1] [--dry-run]", - Short: "Create a secret for use with a Docker registry.", - Long: secretForDockerRegistryLong, - Example: secretForDockerRegistryExample, - Run: func(cmd *cobra.Command, args []string) { - err := CreateSecretDockerRegistry(f, cmdOut, cmd, args) - cmdutil.CheckErr(err) - }, - } - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddValidateFlags(cmd) - cmdutil.AddPrinterFlags(cmd) - cmdutil.AddGeneratorFlags(cmd, cmdutil.SecretForDockerRegistryV1GeneratorName) - cmd.Flags().String("docker-username", "", "Username for Docker registry authentication") - cmd.MarkFlagRequired("docker-username") - cmd.Flags().String("docker-password", "", "Password for Docker registry authentication") - cmd.MarkFlagRequired("docker-password") - cmd.Flags().String("docker-email", "", "Email for Docker registry") - cmd.MarkFlagRequired("docker-email") - cmd.Flags().String("docker-server", "https://index.docker.io/v1/", "Server location for Docker registry") - return cmd -} - -// CreateSecretDockerRegistry is the implementation of the create secret docker-registry command -func CreateSecretDockerRegistry(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error { - name, err := NameFromCommandArgs(cmd, args) - if err != nil { - return err - } - requiredFlags := []string{"docker-username", "docker-password", "docker-email", "docker-server"} - for _, requiredFlag := range requiredFlags { - if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 { - return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag) - } - } - var generator kubectl.StructuredGenerator - switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName { - case cmdutil.SecretForDockerRegistryV1GeneratorName: - generator = &kubectl.SecretForDockerRegistryGeneratorV1{ - Name: name, - Username: cmdutil.GetFlagString(cmd, "docker-username"), - Email: cmdutil.GetFlagString(cmd, "docker-email"), - Password: cmdutil.GetFlagString(cmd, "docker-password"), - Server: cmdutil.GetFlagString(cmd, "docker-server"), - } - default: - return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName)) - } - return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{ - Name: name, - StructuredGenerator: generator, - DryRun: cmdutil.GetFlagBool(cmd, "dry-run"), - OutputFormat: cmdutil.GetFlagString(cmd, "output"), - }) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_secret_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_secret_test.go deleted file mode 100644 index 8365513eb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_secret_test.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func TestCreateSecretGeneric(t *testing.T) { - secretObject := &api.Secret{} - secretObject.Name = "my-secret" - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/secrets" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, secretObject)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdCreateSecretGeneric(f, buf) - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{secretObject.Name}) - expectedOutput := "secret/" + secretObject.Name + "\n" - if buf.String() != expectedOutput { - t.Errorf("expected output: %s, but got: %s", buf.String(), expectedOutput) - } -} - -func TestCreateSecretDockerRegistry(t *testing.T) { - secretObject := &api.Secret{} - secretObject.Name = "my-secret" - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/secrets" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, secretObject)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdCreateSecretDockerRegistry(f, buf) - cmd.Flags().Set("docker-username", "test-user") - cmd.Flags().Set("docker-password", "test-pass") - cmd.Flags().Set("docker-email", "test-email") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{secretObject.Name}) - expectedOutput := "secret/" + secretObject.Name + "\n" - if buf.String() != expectedOutput { - t.Errorf("expected output: %s, but got: %s", buf.String(), expectedOutput) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_test.go deleted file mode 100644 index 9fdee69f1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/create_test.go +++ /dev/null @@ -1,232 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestExtraArgsFail(t *testing.T) { - initTestErrorHandler(t) - buf := bytes.NewBuffer([]byte{}) - - f, _, _ := NewAPIFactory() - c := NewCmdCreate(f, buf) - if ValidateArgs(c, []string{"rc"}) == nil { - t.Errorf("unexpected non-error") - } -} - -func TestCreateObject(t *testing.T) { - initTestErrorHandler(t) - _, _, rc := testData() - rc.Items[0].Name = "redis-master-controller" - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdCreate(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - // uses the name from the file, not the response - if buf.String() != "replicationcontroller/redis-master-controller\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestCreateMultipleObject(t *testing.T) { - initTestErrorHandler(t) - _, svc, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/services" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &svc.Items[0])}, nil - case p == "/namespaces/test/replicationcontrollers" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdCreate(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("filename", "../../../examples/guestbook/frontend-service.yaml") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - // Names should come from the REST response, NOT the files - if buf.String() != "replicationcontroller/rc1\nservice/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestCreateDirectory(t *testing.T) { - initTestErrorHandler(t) - _, svc, rc := testData() - rc.Items[0].Name = "name" - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/services" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &svc.Items[0])}, nil - case p == "/namespaces/test/replicationcontrollers" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdCreate(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/name\nservice/baz\nreplicationcontroller/name\nservice/baz\nreplicationcontroller/name\nservice/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestPrintObjectSpecificMessage(t *testing.T) { - initTestErrorHandler(t) - tests := []struct { - obj runtime.Object - expectOutput bool - }{ - { - obj: &api.Service{}, - expectOutput: false, - }, - { - obj: &api.Pod{}, - expectOutput: false, - }, - { - obj: &api.Service{Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer}}, - expectOutput: false, - }, - { - obj: &api.Service{Spec: api.ServiceSpec{Type: api.ServiceTypeNodePort}}, - expectOutput: true, - }, - } - for _, test := range tests { - buff := &bytes.Buffer{} - printObjectSpecificMessage(test.obj, buff) - if test.expectOutput && buff.Len() == 0 { - t.Errorf("Expected output, saw none for %v", test.obj) - } - if !test.expectOutput && buff.Len() > 0 { - t.Errorf("Expected no output, saw %s for %v", buff.String(), test.obj) - } - } -} - -func TestMakePortsString(t *testing.T) { - initTestErrorHandler(t) - tests := []struct { - ports []api.ServicePort - useNodePort bool - expectedOutput string - }{ - {ports: nil, expectedOutput: ""}, - {ports: []api.ServicePort{}, expectedOutput: ""}, - {ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - }, - }, - expectedOutput: "tcp:80", - }, - {ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - }, - { - Port: 8080, - Protocol: "UDP", - }, - { - Port: 9000, - Protocol: "TCP", - }, - }, - expectedOutput: "tcp:80,udp:8080,tcp:9000", - }, - {ports: []api.ServicePort{ - { - Port: 80, - NodePort: 9090, - Protocol: "TCP", - }, - { - Port: 8080, - NodePort: 80, - Protocol: "UDP", - }, - }, - useNodePort: true, - expectedOutput: "tcp:9090,udp:80", - }, - } - for _, test := range tests { - output := makePortsString(test.ports, test.useNodePort) - if output != test.expectedOutput { - t.Errorf("expected: %s, saw: %s.", test.expectedOutput, output) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/delete.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/delete.go deleted file mode 100644 index 7dffd4f99..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/delete.go +++ /dev/null @@ -1,210 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "time" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" -) - -// DeleteOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type DeleteOptions struct { - Filenames []string -} - -const ( - delete_long = `Delete resources by filenames, stdin, resources and names, or by resources and label selector. - -JSON and YAML formats are accepted. - -Only one type of the arguments may be specified: filenames, resources and names, or resources and label selector - -Note that the delete command does NOT do resource version checks, so if someone -submits an update to a resource right when you submit a delete, their update -will be lost along with the rest of the resource.` - delete_example = `# Delete a pod using the type and name specified in pod.json. -$ kubectl delete -f ./pod.json - -# Delete a pod based on the type and name in the JSON passed into stdin. -$ cat pod.json | kubectl delete -f - - -# Delete pods and services with same names "baz" and "foo" -$ kubectl delete pod,service baz foo - -# Delete pods and services with label name=myLabel. -$ kubectl delete pods,services -l name=myLabel - -# Delete a pod with UID 1234-56-7890-234234-456456. -$ kubectl delete pod 1234-56-7890-234234-456456 - -# Delete all pods -$ kubectl delete pods --all` -) - -func NewCmdDelete(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &DeleteOptions{} - - // retrieve a list of handled resources from printer as valid args - validArgs := []string{} - p, err := f.Printer(nil, false, false, false, false, false, false, []string{}) - cmdutil.CheckErr(err) - if p != nil { - validArgs = p.HandledResources() - } - - cmd := &cobra.Command{ - Use: "delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])", - Short: "Delete resources by filenames, stdin, resources and names, or by resources and label selector.", - Long: delete_long, - Example: delete_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) - err := RunDelete(f, out, cmd, args, options) - cmdutil.CheckErr(err) - }, - ValidArgs: validArgs, - } - usage := "Filename, directory, or URL to a file containing the resource to delete." - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on.") - cmd.Flags().Bool("all", false, "[-all] to select all the specified resources.") - cmd.Flags().Bool("ignore-not-found", false, "Treat \"resource not found\" as a successful delete. Defaults to \"true\" when --all is specified.") - cmd.Flags().Bool("cascade", true, "If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.") - cmd.Flags().Int("grace-period", -1, "Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.") - cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object") - cmdutil.AddOutputFlagsForMutation(cmd) - return cmd -} - -func RunDelete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *DeleteOptions) error { - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - deleteAll := cmdutil.GetFlagBool(cmd, "all") - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - SelectorParam(cmdutil.GetFlagString(cmd, "selector")). - SelectAllParam(deleteAll). - ResourceTypeOrNameArgs(false, args...).RequireObject(false). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - ignoreNotFound := cmdutil.GetFlagBool(cmd, "ignore-not-found") - if deleteAll { - f := cmd.Flags().Lookup("ignore-not-found") - // The flag should never be missing - if f == nil { - return fmt.Errorf("missing --ignore-not-found flag") - } - // If the user didn't explicitly set the option, default to ignoring NotFound errors when used with --all - if !f.Changed { - ignoreNotFound = true - } - } - - shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" - // By default use a reaper to delete all related resources. - if cmdutil.GetFlagBool(cmd, "cascade") { - return ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper) - } - return DeleteResult(r, out, ignoreNotFound, shortOutput, mapper) -} - -func ReapResult(r *resource.Result, f *cmdutil.Factory, out io.Writer, isDefaultDelete, ignoreNotFound bool, timeout time.Duration, gracePeriod int, shortOutput bool, mapper meta.RESTMapper) error { - found := 0 - if ignoreNotFound { - r = r.IgnoreErrors(errors.IsNotFound) - } - err := r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - found++ - reaper, err := f.Reaper(info.Mapping) - if err != nil { - // If there is no reaper for this resources and the user didn't explicitly ask for stop. - if kubectl.IsNoSuchReaperError(err) && isDefaultDelete { - return deleteResource(info, out, shortOutput, mapper) - } - return cmdutil.AddSourceToErr("reaping", info.Source, err) - } - var options *api.DeleteOptions - if gracePeriod >= 0 { - options = api.NewDeleteOptions(int64(gracePeriod)) - } - if err := reaper.Stop(info.Namespace, info.Name, timeout, options); err != nil { - return cmdutil.AddSourceToErr("stopping", info.Source, err) - } - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "deleted") - return nil - }) - if err != nil { - return err - } - if found == 0 { - fmt.Fprintf(out, "No resources found\n") - } - return nil -} - -func DeleteResult(r *resource.Result, out io.Writer, ignoreNotFound bool, shortOutput bool, mapper meta.RESTMapper) error { - found := 0 - if ignoreNotFound { - r = r.IgnoreErrors(errors.IsNotFound) - } - err := r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - found++ - return deleteResource(info, out, shortOutput, mapper) - }) - if err != nil { - return err - } - if found == 0 { - fmt.Fprintf(out, "No resources found\n") - } - return nil -} - -func deleteResource(info *resource.Info, out io.Writer, shortOutput bool, mapper meta.RESTMapper) error { - if err := resource.NewHelper(info.Client, info.Mapping).Delete(info.Namespace, info.Name); err != nil { - return cmdutil.AddSourceToErr("deleting", info.Source, err) - } - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "deleted") - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/delete_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/delete_test.go deleted file mode 100644 index 61da45f4f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/delete_test.go +++ /dev/null @@ -1,451 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func TestDeleteObjectByTuple(t *testing.T) { - _, _, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master-controller" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - default: - // Ensures no GET is performed when deleting by name - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("namespace", "test") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{"replicationcontrollers/redis-master-controller"}) - - if buf.String() != "replicationcontroller/redis-master-controller\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteNamedObject(t *testing.T) { - _, _, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master-controller" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - default: - // Ensures no GET is performed when deleting by name - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("namespace", "test") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{"replicationcontrollers", "redis-master-controller"}) - - if buf.String() != "replicationcontroller/redis-master-controller\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteObject(t *testing.T) { - _, _, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - // uses the name from the file, not the response - if buf.String() != "replicationcontroller/redis-master\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteObjectNotFound(t *testing.T) { - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE": - return &http.Response{StatusCode: 404, Body: stringBody("")}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - options := &DeleteOptions{ - Filenames: []string{"../../../examples/guestbook/redis-master-controller.yaml"}, - } - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - err := RunDelete(f, buf, cmd, []string{}, options) - if err == nil || !errors.IsNotFound(err) { - t.Errorf("unexpected error: expected NotFound, got %v", err) - } -} - -func TestDeleteObjectIgnoreNotFound(t *testing.T) { - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE": - return &http.Response{StatusCode: 404, Body: stringBody("")}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("ignore-not-found", "true") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteAllNotFound(t *testing.T) { - _, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - - // Add an item to the list which will result in a 404 on delete - svc.Items = append(svc.Items, api.Service{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - notFoundError := &errors.NewNotFound(api.Resource("services"), "foo").(*errors.StatusError).ErrStatus - - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/services" && m == "GET": - return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil - case p == "/namespaces/test/services/foo" && m == "DELETE": - return &http.Response{StatusCode: 404, Body: objBody(codec, notFoundError)}, nil - case p == "/namespaces/test/services/baz" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("all", "true") - cmd.Flags().Set("cascade", "false") - // Make sure we can explicitly choose to fail on NotFound errors, even with --all - cmd.Flags().Set("ignore-not-found", "false") - cmd.Flags().Set("output", "name") - - err := RunDelete(f, buf, cmd, []string{"services"}, &DeleteOptions{}) - if err == nil || !errors.IsNotFound(err) { - t.Errorf("unexpected error: expected NotFound, got %v", err) - } -} - -func TestDeleteAllIgnoreNotFound(t *testing.T) { - _, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - - // Add an item to the list which will result in a 404 on delete - svc.Items = append(svc.Items, api.Service{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - notFoundError := &errors.NewNotFound(api.Resource("services"), "foo").(*errors.StatusError).ErrStatus - - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/services" && m == "GET": - return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil - case p == "/namespaces/test/services/foo" && m == "DELETE": - return &http.Response{StatusCode: 404, Body: objBody(codec, notFoundError)}, nil - case p == "/namespaces/test/services/baz" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("all", "true") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{"services"}) - - if buf.String() != "service/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteMultipleObject(t *testing.T) { - _, svc, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - case p == "/namespaces/test/services/frontend" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("filename", "../../../examples/guestbook/frontend-service.yaml") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/redis-master\nservice/frontend\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteMultipleObjectContinueOnMissing(t *testing.T) { - _, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE": - return &http.Response{StatusCode: 404, Body: stringBody("")}, nil - case p == "/namespaces/test/services/frontend" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - options := &DeleteOptions{ - Filenames: []string{"../../../examples/guestbook/redis-master-controller.yaml", "../../../examples/guestbook/frontend-service.yaml"}, - } - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - err := RunDelete(f, buf, cmd, []string{}, options) - if err == nil || !errors.IsNotFound(err) { - t.Errorf("unexpected error: expected NotFound, got %v", err) - } - - if buf.String() != "service/frontend\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteMultipleResourcesWithTheSameName(t *testing.T) { - _, svc, rc := testData() - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/baz" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - case p == "/namespaces/test/replicationcontrollers/foo" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - case p == "/namespaces/test/services/baz" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - case p == "/namespaces/test/services/foo" && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - // Ensures no GET is performed when deleting by name - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("namespace", "test") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{"replicationcontrollers,services", "baz", "foo"}) - if buf.String() != "replicationcontroller/baz\nreplicationcontroller/foo\nservice/baz\nservice/foo\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteDirectory(t *testing.T) { - _, svc, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case strings.HasPrefix(p, "/namespaces/test/services/") && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers/") && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/frontend\nservice/frontend\nreplicationcontroller/redis-master\nservice/redis-master\nreplicationcontroller/redis-slave\nservice/redis-slave\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDeleteMultipleSelector(t *testing.T) { - pods, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/pods" && m == "GET": - if req.URL.Query().Get(unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String())) != "a=b" { - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - } - return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil - case p == "/namespaces/test/services" && m == "GET": - if req.URL.Query().Get(unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String())) != "a=b" { - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - } - return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil - case strings.HasPrefix(p, "/namespaces/test/pods/") && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - case strings.HasPrefix(p, "/namespaces/test/services/") && m == "DELETE": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDelete(f, buf) - cmd.Flags().Set("selector", "a=b") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{"pods,services"}) - - if buf.String() != "pod/foo\npod/bar\nservice/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/describe.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/describe.go deleted file mode 100644 index 3ea83ecdc..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/describe.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "strings" - - "github.com/spf13/cobra" - - apierrors "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - utilerrors "k8s.io/kubernetes/pkg/util/errors" -) - -// DescribeOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type DescribeOptions struct { - Filenames []string -} - -const ( - describe_long = `Show details of a specific resource or group of resources. - -This command joins many API calls together to form a detailed description of a -given resource or group of resources. - -$ kubectl describe TYPE NAME_PREFIX - -will first check for an exact match on TYPE and NAME_PREFIX. If no such resource -exists, it will output details for every resource that has a name prefixed with NAME_PREFIX - -Possible resource types include (case insensitive): pods (po), services (svc), -replicationcontrollers (rc), nodes (no), events (ev), limitranges (limits), -persistentvolumes (pv), persistentvolumeclaims (pvc), resourcequotas (quota), -namespaces (ns), serviceaccounts, horizontalpodautoscalers (hpa), -endpoints (ep) or secrets.` - describe_example = `# Describe a node -$ kubectl describe nodes kubernetes-minion-emt8.c.myproject.internal - -# Describe a pod -$ kubectl describe pods/nginx - -# Describe a pod identified by type and name in "pod.json" -$ kubectl describe -f pod.json - -# Describe all pods -$ kubectl describe pods - -# Describe pods by label name=myLabel -$ kubectl describe po -l name=myLabel - -# Describe all pods managed by the 'frontend' replication controller (rc-created pods -# get the name of the rc as a prefix in the pod the name). -$ kubectl describe pods frontend` -) - -func NewCmdDescribe(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &DescribeOptions{} - - cmd := &cobra.Command{ - Use: "describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)", - Short: "Show details of a specific resource or group of resources", - Long: describe_long, - Example: describe_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunDescribe(f, out, cmd, args, options) - cmdutil.CheckErr(err) - }, - ValidArgs: kubectl.DescribableResources(), - } - usage := "Filename, directory, or URL to a file containing the resource to describe" - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on") - return cmd -} - -func RunDescribe(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *DescribeOptions) error { - selector := cmdutil.GetFlagString(cmd, "selector") - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - if len(args) == 0 && len(options.Filenames) == 0 { - fmt.Fprint(out, "You must specify the type of resource to describe. ", valid_resources) - return cmdutil.UsageError(cmd, "Required resource not specified.") - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - SelectorParam(selector). - ResourceTypeOrNameArgs(true, args...). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - allErrs := []error{} - infos, err := r.Infos() - if err != nil { - if apierrors.IsNotFound(err) && len(args) == 2 { - return DescribeMatchingResources(mapper, typer, f, cmdNamespace, args[0], args[1], out, err) - } - allErrs = append(allErrs, err) - } - - for _, info := range infos { - mapping := info.ResourceMapping() - describer, err := f.Describer(mapping) - if err != nil { - allErrs = append(allErrs, err) - continue - } - s, err := describer.Describe(info.Namespace, info.Name) - if err != nil { - allErrs = append(allErrs, err) - continue - } - fmt.Fprintf(out, "%s\n\n", s) - } - - return utilerrors.NewAggregate(allErrs) -} - -func DescribeMatchingResources(mapper meta.RESTMapper, typer runtime.ObjectTyper, f *cmdutil.Factory, namespace, rsrc, prefix string, out io.Writer, originalError error) error { - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(namespace).DefaultNamespace(). - ResourceTypeOrNameArgs(true, rsrc). - SingleResourceType(). - Flatten(). - Do() - mapping, err := r.ResourceMapping() - if err != nil { - return err - } - describer, err := f.Describer(mapping) - if err != nil { - return err - } - infos, err := r.Infos() - if err != nil { - return err - } - isFound := false - for ix := range infos { - info := infos[ix] - if strings.HasPrefix(info.Name, prefix) { - isFound = true - s, err := describer.Describe(info.Namespace, info.Name) - if err != nil { - return err - } - fmt.Fprintf(out, "%s\n", s) - } - } - if !isFound { - return originalError - } - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/describe_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/describe_test.go deleted file mode 100644 index 35a87f2e5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/describe_test.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "fmt" - "net/http" - "testing" - - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -// Verifies that schemas that are not in the master tree of Kubernetes can be retrieved via Get. -func TestDescribeUnknownSchemaObject(t *testing.T) { - d := &testDescriber{Output: "test output"} - f, tf, codec := NewTestFactory() - tf.Describer = d - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, &internalType{Name: "foo"})}, - } - tf.Namespace = "non-default" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDescribe(f, buf) - cmd.Run(cmd, []string{"type", "foo"}) - - if d.Name != "foo" || d.Namespace != "non-default" { - t.Errorf("unexpected describer: %#v", d) - } - - if buf.String() != fmt.Sprintf("%s\n\n", d.Output) { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDescribeObject(t *testing.T) { - _, _, rc := testData() - f, tf, codec := NewAPIFactory() - d := &testDescriber{Output: "test output"} - tf.Describer = d - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "GET": - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdDescribe(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Run(cmd, []string{}) - - if d.Name != "redis-master" || d.Namespace != "test" { - t.Errorf("unexpected describer: %#v", d) - } - - if buf.String() != fmt.Sprintf("%s\n\n", d.Output) { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestDescribeListObjects(t *testing.T) { - pods, _, _ := testData() - f, tf, codec := NewAPIFactory() - d := &testDescriber{Output: "test output"} - tf.Describer = d - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, - } - - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdDescribe(f, buf) - cmd.Run(cmd, []string{"pods"}) - if buf.String() != fmt.Sprintf("%s\n\n%s\n\n", d.Output, d.Output) { - t.Errorf("unexpected output: %s", buf.String()) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/drain.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/drain.go deleted file mode 100644 index 89cba686d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/drain.go +++ /dev/null @@ -1,373 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "errors" - "fmt" - "io" - "reflect" - "strings" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/controller" - // "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/fields" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/kubelet/types" - "k8s.io/kubernetes/pkg/runtime" -) - -type DrainOptions struct { - client *client.Client - factory *cmdutil.Factory - Force bool - GracePeriodSeconds int - IgnoreDaemonsets bool - mapper meta.RESTMapper - nodeInfo *resource.Info - out io.Writer - typer runtime.ObjectTyper -} - -const ( - cordon_long = `Mark node as unschedulable. -` - cordon_example = `# Mark node "foo" as unschedulable. -$ kubectl cordon foo -` -) - -func NewCmdCordon(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &DrainOptions{factory: f, out: out} - - return &cobra.Command{ - Use: "cordon NODE", - Short: "Mark node as unschedulable", - Long: cordon_long, - Example: cordon_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(options.SetupDrain(cmd, args)) - cmdutil.CheckErr(options.RunCordonOrUncordon(true)) - }, - } -} - -const ( - uncordon_long = `Mark node as schedulable. -` - uncordon_example = `# Mark node "foo" as schedulable. -$ kubectl uncordon foo -` -) - -func NewCmdUncordon(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &DrainOptions{factory: f, out: out} - - return &cobra.Command{ - Use: "uncordon NODE", - Short: "Mark node as schedulable", - Long: uncordon_long, - Example: uncordon_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(options.SetupDrain(cmd, args)) - cmdutil.CheckErr(options.RunCordonOrUncordon(false)) - }, - } -} - -const ( - drain_long = `Drain node in preparation for maintenance. - -The given node will be marked unschedulable to prevent new pods from arriving. -Then drain deletes all pods except mirror pods (which cannot be deleted through -the API server). If there are DaemonSet-managed pods, drain will not proceed -without --ignore-daemonsets, and regardless it will not delete any -DaemonSet-managed pods, because those pods would be immediately replaced by the -DaemonSet controller, which ignores unschedulable marknigs. If there are any -pods that are neither mirror pods nor managed--by ReplicationController, -DaemonSet or Job--, then drain will not delete any pods unless you use --force. - -When you are ready to put the node back into service, use kubectl uncordon, which -will make the node schedulable again. -` - drain_example = `# Drain node "foo", even if there are pods not managed by a ReplicationController, Job, or DaemonSet on it. -$ kubectl drain foo --force - -# As above, but abort if there are pods not managed by a ReplicationController, Job, or DaemonSet, and use a grace period of 15 minutes. -$ kubectl drain foo --grace-period=900 -` -) - -func NewCmdDrain(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &DrainOptions{factory: f, out: out} - - cmd := &cobra.Command{ - Use: "drain NODE", - Short: "Drain node in preparation for maintenance", - Long: drain_long, - Example: drain_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(options.SetupDrain(cmd, args)) - cmdutil.CheckErr(options.RunDrain()) - }, - } - cmd.Flags().BoolVar(&options.Force, "force", false, "Continue even if there are pods not managed by a ReplicationController, Job, or DaemonSet.") - cmd.Flags().BoolVar(&options.IgnoreDaemonsets, "ignore-daemonsets", false, "Ignore DaemonSet-managed pods.") - cmd.Flags().IntVar(&options.GracePeriodSeconds, "grace-period", -1, "Period of time in seconds given to each pod to terminate gracefully. If negative, the default value specified in the pod will be used.") - return cmd -} - -// SetupDrain populates some fields from the factory, grabs command line -// arguments and looks up the node using Builder -func (o *DrainOptions) SetupDrain(cmd *cobra.Command, args []string) error { - var err error - if len(args) != 1 { - return cmdutil.UsageError(cmd, fmt.Sprintf("USAGE: %s [flags]", cmd.Use)) - } - - if o.client, err = o.factory.Client(); err != nil { - return err - } - - o.mapper, o.typer = o.factory.Object() - - cmdNamespace, _, err := o.factory.DefaultNamespace() - if err != nil { - return err - } - - r := o.factory.NewBuilder(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - ResourceNames("node", args[0]). - Do() - - if err = r.Err(); err != nil { - return err - } - - return r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - o.nodeInfo = info - return nil - }) -} - -// RunDrain runs the 'drain' command -func (o *DrainOptions) RunDrain() error { - if err := o.RunCordonOrUncordon(true); err != nil { - return err - } - - pods, err := o.getPodsForDeletion() - if err != nil { - return err - } - - if err = o.deletePods(pods); err != nil { - return err - } - cmdutil.PrintSuccess(o.mapper, false, o.out, "node", o.nodeInfo.Name, "drained") - return nil -} - -// getPodsForDeletion returns all the pods we're going to delete. If there are -// any unmanaged pods and the user didn't pass --force, we return that list in -// an error. -func (o *DrainOptions) getPodsForDeletion() ([]api.Pod, error) { - pods := []api.Pod{} - podList, err := o.client.Pods(api.NamespaceAll).List(api.ListOptions{FieldSelector: fields.SelectorFromSet(fields.Set{"spec.nodeName": o.nodeInfo.Name})}) - if err != nil { - return pods, err - } - unreplicatedPodNames := []string{} - daemonSetPodNames := []string{} - - for _, pod := range podList.Items { - _, found := pod.ObjectMeta.Annotations[types.ConfigMirrorAnnotationKey] - if found { - // Skip mirror pod - continue - } - replicated := false - daemonset_pod := false - - creatorRef, found := pod.ObjectMeta.Annotations[controller.CreatedByAnnotation] - if found { - // Now verify that the specified creator actually exists. - var sr api.SerializedReference - if err := runtime.DecodeInto(o.factory.Decoder(true), []byte(creatorRef), &sr); err != nil { - return pods, err - } - if sr.Reference.Kind == "ReplicationController" { - rc, err := o.client.ReplicationControllers(sr.Reference.Namespace).Get(sr.Reference.Name) - // Assume the only reason for an error is because the RC is - // gone/missing, not for any other cause. TODO(mml): something more - // sophisticated than this - if err == nil && rc != nil { - replicated = true - } - } else if sr.Reference.Kind == "DaemonSet" { - ds, err := o.client.DaemonSets(sr.Reference.Namespace).Get(sr.Reference.Name) - - // Assume the only reason for an error is because the DaemonSet is - // gone/missing, not for any other cause. TODO(mml): something more - // sophisticated than this - if err == nil && ds != nil { - // Otherwise, treat daemonset-managed pods as unmanaged since - // DaemonSet Controller currently ignores the unschedulable bit. - // FIXME(mml): Add link to the issue concerning a proper way to drain - // daemonset pods, probably using taints. - daemonset_pod = true - } - } else if sr.Reference.Kind == "Job" { - job, err := o.client.Jobs(sr.Reference.Namespace).Get(sr.Reference.Name) - - // Assume the only reason for an error is because the Job is - // gone/missing, not for any other cause. TODO(mml): something more - // sophisticated than this - if err == nil && job != nil { - replicated = true - } - } - } - - switch { - case daemonset_pod: - daemonSetPodNames = append(daemonSetPodNames, pod.Name) - case !replicated: - unreplicatedPodNames = append(unreplicatedPodNames, pod.Name) - if o.Force { - pods = append(pods, pod) - } - default: - pods = append(pods, pod) - } - } - - daemonSetErrors := !o.IgnoreDaemonsets && len(daemonSetPodNames) > 0 - unreplicatedErrors := !o.Force && len(unreplicatedPodNames) > 0 - - switch { - case daemonSetErrors && unreplicatedErrors: - return []api.Pod{}, errors.New(unmanagedMsg(unreplicatedPodNames, daemonSetPodNames, true)) - case daemonSetErrors && !unreplicatedErrors: - return []api.Pod{}, errors.New(unmanagedMsg([]string{}, daemonSetPodNames, true)) - case unreplicatedErrors && !daemonSetErrors: - return []api.Pod{}, errors.New(unmanagedMsg(unreplicatedPodNames, []string{}, true)) - } - - if len(unreplicatedPodNames) > 0 { - fmt.Fprintf(o.out, "WARNING: About to delete these %s\n", unmanagedMsg(unreplicatedPodNames, []string{}, false)) - } - if len(daemonSetPodNames) > 0 { - fmt.Fprintf(o.out, "WARNING: Skipping %s\n", unmanagedMsg([]string{}, daemonSetPodNames, false)) - } - - return pods, nil -} - -// Helper for generating errors or warnings about unmanaged pods. -func unmanagedMsg(unreplicatedNames []string, daemonSetNames []string, include_guidance bool) string { - msgs := []string{} - if len(unreplicatedNames) > 0 { - msg := fmt.Sprintf("pods not managed by ReplicationController, Job, or DaemonSet: %s", strings.Join(unreplicatedNames, ",")) - if include_guidance { - msg += " (use --force to override)" - } - msgs = append(msgs, msg) - } - if len(daemonSetNames) > 0 { - msg := fmt.Sprintf("DaemonSet-managed pods: %s", strings.Join(daemonSetNames, ",")) - if include_guidance { - msg += " (use --ignore-daemonsets to ignore)" - } - msgs = append(msgs, msg) - } - - return strings.Join(msgs, " and ") -} - -// deletePods deletes the pods on the api server -func (o *DrainOptions) deletePods(pods []api.Pod) error { - deleteOptions := api.DeleteOptions{} - if o.GracePeriodSeconds >= 0 { - gracePeriodSeconds := int64(o.GracePeriodSeconds) - deleteOptions.GracePeriodSeconds = &gracePeriodSeconds - } - - for _, pod := range pods { - err := o.client.Pods(pod.Namespace).Delete(pod.Name, &deleteOptions) - if err != nil { - return err - } - cmdutil.PrintSuccess(o.mapper, false, o.out, "pod", pod.Name, "deleted") - } - - return nil -} - -// RunCordonOrUncordon runs either Cordon or Uncordon. The desired value for -// "Unschedulable" is passed as the first arg. -func (o *DrainOptions) RunCordonOrUncordon(desired bool) error { - cmdNamespace, _, err := o.factory.DefaultNamespace() - if err != nil { - return err - } - - if o.nodeInfo.Mapping.GroupVersionKind.Kind == "Node" { - unsched := reflect.ValueOf(o.nodeInfo.Object).Elem().FieldByName("Spec").FieldByName("Unschedulable") - if unsched.Bool() == desired { - cmdutil.PrintSuccess(o.mapper, false, o.out, o.nodeInfo.Mapping.Resource, o.nodeInfo.Name, already(desired)) - } else { - helper := resource.NewHelper(o.client, o.nodeInfo.Mapping) - unsched.SetBool(desired) - _, err := helper.Replace(cmdNamespace, o.nodeInfo.Name, true, o.nodeInfo.Object) - if err != nil { - return err - } - cmdutil.PrintSuccess(o.mapper, false, o.out, o.nodeInfo.Mapping.Resource, o.nodeInfo.Name, changed(desired)) - } - } else { - cmdutil.PrintSuccess(o.mapper, false, o.out, o.nodeInfo.Mapping.Resource, o.nodeInfo.Name, "skipped") - } - - return nil -} - -// already() and changed() return suitable strings for {un,}cordoning - -func already(desired bool) string { - if desired { - return "already cordoned" - } - return "already uncordoned" -} - -func changed(desired bool) string { - if desired { - return "cordoned" - } - return "uncordoned" -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/drain_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/drain_test.go deleted file mode 100644 index b0aa36649..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/drain_test.go +++ /dev/null @@ -1,494 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "reflect" - "strings" - "testing" - "time" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/controller" - "k8s.io/kubernetes/pkg/conversion" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/runtime" -) - -var node *api.Node -var cordoned_node *api.Node - -func TestMain(m *testing.M) { - // Create a node. - node = &api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "node", - CreationTimestamp: unversioned.Time{time.Now()}, - }, - Spec: api.NodeSpec{ - ExternalID: "node", - }, - Status: api.NodeStatus{}, - } - clone, _ := conversion.NewCloner().DeepCopy(node) - - // A copy of the same node, but cordoned. - cordoned_node = clone.(*api.Node) - cordoned_node.Spec.Unschedulable = true - os.Exit(m.Run()) -} - -func TestCordon(t *testing.T) { - tests := []struct { - description string - node *api.Node - expected *api.Node - cmd func(*cmdutil.Factory, io.Writer) *cobra.Command - arg string - expectFatal bool - }{ - { - description: "node/node syntax", - node: cordoned_node, - expected: node, - cmd: NewCmdUncordon, - arg: "node/node", - expectFatal: false, - }, - { - description: "uncordon for real", - node: cordoned_node, - expected: node, - cmd: NewCmdUncordon, - arg: "node", - expectFatal: false, - }, - { - description: "uncordon does nothing", - node: node, - expected: node, - cmd: NewCmdUncordon, - arg: "node", - expectFatal: false, - }, - { - description: "cordon does nothing", - node: cordoned_node, - expected: cordoned_node, - cmd: NewCmdCordon, - arg: "node", - expectFatal: false, - }, - { - description: "cordon for real", - node: node, - expected: cordoned_node, - cmd: NewCmdCordon, - arg: "node", - expectFatal: false, - }, - { - description: "cordon missing node", - node: node, - expected: node, - cmd: NewCmdCordon, - arg: "bar", - expectFatal: true, - }, - { - description: "uncordon missing node", - node: node, - expected: node, - cmd: NewCmdUncordon, - arg: "bar", - expectFatal: true, - }, - } - - for _, test := range tests { - f, tf, codec := NewAPIFactory() - new_node := &api.Node{} - updated := false - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - m := &MyReq{req} - switch { - case m.isFor("GET", "/nodes/node"): - return &http.Response{StatusCode: 200, Body: objBody(codec, test.node)}, nil - case m.isFor("GET", "/nodes/bar"): - return &http.Response{StatusCode: 404, Body: stringBody("nope")}, nil - case m.isFor("PUT", "/nodes/node"): - data, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatalf("%s: unexpected error: %v", test.description, err) - } - defer req.Body.Close() - if err := runtime.DecodeInto(codec, data, new_node); err != nil { - t.Fatalf("%s: unexpected error: %v", test.description, err) - } - if !reflect.DeepEqual(test.expected.Spec, new_node.Spec) { - t.Fatalf("%s: expected:\n%v\nsaw:\n%v\n", test.description, test.expected.Spec, new_node.Spec) - } - updated = true - return &http.Response{StatusCode: 200, Body: objBody(codec, new_node)}, nil - default: - t.Fatalf("%s: unexpected request: %v %#v\n%#v", test.description, req.Method, req.URL, req) - return nil, nil - } - }), - } - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := test.cmd(f, buf) - - saw_fatal := false - func() { - defer func() { - // Recover from the panic below. - _ = recover() - // Restore cmdutil behavior - cmdutil.DefaultBehaviorOnFatal() - }() - cmdutil.BehaviorOnFatal(func(e string) { saw_fatal = true; panic(e) }) - cmd.SetArgs([]string{test.arg}) - cmd.Execute() - }() - - if test.expectFatal { - if !saw_fatal { - t.Fatalf("%s: unexpected non-error", test.description) - } - if updated { - t.Fatalf("%s: unexpcted update", test.description) - } - } - - if !test.expectFatal && saw_fatal { - t.Fatalf("%s: unexpected error", test.description) - } - if !reflect.DeepEqual(test.expected.Spec, test.node.Spec) && !updated { - t.Fatalf("%s: node never updated", test.description) - } - } -} - -func TestDrain(t *testing.T) { - labels := make(map[string]string) - labels["my_key"] = "my_value" - - rc := api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "rc", - Namespace: "default", - CreationTimestamp: unversioned.Time{time.Now()}, - Labels: labels, - SelfLink: testapi.Default.SelfLink("replicationcontrollers", "rc"), - }, - Spec: api.ReplicationControllerSpec{ - Selector: labels, - }, - } - - rc_anno := make(map[string]string) - rc_anno[controller.CreatedByAnnotation] = refJson(t, &rc) - - replicated_pod := api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Namespace: "default", - CreationTimestamp: unversioned.Time{time.Now()}, - Labels: labels, - Annotations: rc_anno, - }, - Spec: api.PodSpec{ - NodeName: "node", - }, - } - - ds := extensions.DaemonSet{ - ObjectMeta: api.ObjectMeta{ - Name: "ds", - Namespace: "default", - CreationTimestamp: unversioned.Time{time.Now()}, - SelfLink: "/apis/extensions/v1beta1/namespaces/default/daemonsets/ds", - }, - Spec: extensions.DaemonSetSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: labels}, - }, - } - - ds_anno := make(map[string]string) - ds_anno[controller.CreatedByAnnotation] = refJson(t, &ds) - - ds_pod := api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Namespace: "default", - CreationTimestamp: unversioned.Time{time.Now()}, - Labels: labels, - Annotations: ds_anno, - }, - Spec: api.PodSpec{ - NodeName: "node", - }, - } - - job := extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "job", - Namespace: "default", - CreationTimestamp: unversioned.Time{time.Now()}, - SelfLink: "/apis/extensions/v1beta1/namespaces/default/jobs/job", - }, - Spec: extensions.JobSpec{ - Selector: &unversioned.LabelSelector{MatchLabels: labels}, - }, - } - - job_pod := api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Namespace: "default", - CreationTimestamp: unversioned.Time{time.Now()}, - Labels: labels, - Annotations: map[string]string{controller.CreatedByAnnotation: refJson(t, &job)}, - }, - } - - naked_pod := api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Namespace: "default", - CreationTimestamp: unversioned.Time{time.Now()}, - Labels: labels, - }, - Spec: api.PodSpec{ - NodeName: "node", - }, - } - - tests := []struct { - description string - node *api.Node - expected *api.Node - pods []api.Pod - rcs []api.ReplicationController - args []string - expectFatal bool - expectDelete bool - }{ - { - description: "RC-managed pod", - node: node, - expected: cordoned_node, - pods: []api.Pod{replicated_pod}, - rcs: []api.ReplicationController{rc}, - args: []string{"node"}, - expectFatal: false, - expectDelete: true, - }, - { - description: "DS-managed pod", - node: node, - expected: cordoned_node, - pods: []api.Pod{ds_pod}, - rcs: []api.ReplicationController{rc}, - args: []string{"node"}, - expectFatal: true, - expectDelete: false, - }, - { - description: "DS-managed pod with --ignore-daemonsets", - node: node, - expected: cordoned_node, - pods: []api.Pod{ds_pod}, - rcs: []api.ReplicationController{rc}, - args: []string{"node", "--ignore-daemonsets"}, - expectFatal: false, - expectDelete: false, - }, - { - description: "Job-managed pod", - node: node, - expected: cordoned_node, - pods: []api.Pod{job_pod}, - rcs: []api.ReplicationController{rc}, - args: []string{"node"}, - expectFatal: false, - expectDelete: true, - }, - { - description: "naked pod", - node: node, - expected: cordoned_node, - pods: []api.Pod{naked_pod}, - rcs: []api.ReplicationController{}, - args: []string{"node"}, - expectFatal: true, - expectDelete: false, - }, - { - description: "naked pod with --force", - node: node, - expected: cordoned_node, - pods: []api.Pod{naked_pod}, - rcs: []api.ReplicationController{}, - args: []string{"node", "--force"}, - expectFatal: false, - expectDelete: true, - }, - { - description: "empty node", - node: node, - expected: cordoned_node, - pods: []api.Pod{}, - rcs: []api.ReplicationController{rc}, - args: []string{"node"}, - expectFatal: false, - expectDelete: false, - }, - } - - for _, test := range tests { - new_node := &api.Node{} - deleted := false - f, tf, codec := NewAPIFactory() - - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - m := &MyReq{req} - switch { - case m.isFor("GET", "/nodes/node"): - return &http.Response{StatusCode: 200, Body: objBody(codec, test.node)}, nil - case m.isFor("GET", "/namespaces/default/replicationcontrollers/rc"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &test.rcs[0])}, nil - case m.isFor("GET", "/namespaces/default/daemonsets/ds"): - return &http.Response{StatusCode: 200, Body: objBody(testapi.Extensions.Codec(), &ds)}, nil - case m.isFor("GET", "/namespaces/default/jobs/job"): - return &http.Response{StatusCode: 200, Body: objBody(testapi.Extensions.Codec(), &job)}, nil - case m.isFor("GET", "/pods"): - values, err := url.ParseQuery(req.URL.RawQuery) - if err != nil { - t.Fatalf("%s: unexpected error: %v", test.description, err) - } - get_params := make(url.Values) - get_params["fieldSelector"] = []string{"spec.nodeName=node"} - if !reflect.DeepEqual(get_params, values) { - t.Fatalf("%s: expected:\n%v\nsaw:\n%v\n", test.description, get_params, values) - } - return &http.Response{StatusCode: 200, Body: objBody(codec, &api.PodList{Items: test.pods})}, nil - case m.isFor("GET", "/replicationcontrollers"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &api.ReplicationControllerList{Items: test.rcs})}, nil - case m.isFor("PUT", "/nodes/node"): - data, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatalf("%s: unexpected error: %v", test.description, err) - } - defer req.Body.Close() - if err := runtime.DecodeInto(codec, data, new_node); err != nil { - t.Fatalf("%s: unexpected error: %v", test.description, err) - } - if !reflect.DeepEqual(test.expected.Spec, new_node.Spec) { - t.Fatalf("%s: expected:\n%v\nsaw:\n%v\n", test.description, test.expected.Spec, new_node.Spec) - } - return &http.Response{StatusCode: 200, Body: objBody(codec, new_node)}, nil - case m.isFor("DELETE", "/namespaces/default/pods/bar"): - deleted = true - return &http.Response{StatusCode: 204, Body: objBody(codec, &test.pods[0])}, nil - default: - t.Fatalf("%s: unexpected request: %v %#v\n%#v", test.description, req.Method, req.URL, req) - return nil, nil - } - }), - } - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdDrain(f, buf) - - saw_fatal := false - func() { - defer func() { - // Recover from the panic below. - _ = recover() - // Restore cmdutil behavior - cmdutil.DefaultBehaviorOnFatal() - }() - cmdutil.BehaviorOnFatal(func(e string) { saw_fatal = true; panic(e) }) - cmd.SetArgs(test.args) - cmd.Execute() - }() - - if test.expectFatal { - if !saw_fatal { - t.Fatalf("%s: unexpected non-error", test.description) - } - } - - if test.expectDelete { - if !deleted { - t.Fatalf("%s: pod never deleted", test.description) - } - } - if !test.expectDelete { - if deleted { - t.Fatalf("%s: unexpected delete", test.description) - } - } - } -} - -type MyReq struct { - Request *http.Request -} - -func (m *MyReq) isFor(method string, path string) bool { - req := m.Request - - return method == req.Method && (req.URL.Path == path || req.URL.Path == strings.Join([]string{"/api/v1", path}, "") || req.URL.Path == strings.Join([]string{"/apis/extensions/v1beta1", path}, "")) -} - -func refJson(t *testing.T, o runtime.Object) string { - ref, err := api.GetReference(o) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - _, _, codec := NewAPIFactory() - json, err := runtime.Encode(codec, &api.SerializedReference{Reference: *ref}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - return string(json) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/edit.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/edit.go deleted file mode 100644 index 279cd9eca..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/edit.go +++ /dev/null @@ -1,465 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "bufio" - "bytes" - "fmt" - "io" - "os" - gruntime "runtime" - "strings" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/cmd/util/editor" - "k8s.io/kubernetes/pkg/kubectl/cmd/util/jsonmerge" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/strategicpatch" - "k8s.io/kubernetes/pkg/util/yaml" - - "github.com/golang/glog" - "github.com/spf13/cobra" -) - -const ( - editLong = `Edit a resource from the default editor. - -The edit command allows you to directly edit any API resource you can retrieve via the -command line tools. It will open the editor defined by your KUBE_EDITOR, or EDITOR -environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows. -You can edit multiple objects, although changes are applied one at a time. The command -accepts filenames as well as command line arguments, although the files you point to must -be previously saved versions of resources. - -The files to edit will be output in the default API version, or a version specified -by --output-version. The default format is YAML - if you would like to edit in JSON -pass -o json. The flag --windows-line-endings can be used to force Windows line endings, -otherwise the default for your operating system will be used. - -In the event an error occurs while updating, a temporary file will be created on disk -that contains your unapplied changes. The most common error when updating a resource -is another editor changing the resource on the server. When this occurs, you will have -to apply your changes to the newer version of the resource, or update your temporary -saved copy to include the latest resource version.` - - editExample = ` # Edit the service named 'docker-registry': - $ kubectl edit svc/docker-registry - - # Use an alternative editor - $ KUBE_EDITOR="nano" kubectl edit svc/docker-registry - - # Edit the service 'docker-registry' in JSON using the v1 API format: - $ kubectl edit svc/docker-registry --output-version=v1 -o json` -) - -var errExit = fmt.Errorf("exit directly") - -func NewCmdEdit(f *cmdutil.Factory, out io.Writer) *cobra.Command { - filenames := []string{} - cmd := &cobra.Command{ - Use: "edit (RESOURCE/NAME | -f FILENAME)", - Short: "Edit a resource on the server", - Long: editLong, - Example: fmt.Sprintf(editExample), - Run: func(cmd *cobra.Command, args []string) { - err := RunEdit(f, out, cmd, args, filenames) - if err == errExit { - os.Exit(1) - } - cmdutil.CheckErr(err) - }, - } - usage := "Filename, directory, or URL to file to use to edit the resource" - kubectl.AddJsonFilenameFlag(cmd, &filenames, usage) - cmd.Flags().StringP("output", "o", "yaml", "Output format. One of: yaml|json.") - cmd.Flags().String("output-version", "", "Output the formatted object with the given version (default api-version).") - cmd.Flags().Bool("windows-line-endings", gruntime.GOOS == "windows", "Use Windows line-endings (default Unix line-endings)") - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddRecordFlag(cmd) - return cmd -} - -func RunEdit(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames []string) error { - var printer kubectl.ResourcePrinter - var ext string - switch format := cmdutil.GetFlagString(cmd, "output"); format { - case "json": - printer = &kubectl.JSONPrinter{} - ext = ".json" - case "yaml": - printer = &kubectl.YAMLPrinter{} - ext = ".yaml" - default: - return cmdutil.UsageError(cmd, "The flag 'output' must be one of yaml|json") - } - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - mapper, typer := f.Object() - resourceMapper := &resource.Mapper{ - ObjectTyper: typer, - RESTMapper: mapper, - ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), - Decoder: f.Decoder(true), - } - - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, filenames...). - ResourceTypeOrNameArgs(true, args...). - Latest(). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - infos, err := r.Infos() - if err != nil { - return err - } - - clientConfig, err := f.ClientConfig() - if err != nil { - return err - } - - encoder := f.JSONEncoder() - defaultVersion, err := cmdutil.OutputVersion(cmd, clientConfig.GroupVersion) - if err != nil { - return err - } - objs, err := resource.AsVersionedObjects(infos, defaultVersion.String(), encoder) - if err != nil { - return err - } - - var ( - windowsLineEndings = cmdutil.GetFlagBool(cmd, "windows-line-endings") - edit = editor.NewDefaultEditor(f.EditorEnvs()) - results = editResults{} - original = []byte{} - edited = []byte{} - file string - ) - -outter: - for i := range objs { - obj := objs[i] - // some bookkeeping - results.header.flush() - containsError := false - - for { - // generate the file to edit - buf := &bytes.Buffer{} - var w io.Writer = buf - if windowsLineEndings { - w = util.NewCRLFWriter(w) - } - if err := results.header.writeTo(w); err != nil { - return preservedFile(err, results.file, out) - } - if !containsError { - if err := printer.PrintObj(obj, w); err != nil { - return preservedFile(err, results.file, out) - } - original = buf.Bytes() - } else { - // In case of an error, preserve the edited file. - // Remove the comments (header) from it since we already - // have included the latest header in the buffer above. - buf.Write(manualStrip(edited)) - } - - // launch the editor - editedDiff := edited - edited, file, err = edit.LaunchTempFile(fmt.Sprintf("%s-edit-", os.Args[0]), ext, buf) - if err != nil { - return preservedFile(err, results.file, out) - } - if bytes.Equal(stripComments(editedDiff), stripComments(edited)) { - // Ugly hack right here. We will hit this either (1) when we try to - // save the same changes we tried to save in the previous iteration - // which means our changes are invalid or (2) when we exit the second - // time. The second case is more usual so we can probably live with it. - // TODO: A less hacky fix would be welcome :) - fmt.Fprintln(out, "Edit cancelled, no valid changes were saved.") - continue outter - } - - // cleanup any file from the previous pass - if len(results.file) > 0 { - os.Remove(results.file) - } - glog.V(4).Infof("User edited:\n%s", string(edited)) - - // Compare content without comments - if bytes.Equal(stripComments(original), stripComments(edited)) { - os.Remove(file) - fmt.Fprintln(out, "Edit cancelled, no changes made.") - continue outter - } - lines, err := hasLines(bytes.NewBuffer(edited)) - if err != nil { - return preservedFile(err, file, out) - } - if !lines { - os.Remove(file) - fmt.Fprintln(out, "Edit cancelled, saved file was empty.") - continue outter - } - - results = editResults{ - file: file, - } - - // parse the edited file - updates, err := resourceMapper.InfoForData(edited, "edited-file") - if err != nil { - // syntax error - containsError = true - results.header.reasons = append(results.header.reasons, editReason{head: fmt.Sprintf("The edited file had a syntax error: %v", err)}) - continue - } - // not a syntax error as it turns out... - containsError = false - - // put configuration annotation in "updates" - if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), updates, encoder); err != nil { - return preservedFile(err, file, out) - } - if cmdutil.ShouldRecord(cmd, updates) { - err = cmdutil.RecordChangeCause(updates.Object, f.Command()) - if err != nil { - return err - } - } - editedCopy := edited - if editedCopy, err = runtime.Encode(encoder, updates.Object); err != nil { - return preservedFile(err, file, out) - } - - visitor := resource.NewFlattenListVisitor(updates, resourceMapper) - - // need to make sure the original namespace wasn't changed while editing - if err = visitor.Visit(resource.RequireNamespace(cmdNamespace)); err != nil { - return preservedFile(err, file, out) - } - - // use strategic merge to create a patch - originalJS, err := yaml.ToJSON(original) - if err != nil { - return preservedFile(err, file, out) - } - editedJS, err := yaml.ToJSON(editedCopy) - if err != nil { - return preservedFile(err, file, out) - } - patch, err := strategicpatch.CreateStrategicMergePatch(originalJS, editedJS, obj) - // TODO: change all jsonmerge to strategicpatch - // for checking preconditions - preconditions := []jsonmerge.PreconditionFunc{} - if err != nil { - glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err) - return preservedFile(err, file, out) - } else { - preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("apiVersion")) - preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("kind")) - preconditions = append(preconditions, jsonmerge.RequireMetadataKeyUnchanged("name")) - results.version = defaultVersion - } - - if hold, msg := jsonmerge.TestPreconditionsHold(patch, preconditions); !hold { - fmt.Fprintf(out, "error: %s", msg) - return preservedFile(nil, file, out) - } - - err = visitor.Visit(func(info *resource.Info, err error) error { - patched, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch) - if err != nil { - glog.V(4).Infof(results.addError(err, info)) - return err - } - info.Refresh(patched, true) - cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, "edited") - return nil - }) - if err == nil { - os.Remove(file) - continue outter - } - // Handle all possible errors - // - // 1. retryable: propose kubectl replace -f - // 2. notfound: indicate the location of the saved configuration of the deleted resource - // 3. invalid: retry those on the spot by looping ie. reloading the editor - if results.retryable > 0 { - fmt.Fprintf(out, "You can run `%s replace -f %s` to try this update again.\n", os.Args[0], file) - continue outter - } - if results.notfound > 0 { - fmt.Fprintf(out, "The edits you made on deleted resources have been saved to %q\n", file) - continue outter - } - // validation error - containsError = true - } - } - return nil -} - -// editReason preserves a message about the reason this file must be edited again -type editReason struct { - head string - other []string -} - -// editHeader includes a list of reasons the edit must be retried -type editHeader struct { - reasons []editReason -} - -// writeTo outputs the current header information into a stream -func (h *editHeader) writeTo(w io.Writer) error { - fmt.Fprint(w, `# Please edit the object below. Lines beginning with a '#' will be ignored, -# and an empty file will abort the edit. If an error occurs while saving this file will be -# reopened with the relevant failures. -# -`) - for _, r := range h.reasons { - if len(r.other) > 0 { - fmt.Fprintf(w, "# %s:\n", r.head) - } else { - fmt.Fprintf(w, "# %s\n", r.head) - } - for _, o := range r.other { - fmt.Fprintf(w, "# * %s\n", o) - } - fmt.Fprintln(w, "#") - } - return nil -} - -func (h *editHeader) flush() { - h.reasons = []editReason{} -} - -// editResults capture the result of an update -type editResults struct { - header editHeader - retryable int - notfound int - edit []*resource.Info - file string - - version unversioned.GroupVersion -} - -func (r *editResults) addError(err error, info *resource.Info) string { - switch { - case errors.IsInvalid(err): - r.edit = append(r.edit, info) - reason := editReason{ - head: fmt.Sprintf("%s %q was not valid", info.Mapping.Resource, info.Name), - } - if err, ok := err.(errors.APIStatus); ok { - if details := err.Status().Details; details != nil { - for _, cause := range details.Causes { - reason.other = append(reason.other, fmt.Sprintf("%s: %s", cause.Field, cause.Message)) - } - } - } - r.header.reasons = append(r.header.reasons, reason) - return fmt.Sprintf("Error: %s %q is invalid", info.Mapping.Resource, info.Name) - case errors.IsNotFound(err): - r.notfound++ - return fmt.Sprintf("Error: %s %q could not be found on the server", info.Mapping.Resource, info.Name) - default: - r.retryable++ - return fmt.Sprintf("Error: %s %q could not be patched: %v", info.Mapping.Resource, info.Name, err) - } -} - -// preservedFile writes out a message about the provided file if it exists to the -// provided output stream when an error happens. Used to notify the user where -// their updates were preserved. -func preservedFile(err error, path string, out io.Writer) error { - if len(path) > 0 { - if _, err := os.Stat(path); !os.IsNotExist(err) { - fmt.Fprintf(out, "A copy of your changes has been stored to %q\n", path) - } - } - return err -} - -// hasLines returns true if any line in the provided stream is non empty - has non-whitespace -// characters, or the first non-whitespace character is a '#' indicating a comment. Returns -// any errors encountered reading the stream. -func hasLines(r io.Reader) (bool, error) { - // TODO: if any files we read have > 64KB lines, we'll need to switch to bytes.ReadLine - // TODO: probably going to be secrets - s := bufio.NewScanner(r) - for s.Scan() { - if line := strings.TrimSpace(s.Text()); len(line) > 0 && line[0] != '#' { - return true, nil - } - } - if err := s.Err(); err != nil && err != io.EOF { - return false, err - } - return false, nil -} - -// stripComments will transform a YAML file into JSON, thus dropping any comments -// in it. Note that if the given file has a syntax error, the transformation will -// fail and we will manually drop all comments from the file. -func stripComments(file []byte) []byte { - stripped := file - stripped, err := yaml.ToJSON(stripped) - if err != nil { - stripped = manualStrip(file) - } - return stripped -} - -// manualStrip is used for dropping comments from a YAML file -func manualStrip(file []byte) []byte { - stripped := []byte{} - lines := bytes.Split(file, []byte("\n")) - for i, line := range lines { - if bytes.HasPrefix(bytes.TrimSpace(line), []byte("#")) { - continue - } - stripped = append(stripped, line...) - if i < len(lines)-1 { - stripped = append(stripped, '\n') - } - } - return stripped -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/exec.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/exec.go deleted file mode 100644 index eec6da62f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/exec.go +++ /dev/null @@ -1,239 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "net/url" - "os" - "os/signal" - "syscall" - - "github.com/docker/docker/pkg/term" - "github.com/golang/glog" - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/remotecommand" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -const ( - exec_example = `# Get output from running 'date' from pod 123456-7890, using the first container by default -$ kubectl exec 123456-7890 date - -# Get output from running 'date' in ruby-container from pod 123456-7890 -$ kubectl exec 123456-7890 -c ruby-container date - -# Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890 -# and sends stdout/stderr from 'bash' back to the client -$ kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il` -) - -func NewCmdExec(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer) *cobra.Command { - options := &ExecOptions{ - In: cmdIn, - Out: cmdOut, - Err: cmdErr, - - Executor: &DefaultRemoteExecutor{}, - } - cmd := &cobra.Command{ - Use: "exec POD [-c CONTAINER] -- COMMAND [args...]", - Short: "Execute a command in a container.", - Long: "Execute a command in a container.", - Example: exec_example, - Run: func(cmd *cobra.Command, args []string) { - argsLenAtDash := cmd.ArgsLenAtDash() - cmdutil.CheckErr(options.Complete(f, cmd, args, argsLenAtDash)) - cmdutil.CheckErr(options.Validate()) - cmdutil.CheckErr(options.Run()) - }, - } - cmd.Flags().StringVarP(&options.PodName, "pod", "p", "", "Pod name") - // TODO support UID - cmd.Flags().StringVarP(&options.ContainerName, "container", "c", "", "Container name. If omitted, the first container in the pod will be chosen") - cmd.Flags().BoolVarP(&options.Stdin, "stdin", "i", false, "Pass stdin to the container") - cmd.Flags().BoolVarP(&options.TTY, "tty", "t", false, "Stdin is a TTY") - return cmd -} - -// RemoteExecutor defines the interface accepted by the Exec command - provided for test stubbing -type RemoteExecutor interface { - Execute(method string, url *url.URL, config *client.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool) error -} - -// DefaultRemoteExecutor is the standard implementation of remote command execution -type DefaultRemoteExecutor struct{} - -func (*DefaultRemoteExecutor) Execute(method string, url *url.URL, config *client.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool) error { - exec, err := remotecommand.NewExecutor(config, method, url) - if err != nil { - return err - } - return exec.Stream(stdin, stdout, stderr, tty) -} - -// ExecOptions declare the arguments accepted by the Exec command -type ExecOptions struct { - Namespace string - PodName string - ContainerName string - Stdin bool - TTY bool - Command []string - - In io.Reader - Out io.Writer - Err io.Writer - - Executor RemoteExecutor - Client *client.Client - Config *client.Config -} - -// Complete verifies command line arguments and loads data from the command environment -func (p *ExecOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, argsIn []string, argsLenAtDash int) error { - // Let kubectl exec follow rules for `--`, see #13004 issue - if len(p.PodName) == 0 && (len(argsIn) == 0 || argsLenAtDash == 0) { - return cmdutil.UsageError(cmd, "POD is required for exec") - } - if len(p.PodName) != 0 { - printDeprecationWarning("exec POD", "-p POD") - if len(argsIn) < 1 { - return cmdutil.UsageError(cmd, "COMMAND is required for exec") - } - p.Command = argsIn - } else { - p.PodName = argsIn[0] - p.Command = argsIn[1:] - if len(p.Command) < 1 { - return cmdutil.UsageError(cmd, "COMMAND is required for exec") - } - } - - namespace, _, err := f.DefaultNamespace() - if err != nil { - return err - } - p.Namespace = namespace - - config, err := f.ClientConfig() - if err != nil { - return err - } - p.Config = config - - client, err := f.Client() - if err != nil { - return err - } - p.Client = client - - return nil -} - -// Validate checks that the provided exec options are specified. -func (p *ExecOptions) Validate() error { - if len(p.PodName) == 0 { - return fmt.Errorf("pod name must be specified") - } - if len(p.Command) == 0 { - return fmt.Errorf("you must specify at least one command for the container") - } - if p.Out == nil || p.Err == nil { - return fmt.Errorf("both output and error output must be provided") - } - if p.Executor == nil || p.Client == nil || p.Config == nil { - return fmt.Errorf("client, client config, and executor must be provided") - } - return nil -} - -// Run executes a validated remote execution against a pod. -func (p *ExecOptions) Run() error { - pod, err := p.Client.Pods(p.Namespace).Get(p.PodName) - if err != nil { - return err - } - - if pod.Status.Phase != api.PodRunning { - return fmt.Errorf("pod %s is not running and cannot execute commands; current phase is %s", p.PodName, pod.Status.Phase) - } - - containerName := p.ContainerName - if len(containerName) == 0 { - glog.V(4).Infof("defaulting container name to %s", pod.Spec.Containers[0].Name) - containerName = pod.Spec.Containers[0].Name - } - - // TODO: refactor with terminal helpers from the edit utility once that is merged - var stdin io.Reader - tty := p.TTY - if p.Stdin { - stdin = p.In - if tty { - if file, ok := stdin.(*os.File); ok { - inFd := file.Fd() - if term.IsTerminal(inFd) { - oldState, err := term.SetRawTerminal(inFd) - if err != nil { - glog.Fatal(err) - } - // this handles a clean exit, where the command finished - defer term.RestoreTerminal(inFd, oldState) - - // SIGINT is handled by term.SetRawTerminal (it runs a goroutine that listens - // for SIGINT and restores the terminal before exiting) - - // this handles SIGTERM - sigChan := make(chan os.Signal, 1) - signal.Notify(sigChan, syscall.SIGTERM) - go func() { - <-sigChan - term.RestoreTerminal(inFd, oldState) - os.Exit(0) - }() - } else { - fmt.Fprintln(p.Err, "STDIN is not a terminal") - } - } else { - tty = false - fmt.Fprintln(p.Err, "Unable to use a TTY - input is not the right kind of file") - } - } - } - - // TODO: consider abstracting into a client invocation or client helper - req := p.Client.RESTClient.Post(). - Resource("pods"). - Name(pod.Name). - Namespace(pod.Namespace). - SubResource("exec"). - Param("container", containerName) - req.VersionedParams(&api.PodExecOptions{ - Container: containerName, - Command: p.Command, - Stdin: stdin != nil, - Stdout: p.Out != nil, - Stderr: p.Err != nil, - TTY: tty, - }, api.ParameterCodec) - - return p.Executor.Execute("POST", req.URL(), p.Config, stdin, p.Out, p.Err, tty) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/exec_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/exec_test.go deleted file mode 100644 index 8317db936..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/exec_test.go +++ /dev/null @@ -1,258 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "fmt" - "io" - "net/http" - "net/url" - "reflect" - "testing" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -type fakeRemoteExecutor struct { - method string - url *url.URL - execErr error -} - -func (f *fakeRemoteExecutor) Execute(method string, url *url.URL, config *client.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool) error { - f.method = method - f.url = url - return f.execErr -} - -func TestPodAndContainer(t *testing.T) { - tests := []struct { - args []string - argsLenAtDash int - p *ExecOptions - name string - expectError bool - expectedPod string - expectedContainer string - expectedArgs []string - }{ - { - p: &ExecOptions{}, - argsLenAtDash: -1, - expectError: true, - name: "empty", - }, - { - p: &ExecOptions{PodName: "foo"}, - argsLenAtDash: -1, - expectError: true, - name: "no cmd", - }, - { - p: &ExecOptions{PodName: "foo", ContainerName: "bar"}, - argsLenAtDash: -1, - expectError: true, - name: "no cmd, w/ container", - }, - { - p: &ExecOptions{PodName: "foo"}, - args: []string{"cmd"}, - argsLenAtDash: -1, - expectedPod: "foo", - expectedArgs: []string{"cmd"}, - name: "pod in flags", - }, - { - p: &ExecOptions{}, - args: []string{"foo", "cmd"}, - argsLenAtDash: 0, - expectError: true, - name: "no pod, pod name is behind dash", - }, - { - p: &ExecOptions{}, - args: []string{"foo"}, - argsLenAtDash: -1, - expectError: true, - name: "no cmd, w/o flags", - }, - { - p: &ExecOptions{}, - args: []string{"foo", "cmd"}, - argsLenAtDash: -1, - expectedPod: "foo", - expectedArgs: []string{"cmd"}, - name: "cmd, w/o flags", - }, - { - p: &ExecOptions{}, - args: []string{"foo", "cmd"}, - argsLenAtDash: 1, - expectedPod: "foo", - expectedArgs: []string{"cmd"}, - name: "cmd, cmd is behind dash", - }, - { - p: &ExecOptions{ContainerName: "bar"}, - args: []string{"foo", "cmd"}, - argsLenAtDash: -1, - expectedPod: "foo", - expectedContainer: "bar", - expectedArgs: []string{"cmd"}, - name: "cmd, container in flag", - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { return nil, nil }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{} - - cmd := &cobra.Command{} - options := test.p - err := options.Complete(f, cmd, test.args, test.argsLenAtDash) - if test.expectError && err == nil { - t.Errorf("unexpected non-error (%s)", test.name) - } - if !test.expectError && err != nil { - t.Errorf("unexpected error: %v (%s)", err, test.name) - } - if err != nil { - continue - } - if options.PodName != test.expectedPod { - t.Errorf("expected: %s, got: %s (%s)", test.expectedPod, options.PodName, test.name) - } - if options.ContainerName != test.expectedContainer { - t.Errorf("expected: %s, got: %s (%s)", test.expectedContainer, options.ContainerName, test.name) - } - if !reflect.DeepEqual(test.expectedArgs, options.Command) { - t.Errorf("expected: %v, got %v (%s)", test.expectedArgs, options.Command, test.name) - } - } -} - -func TestExec(t *testing.T) { - version := testapi.Default.GroupVersion().Version - tests := []struct { - name, version, podPath, execPath, container string - pod *api.Pod - execErr bool - }{ - { - name: "pod exec", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - execPath: "/api/" + version + "/namespaces/test/pods/foo/exec", - pod: execPod(), - }, - { - name: "pod exec error", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - execPath: "/api/" + version + "/namespaces/test/pods/foo/exec", - pod: execPod(), - execErr: true, - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == test.podPath && m == "GET": - body := objBody(codec, test.pod) - return &http.Response{StatusCode: 200, Body: body}, nil - default: - // Ensures no GET is performed when deleting by name - t.Errorf("%s: unexpected request: %s %#v\n%#v", test.name, req.Method, req.URL, req) - return nil, fmt.Errorf("unexpected request") - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}} - bufOut := bytes.NewBuffer([]byte{}) - bufErr := bytes.NewBuffer([]byte{}) - bufIn := bytes.NewBuffer([]byte{}) - ex := &fakeRemoteExecutor{} - if test.execErr { - ex.execErr = fmt.Errorf("exec error") - } - params := &ExecOptions{ - PodName: "foo", - ContainerName: "bar", - In: bufIn, - Out: bufOut, - Err: bufErr, - Executor: ex, - } - cmd := &cobra.Command{} - args := []string{"test", "command"} - if err := params.Complete(f, cmd, args, -1); err != nil { - t.Fatal(err) - } - err := params.Run() - if test.execErr && err != ex.execErr { - t.Errorf("%s: Unexpected exec error: %v", test.name, err) - continue - } - if !test.execErr && err != nil { - t.Errorf("%s: Unexpected error: %v", test.name, err) - continue - } - if test.execErr { - continue - } - if ex.url.Path != test.execPath { - t.Errorf("%s: Did not get expected path for exec request", test.name) - continue - } - if ex.method != "POST" { - t.Errorf("%s: Did not get method for exec request: %s", test.name, ex.method) - } - } -} - -func execPod() *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"}, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{ - { - Name: "bar", - }, - }, - }, - Status: api.PodStatus{ - Phase: api.PodRunning, - }, - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/explain.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/explain.go deleted file mode 100644 index 765091c03..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/explain.go +++ /dev/null @@ -1,107 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -const ( - explainExamples = `# Get the documentation of the resource and its fields -$ kubectl explain pods - -# Get the documentation of a specific field of a resource -$ kubectl explain pods.spec.containers` - - explainLong = `Documentation of resources. - -Possible resource types include: pods (po), services (svc), -replicationcontrollers (rc), nodes (no), events (ev), componentstatuses (cs), -limitranges (limits), persistentvolumes (pv), persistentvolumeclaims (pvc), -resourcequotas (quota), namespaces (ns), horizontalpodautoscalers (hpa) -or endpoints (ep).` -) - -// NewCmdExplain returns a cobra command for swagger docs -func NewCmdExplain(f *cmdutil.Factory, out io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "explain RESOURCE", - Short: "Documentation of resources.", - Long: explainLong, - Example: explainExamples, - Run: func(cmd *cobra.Command, args []string) { - err := RunExplain(f, out, cmd, args) - cmdutil.CheckErr(err) - }, - } - cmd.Flags().Bool("recursive", false, "Print the fields of fields (Currently only 1 level deep)") - return cmd -} - -// RunExplain executes the appropriate steps to print a model's documentation -func RunExplain(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { - if len(args) != 1 { - return cmdutil.UsageError(cmd, "We accept only this format: explain RESOURCE") - } - - recursive := cmdutil.GetFlagBool(cmd, "recursive") - apiVersionString := cmdutil.GetFlagString(cmd, "api-version") - apiVersion := unversioned.GroupVersion{} - - mapper, _ := f.Object() - // TODO: After we figured out the new syntax to separate group and resource, allow - // the users to use it in explain (kubectl explain ). - // Refer to issue #16039 for why we do this. Refer to PR #15808 that used "/" syntax. - inModel, fieldsPath, err := kubectl.SplitAndParseResourceRequest(args[0], mapper) - if err != nil { - return err - } - - // TODO: We should deduce the group for a resource by discovering the supported resources at server. - gvk, err := mapper.KindFor(unversioned.GroupVersionResource{Resource: inModel}) - if err != nil { - return err - } - - if len(apiVersionString) == 0 { - groupMeta, err := registered.Group(gvk.Group) - if err != nil { - return err - } - apiVersion = groupMeta.GroupVersion - - } else { - apiVersion, err = unversioned.ParseGroupVersion(apiVersionString) - if err != nil { - return nil - } - } - - schema, err := f.SwaggerSchema(apiVersion.WithKind(gvk.Kind)) - if err != nil { - return err - } - - return kubectl.PrintModelDescription(inModel, fieldsPath, out, schema, recursive) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/expose.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/expose.go deleted file mode 100644 index 48b624436..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/expose.go +++ /dev/null @@ -1,244 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "strings" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/validation" -) - -// ExposeOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type ExposeOptions struct { - Filenames []string -} - -const ( - expose_long = `Take a replication controller, service, replica set or pod and expose it as a new Kubernetes service. - -Looks up a replication controller, service, replica set or pod by name and uses the selector for that -resource as the selector for a new service on the specified port. A replica set will be exposed as a -service only if it's selector is convertible to a selector that service supports, i.e. when the -replica set selector contains only the matchLabels component. Note that if no port is specified -via --port and the exposed resource has multiple ports, all will be re-used by the new service. Also -if no labels are specified, the new service will re-use the labels from the resource it exposes.` - - expose_example = `# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000. -$ kubectl expose rc nginx --port=80 --target-port=8000 - -# Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml", which serves on port 80 and connects to the containers on port 8000. -$ kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000 - -# Create a service for a pod valid-pod, which serves on port 444 with the name "frontend" -$ kubectl expose pod valid-pod --port=444 --name=frontend - -# Create a second service based on the above service, exposing the container port 8443 as port 443 with the name "nginx-https" -$ kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https - -# Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'. -$ kubectl expose rc streamer --port=4100 --protocol=udp --name=video-stream - -# Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on port 8000. -$ kubectl expose rs nginx --port=80 --target-port=8000` -) - -func NewCmdExposeService(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &ExposeOptions{} - - cmd := &cobra.Command{ - Use: "expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]", - Short: "Take a replication controller, service or pod and expose it as a new Kubernetes Service", - Long: expose_long, - Example: expose_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunExpose(f, out, cmd, args, options) - cmdutil.CheckErr(err) - }, - } - cmdutil.AddPrinterFlags(cmd) - cmd.Flags().String("generator", "service/v2", "The name of the API generator to use. There are 2 generators: 'service/v1' and 'service/v2'. The only difference between them is that service port in v1 is named 'default', while it is left unnamed in v2. Default is 'service/v2'.") - cmd.Flags().String("protocol", "TCP", "The network protocol for the service to be created. Default is 'tcp'.") - cmd.Flags().String("port", "", "The port that the service should serve on. Copied from the resource being exposed, if unspecified") - cmd.Flags().String("type", "", "Type for this service: ClusterIP, NodePort, or LoadBalancer. Default is 'ClusterIP'.") - // TODO: remove create-external-load-balancer in code on or after Aug 25, 2016. - cmd.Flags().Bool("create-external-load-balancer", false, "If true, create an external load balancer for this service (trumped by --type). Implementation is cloud provider dependent. Default is 'false'.") - cmd.Flags().MarkDeprecated("create-external-load-balancer", "use --type=\"LoadBalancer\" instead") - cmd.Flags().String("load-balancer-ip", "", "IP to assign to to the Load Balancer. If empty, an ephemeral IP will be created and used (cloud-provider specific).") - cmd.Flags().String("selector", "", "A label selector to use for this service. Only equality-based selector requirements are supported. If empty (the default) infer the selector from the replication controller or replica set.") - cmd.Flags().StringP("labels", "l", "", "Labels to apply to the service created by this call.") - cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without creating it.") - cmd.Flags().String("container-port", "", "Synonym for --target-port") - cmd.Flags().String("target-port", "", "Name or number for the port on the container that the service should direct traffic to. Optional.") - cmd.Flags().String("external-ip", "", "Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP is routed to a node, the service can be accessed by this IP in addition to its generated service IP.") - cmd.Flags().String("overrides", "", "An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.") - cmd.Flags().String("name", "", "The name for the newly created object.") - cmd.Flags().String("session-affinity", "", "If non-empty, set the session affinity for the service to this; legal values: 'None', 'ClientIP'") - - usage := "Filename, directory, or URL to a file identifying the resource to expose a service" - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddRecordFlag(cmd) - return cmd -} - -func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ExposeOptions) error { - namespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(namespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - ResourceTypeOrNameArgs(false, args...). - Flatten(). - Do() - infos, err := r.Infos() - if err != nil { - return err - } - if len(infos) > 1 { - return fmt.Errorf("multiple resources provided: %v", args) - } - info := infos[0] - mapping := info.ResourceMapping() - if err := f.CanBeExposed(mapping.GroupVersionKind.GroupKind()); err != nil { - return err - } - // Get the input object - inputObject, err := r.Object() - if err != nil { - return err - } - - // Get the generator, setup and validate all required parameters - generatorName := cmdutil.GetFlagString(cmd, "generator") - generators := f.Generators("expose") - generator, found := generators[generatorName] - if !found { - return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName)) - } - names := generator.ParamNames() - params := kubectl.MakeParams(cmd, names) - name := info.Name - if len(name) > validation.DNS952LabelMaxLength { - name = name[:validation.DNS952LabelMaxLength] - } - params["default-name"] = name - - // For objects that need a pod selector, derive it from the exposed object in case a user - // didn't explicitly specify one via --selector - if s, found := params["selector"]; found && kubectl.IsZero(s) { - s, err := f.MapBasedSelectorForObject(inputObject) - if err != nil { - return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't retrieve selectors via --selector flag or introspection: %s", err)) - } - params["selector"] = s - } - - // For objects that need a port, derive it from the exposed object in case a user - // didn't explicitly specify one via --port - if port, found := params["port"]; found && kubectl.IsZero(port) { - ports, err := f.PortsForObject(inputObject) - if err != nil { - return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err)) - } - switch len(ports) { - case 0: - return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection") - case 1: - params["port"] = ports[0] - default: - params["ports"] = strings.Join(ports, ",") - } - } - if kubectl.IsZero(params["labels"]) { - labels, err := f.LabelsForObject(inputObject) - if err != nil { - return err - } - params["labels"] = kubectl.MakeLabels(labels) - } - if err = kubectl.ValidateParams(names, params); err != nil { - return err - } - // Check for invalid flags used against the present generator. - if err := kubectl.EnsureFlagsValid(cmd, generators, generatorName); err != nil { - return err - } - - // Generate new object - object, err := generator.Generate(params) - if err != nil { - return err - } - - if inline := cmdutil.GetFlagString(cmd, "overrides"); len(inline) > 0 { - codec := runtime.NewCodec(f.JSONEncoder(), f.Decoder(true)) - object, err = cmdutil.Merge(codec, object, inline, mapping.GroupVersionKind.Kind) - if err != nil { - return err - } - } - - resourceMapper := &resource.Mapper{ - ObjectTyper: typer, - RESTMapper: mapper, - ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), - Decoder: f.Decoder(true), - } - info, err = resourceMapper.InfoForObject(object) - if err != nil { - return err - } - if cmdutil.ShouldRecord(cmd, info) { - if err := cmdutil.RecordChangeCause(object, f.Command()); err != nil { - return err - } - } - info.Refresh(object, true) - // TODO: extract this flag to a central location, when such a location exists. - if cmdutil.GetFlagBool(cmd, "dry-run") { - return f.PrintObject(cmd, object, out) - } - if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { - return err - } - - // Serialize the object with the annotation applied. - object, err = resource.NewHelper(info.Client, info.Mapping).Create(namespace, false, object) - if err != nil { - return err - } - - if len(cmdutil.GetFlagString(cmd, "output")) > 0 { - return f.PrintObject(cmd, object, out) - } - cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, "exposed") - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/expose_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/expose_test.go deleted file mode 100644 index 6bad24357..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/expose_test.go +++ /dev/null @@ -1,351 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/kubectl" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/intstr" -) - -func TestRunExposeService(t *testing.T) { - tests := []struct { - name string - args []string - ns string - calls map[string]string - input runtime.Object - flags map[string]string - output runtime.Object - expected string - status int - }{ - { - name: "expose-service-from-service-no-selector-defined", - args: []string{"service", "baz"}, - ns: "test", - calls: map[string]string{ - "GET": "/namespaces/test/services/baz", - "POST": "/namespaces/test/services", - }, - input: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{"app": "go"}, - }, - }, - flags: map[string]string{"protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolUDP, - Port: 14, - TargetPort: intstr.FromInt(14), - }, - }, - Selector: map[string]string{"app": "go"}, - }, - }, - expected: "service \"foo\" exposed", - status: 200, - }, - { - name: "expose-service-from-service", - args: []string{"service", "baz"}, - ns: "test", - calls: map[string]string{ - "GET": "/namespaces/test/services/baz", - "POST": "/namespaces/test/services", - }, - input: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{"app": "go"}, - }, - }, - flags: map[string]string{"selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolUDP, - Port: 14, - TargetPort: intstr.FromInt(14), - }, - }, - Selector: map[string]string{"func": "stream"}, - }, - }, - expected: "service \"foo\" exposed", - status: 200, - }, - { - name: "no-name-passed-from-the-cli", - args: []string{"service", "mayor"}, - ns: "default", - calls: map[string]string{ - "GET": "/namespaces/default/services/mayor", - "POST": "/namespaces/default/services", - }, - input: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "mayor", Namespace: "default", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{"run": "this"}, - }, - }, - // No --name flag specified below. Service will use the rc's name passed via the 'default-name' parameter - flags: map[string]string{"selector": "run=this", "port": "80", "labels": "runas=amayor"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "mayor", Namespace: "", Labels: map[string]string{"runas": "amayor"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolTCP, - Port: 80, - TargetPort: intstr.FromInt(80), - }, - }, - Selector: map[string]string{"run": "this"}, - }, - }, - expected: "service \"mayor\" exposed", - status: 200, - }, - { - name: "expose-service", - args: []string{"service", "baz"}, - ns: "test", - calls: map[string]string{ - "GET": "/namespaces/test/services/baz", - "POST": "/namespaces/test/services", - }, - input: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{"app": "go"}, - }, - }, - flags: map[string]string{"selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test", "type": "LoadBalancer", "dry-run": "true"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolUDP, - Port: 14, - TargetPort: intstr.FromInt(14), - }, - }, - Selector: map[string]string{"func": "stream"}, - Type: api.ServiceTypeLoadBalancer, - }, - }, - status: 200, - }, - { - name: "expose-affinity-service", - args: []string{"service", "baz"}, - ns: "test", - calls: map[string]string{ - "GET": "/namespaces/test/services/baz", - "POST": "/namespaces/test/services", - }, - input: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{"app": "go"}, - }, - }, - flags: map[string]string{"selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test", "type": "LoadBalancer", "session-affinity": "ClientIP", "dry-run": "true"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "test"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolUDP, - Port: 14, - TargetPort: intstr.FromInt(14), - }, - }, - Selector: map[string]string{"func": "stream"}, - Type: api.ServiceTypeLoadBalancer, - SessionAffinity: api.ServiceAffinityClientIP, - }, - }, - status: 200, - }, - { - name: "expose-from-file", - args: []string{}, - ns: "test", - calls: map[string]string{ - "GET": "/namespaces/test/services/redis-master", - "POST": "/namespaces/test/services", - }, - input: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "redis-master", Namespace: "test", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{"app": "go"}, - }, - }, - flags: map[string]string{"filename": "../../../examples/guestbook/redis-master-service.yaml", "selector": "func=stream", "protocol": "UDP", "port": "14", "name": "foo", "labels": "svc=test", "dry-run": "true"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Labels: map[string]string{"svc": "test"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolUDP, - Port: 14, - TargetPort: intstr.FromInt(14), - }, - }, - Selector: map[string]string{"func": "stream"}, - }, - }, - status: 200, - }, - { - name: "truncate-name", - args: []string{"pod", "a-name-that-is-toooo-big-for-a-service"}, - ns: "test", - calls: map[string]string{ - "GET": "/namespaces/test/pods/a-name-that-is-toooo-big-for-a-service", - "POST": "/namespaces/test/services", - }, - input: &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - }, - flags: map[string]string{"selector": "svc=frompod", "port": "90", "labels": "svc=frompod", "generator": "service/v2"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "a-name-that-is-toooo-big", Namespace: "", Labels: map[string]string{"svc": "frompod"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolTCP, - Port: 90, - TargetPort: intstr.FromInt(90), - }, - }, - Selector: map[string]string{"svc": "frompod"}, - }, - }, - expected: "service \"a-name-that-is-toooo-big\" exposed", - status: 200, - }, - { - name: "expose-multiport-object", - args: []string{"service", "foo"}, - ns: "test", - calls: map[string]string{ - "GET": "/namespaces/test/services/foo", - "POST": "/namespaces/test/services", - }, - input: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "", Labels: map[string]string{"svc": "multiport"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolTCP, - Port: 80, - TargetPort: intstr.FromInt(80), - }, - { - Protocol: api.ProtocolTCP, - Port: 443, - TargetPort: intstr.FromInt(443), - }, - }, - }, - }, - flags: map[string]string{"selector": "svc=fromfoo", "generator": "service/v2", "name": "fromfoo", "dry-run": "true"}, - output: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "fromfoo", Namespace: "", Labels: map[string]string{"svc": "multiport"}}, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Name: "port-1", - Protocol: api.ProtocolTCP, - Port: 80, - TargetPort: intstr.FromInt(80), - }, - { - Name: "port-2", - Protocol: api.ProtocolTCP, - Port: 443, - TargetPort: intstr.FromInt(443), - }, - }, - Selector: map[string]string{"svc": "fromfoo"}, - }, - }, - status: 200, - }, - } - - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Printer = &kubectl.JSONPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == test.calls[m] && m == "GET": - return &http.Response{StatusCode: test.status, Body: objBody(codec, test.input)}, nil - case p == test.calls[m] && m == "POST": - return &http.Response{StatusCode: test.status, Body: objBody(codec, test.output)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = test.ns - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdExposeService(f, buf) - cmd.SetOutput(buf) - for flag, value := range test.flags { - cmd.Flags().Set(flag, value) - } - cmd.Run(cmd, test.args) - - out := buf.String() - if _, ok := test.flags["dry-run"]; ok { - buf.Reset() - if err := tf.Printer.PrintObj(test.output, buf); err != nil { - t.Errorf("%s: Unexpected error: %v", test.name, err) - continue - } - - test.expected = buf.String() - } - - if !strings.Contains(out, test.expected) { - t.Errorf("%s: Unexpected output! Expected\n%s\ngot\n%s", test.name, test.expected, out) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/get.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/get.go deleted file mode 100644 index 21706e60d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/get.go +++ /dev/null @@ -1,288 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/watch" -) - -// GetOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type GetOptions struct { - Filenames []string -} - -const ( - get_long = `Display one or many resources. - -Possible resource types include (case insensitive): pods (po), services (svc), -replicationcontrollers (rc), nodes (no), events (ev), componentstatuses (cs), -limitranges (limits), persistentvolumes (pv), persistentvolumeclaims (pvc), -resourcequotas (quota), namespaces (ns), endpoints (ep), -horizontalpodautoscalers (hpa), serviceaccounts or secrets. - -By specifying the output as 'template' and providing a Go template as the value -of the --template flag, you can filter the attributes of the fetched resource(s).` - get_example = `# List all pods in ps output format. -$ kubectl get pods - -# List all pods in ps output format with more information (such as node name). -$ kubectl get pods -o wide - -# List a single replication controller with specified NAME in ps output format. -$ kubectl get replicationcontroller web - -# List a single pod in JSON output format. -$ kubectl get -o json pod web-pod-13je7 - -# List a pod identified by type and name specified in "pod.yaml" in JSON output format. -$ kubectl get -f pod.yaml -o json - -# Return only the phase value of the specified pod. -$ kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}} --api-version=v1 - -# List all replication controllers and services together in ps output format. -$ kubectl get rc,services - -# List one or more resources by their type and names. -$ kubectl get rc/web service/frontend pods/web-pod-13je7` -) - -// NewCmdGet creates a command object for the generic "get" action, which -// retrieves one or more resources from a server. -func NewCmdGet(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &GetOptions{} - - // retrieve a list of handled resources from printer as valid args - validArgs := []string{} - p, err := f.Printer(nil, false, false, false, false, false, false, []string{}) - cmdutil.CheckErr(err) - if p != nil { - validArgs = p.HandledResources() - } - - cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|wide|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] (TYPE [NAME | -l label] | TYPE/NAME ...) [flags]", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunGet(f, out, cmd, args, options) - cmdutil.CheckErr(err) - }, - ValidArgs: validArgs, - } - cmdutil.AddPrinterFlags(cmd) - cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on") - cmd.Flags().BoolP("watch", "w", false, "After listing/getting the requested object, watch for changes.") - cmd.Flags().Bool("watch-only", false, "Watch for changes to the requested object(s), without listing/getting first.") - cmd.Flags().Bool("all-namespaces", false, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.") - cmd.Flags().StringSliceP("label-columns", "L", []string{}, "Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive. You can also use multiple flag statements like -L label1 -L label2...") - cmd.Flags().Bool("export", false, "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information.") - usage := "Filename, directory, or URL to a file identifying the resource to get from a server." - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - return cmd -} - -// RunGet implements the generic Get command -// TODO: convert all direct flag accessors to a struct and pass that instead of cmd -func RunGet(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *GetOptions) error { - selector := cmdutil.GetFlagString(cmd, "selector") - allNamespaces := cmdutil.GetFlagBool(cmd, "all-namespaces") - mapper, typer := f.Object() - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - if allNamespaces { - enforceNamespace = false - } - - if len(args) == 0 && len(options.Filenames) == 0 { - fmt.Fprint(out, "You must specify the type of resource to get. ", valid_resources) - return cmdutil.UsageError(cmd, "Required resource not specified.") - } - - // always show resources when getting by name or filename - argsHasNames, err := resource.HasNames(args) - if err != nil { - return err - } - if len(options.Filenames) > 0 || argsHasNames { - cmd.Flag("show-all").Value.Set("true") - } - export := cmdutil.GetFlagBool(cmd, "export") - - // handle watch separately since we cannot watch multiple resource types - isWatch, isWatchOnly := cmdutil.GetFlagBool(cmd, "watch"), cmdutil.GetFlagBool(cmd, "watch-only") - if isWatch || isWatchOnly { - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces). - FilenameParam(enforceNamespace, options.Filenames...). - SelectorParam(selector). - ExportParam(export). - ResourceTypeOrNameArgs(true, args...). - SingleResourceType(). - Latest(). - Do() - err := r.Err() - if err != nil { - return err - } - infos, err := r.Infos() - if err != nil { - return err - } - if len(infos) != 1 { - return fmt.Errorf("watch is only supported on individual resources and resource collections - %d resources were found", len(infos)) - } - info := infos[0] - mapping := info.ResourceMapping() - printer, err := f.PrinterForMapping(cmd, mapping, allNamespaces) - if err != nil { - return err - } - - obj, err := r.Object() - if err != nil { - return err - } - rv, err := mapping.MetadataAccessor.ResourceVersion(obj) - if err != nil { - return err - } - - // print the current object - if !isWatchOnly { - if err := printer.PrintObj(obj, out); err != nil { - return fmt.Errorf("unable to output the provided object: %v", err) - } - } - - // print watched changes - w, err := r.Watch(rv) - if err != nil { - return err - } - - kubectl.WatchLoop(w, func(e watch.Event) error { - return printer.PrintObj(e.Object, out) - }) - return nil - } - - b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace().AllNamespaces(allNamespaces). - FilenameParam(enforceNamespace, options.Filenames...). - SelectorParam(selector). - ExportParam(export). - ResourceTypeOrNameArgs(true, args...). - ContinueOnError(). - Latest() - printer, generic, err := cmdutil.PrinterForCommand(cmd) - if err != nil { - return err - } - - if generic { - clientConfig, err := f.ClientConfig() - if err != nil { - return err - } - - singular := false - r := b.Flatten().Do() - infos, err := r.IntoSingular(&singular).Infos() - if err != nil { - return err - } - - // the outermost object will be converted to the output-version, but inner - // objects can use their mappings - version, err := cmdutil.OutputVersion(cmd, clientConfig.GroupVersion) - if err != nil { - return err - } - obj, err := resource.AsVersionedObject(infos, !singular, version.String(), f.JSONEncoder()) - if err != nil { - return err - } - - return printer.PrintObj(obj, out) - } - - infos, err := b.Flatten().Do().Infos() - if err != nil { - return err - } - objs := make([]runtime.Object, len(infos)) - for ix := range infos { - objs[ix] = infos[ix].Object - } - - sorting, err := cmd.Flags().GetString("sort-by") - var sorter *kubectl.RuntimeSort - if err == nil && len(sorting) > 0 && len(objs) > 1 { - // TODO: questionable - if sorter, err = kubectl.SortObjects(f.Decoder(true), objs, sorting); err != nil { - return err - } - } - - // use the default printer for each object - printer = nil - var lastMapping *meta.RESTMapping - w := kubectl.GetNewTabWriter(out) - defer w.Flush() - - for ix := range objs { - var mapping *meta.RESTMapping - if sorter != nil { - mapping = infos[sorter.OriginalPosition(ix)].Mapping - } else { - mapping = infos[ix].Mapping - } - if printer == nil || lastMapping == nil || mapping == nil || mapping.Resource != lastMapping.Resource { - printer, err = f.PrinterForMapping(cmd, mapping, allNamespaces) - if err != nil { - return err - } - lastMapping = mapping - } - if _, found := printer.(*kubectl.HumanReadablePrinter); found { - if err := printer.PrintObj(objs[ix], w); err != nil { - return err - } - continue - } - if err := printer.PrintObj(objs[ix], w); err != nil { - return err - } - } - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/get_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/get_test.go deleted file mode 100644 index 4d4ac5e18..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/get_test.go +++ /dev/null @@ -1,817 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - encjson "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/watch" - "k8s.io/kubernetes/pkg/watch/json" -) - -func testData() (*api.PodList, *api.ServiceList, *api.ReplicationControllerList) { - pods := &api.PodList{ - ListMeta: unversioned.ListMeta{ - ResourceVersion: "15", - }, - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "test", ResourceVersion: "11"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - }, - } - svc := &api.ServiceList{ - ListMeta: unversioned.ListMeta{ - ResourceVersion: "16", - }, - Items: []api.Service{ - { - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - SessionAffinity: "None", - Type: api.ServiceTypeClusterIP, - }, - }, - }, - } - rc := &api.ReplicationControllerList{ - ListMeta: unversioned.ListMeta{ - ResourceVersion: "17", - }, - Items: []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{Name: "rc1", Namespace: "test", ResourceVersion: "18"}, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - }, - }, - }, - } - return pods, svc, rc -} - -func testComponentStatusData() *api.ComponentStatusList { - good := api.ComponentStatus{ - Conditions: []api.ComponentCondition{ - {Type: api.ComponentHealthy, Status: api.ConditionTrue, Message: "ok"}, - }, - ObjectMeta: api.ObjectMeta{Name: "servergood"}, - } - - bad := api.ComponentStatus{ - Conditions: []api.ComponentCondition{ - {Type: api.ComponentHealthy, Status: api.ConditionFalse, Message: "", Error: "bad status: 500"}, - }, - ObjectMeta: api.ObjectMeta{Name: "serverbad"}, - } - - unknown := api.ComponentStatus{ - Conditions: []api.ComponentCondition{ - {Type: api.ComponentHealthy, Status: api.ConditionUnknown, Message: "", Error: "fizzbuzz error"}, - }, - ObjectMeta: api.ObjectMeta{Name: "serverunknown"}, - } - - return &api.ComponentStatusList{ - Items: []api.ComponentStatus{good, bad, unknown}, - } -} - -// Verifies that schemas that are not in the master tree of Kubernetes can be retrieved via Get. -func TestGetUnknownSchemaObject(t *testing.T) { - f, tf, codec := NewTestFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, &internalType{Name: "foo"})}, - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Run(cmd, []string{"type", "foo"}) - - expected := &internalType{Name: "foo"} - actual := tf.Printer.(*testPrinter).Objects[0] - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %#v", actual) - } - if buf.String() != fmt.Sprintf("%#v", expected) { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -// Verifies that schemas that are not in the master tree of Kubernetes can be retrieved via Get. -// Because api.List is part of the Kube API, resource.Builder has to perform a conversion on -// api.Scheme, which may not have access to all objects, and not all objects are at the same -// internal versioning scheme. This test verifies that two isolated schemes (Test, and api.Scheme) -// can be conjoined into a single output object. -// -// The expected behavior of the `kubectl get` command is: -// 1. objects using unrecognized schemes will always be returned using that scheme/version, "unlikelyversion" in this test; -// 2. if the specified output-version is a recognized, valid Scheme, then the list should use that scheme, and otherwise it will default to the client version, testapi.Default.GroupVersion().String() in this test; -// 3a. if the specified output-version is a recognized, valid Scheme, in which the requested object (replicationcontroller) can be represented, then the object should be returned using that version; -// 3b. otherwise if the specified output-version is unrecognized, but the requested object (replicationcontroller) is recognized by the client's codec, then it will be converted to the client version, testapi.Default.GroupVersion().String() in this test. -func TestGetUnknownSchemaObjectListGeneric(t *testing.T) { - testCases := map[string]struct { - outputVersion string - listVersion string - testtypeVersion string - rcVersion string - }{ - "handles specific version": { - outputVersion: testapi.Default.GroupVersion().String(), - listVersion: testapi.Default.GroupVersion().String(), - testtypeVersion: unlikelyGV.String(), - rcVersion: testapi.Default.GroupVersion().String(), - }, - "handles second specific version": { - outputVersion: "unlikely.group/unlikelyversion", - listVersion: testapi.Default.GroupVersion().String(), - testtypeVersion: unlikelyGV.String(), - rcVersion: testapi.Default.GroupVersion().String(), // see expected behavior 3b - }, - "handles common version": { - outputVersion: testapi.Default.GroupVersion().String(), - listVersion: testapi.Default.GroupVersion().String(), - testtypeVersion: unlikelyGV.String(), - rcVersion: testapi.Default.GroupVersion().String(), - }, - } - for k, test := range testCases { - apiCodec := testapi.Default.Codec() - regularClient := &fake.RESTClient{ - Codec: apiCodec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - return &http.Response{StatusCode: 200, Body: objBody(apiCodec, &api.ReplicationController{ObjectMeta: api.ObjectMeta{Name: "foo"}})}, nil - }), - } - - f, tf, codec := NewMixedFactory(regularClient) - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - return &http.Response{StatusCode: 200, Body: objBody(codec, &internalType{Name: "foo"})}, nil - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Flags().Set("output", "json") - - cmd.Flags().Set("output-version", test.outputVersion) - err := RunGet(f, buf, cmd, []string{"type/foo", "replicationcontrollers/foo"}, &GetOptions{}) - if err != nil { - t.Errorf("%s: unexpected error: %v", k, err) - continue - } - out := make(map[string]interface{}) - if err := encjson.Unmarshal(buf.Bytes(), &out); err != nil { - t.Errorf("%s: unexpected error: %v\n%s", k, err, buf.String()) - continue - } - if out["apiVersion"] != test.listVersion { - t.Errorf("%s: unexpected list: %#v", k, out) - } - arr := out["items"].([]interface{}) - if arr[0].(map[string]interface{})["apiVersion"] != test.testtypeVersion { - t.Errorf("%s: unexpected list: %#v", k, out) - } - if arr[1].(map[string]interface{})["apiVersion"] != test.rcVersion { - t.Errorf("%s: unexpected list: %#v", k, out) - } - } -} - -// Verifies that schemas that are not in the master tree of Kubernetes can be retrieved via Get. -func TestGetSchemaObject(t *testing.T) { - f, tf, _ := NewTestFactory() - tf.Mapper = testapi.Default.RESTMapper() - tf.Typer = api.Scheme - codec := testapi.Default.Codec() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, &api.ReplicationController{ObjectMeta: api.ObjectMeta{Name: "foo"}})}, - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: "v1"}}} - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.Run(cmd, []string{"replicationcontrollers", "foo"}) - - if !strings.Contains(buf.String(), "\"foo\"") { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestGetObjects(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Run(cmd, []string{"pods", "foo"}) - - expected := []runtime.Object{&pods.Items[0]} - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %#v", actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestGetObjectsIdentifiedByFile(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Flags().Set("filename", "../../../examples/cassandra/cassandra.yaml") - cmd.Run(cmd, []string{}) - - expected := []runtime.Object{&pods.Items[0]} - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %#v", actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestGetListObjects(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Run(cmd, []string{"pods"}) - - expected, err := extractResourceList([]runtime.Object{pods}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: expected %#v, got %#v", expected, actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func extractResourceList(objs []runtime.Object) ([]runtime.Object, error) { - finalObjs := []runtime.Object{} - for _, obj := range objs { - items, err := meta.ExtractList(obj) - if err != nil { - return nil, err - } - for _, item := range items { - finalObjs = append(finalObjs, item) - } - } - return finalObjs, nil -} - -func TestGetAllListObjects(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Flags().Set("show-all", "true") - cmd.Run(cmd, []string{"pods"}) - - expected, err := extractResourceList([]runtime.Object{pods}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %#v %#v", expected, actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestGetListComponentStatus(t *testing.T) { - statuses := testComponentStatusData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, statuses)}, - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Run(cmd, []string{"componentstatuses"}) - - expected, err := extractResourceList([]runtime.Object{statuses}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: expected %#v, got %#v", expected, actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestGetMultipleTypeObjects(t *testing.T) { - pods, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.URL.Path { - case "/namespaces/test/pods": - return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil - case "/namespaces/test/services": - return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Run(cmd, []string{"pods,services"}) - - expected, err := extractResourceList([]runtime.Object{pods, svc}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %#v", actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestGetMultipleTypeObjectsAsList(t *testing.T) { - pods, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.URL.Path { - case "/namespaces/test/pods": - return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil - case "/namespaces/test/services": - return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - - cmd.Flags().Set("output", "json") - cmd.Run(cmd, []string{"pods,services"}) - - if tf.Printer.(*testPrinter).Objects != nil { - t.Errorf("unexpected print to default printer") - } - - out, err := runtime.Decode(codec, buf.Bytes()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - list, err := meta.ExtractList(out) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if errs := runtime.DecodeList(list, codec); len(errs) > 0 { - t.Fatalf("unexpected error: %v", errs) - } - if err := meta.SetList(out, list); err != nil { - t.Fatalf("unexpected error: %v", err) - } - - expected := &api.List{ - Items: []runtime.Object{ - &pods.Items[0], - &pods.Items[1], - &svc.Items[0], - }, - } - if !reflect.DeepEqual(expected, out) { - t.Errorf("unexpected output: %#v", out) - } -} - -func TestGetMultipleTypeObjectsWithSelector(t *testing.T) { - pods, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - if req.URL.Query().Get(unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String())) != "a=b" { - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - } - switch req.URL.Path { - case "/namespaces/test/pods": - return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil - case "/namespaces/test/services": - return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - - cmd.Flags().Set("selector", "a=b") - cmd.Run(cmd, []string{"pods,services"}) - - expected, err := extractResourceList([]runtime.Object{pods, svc}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %#v", actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestGetMultipleTypeObjectsWithDirectReference(t *testing.T) { - _, svc, _ := testData() - node := &api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.NodeSpec{ - ExternalID: "ext", - }, - } - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.URL.Path { - case "/nodes/foo": - return &http.Response{StatusCode: 200, Body: objBody(codec, node)}, nil - case "/namespaces/test/services/bar": - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - - cmd.Run(cmd, []string{"services/bar", "node/foo"}) - - expected := []runtime.Object{&svc.Items[0], node} - actual := tf.Printer.(*testPrinter).Objects - if !api.Semantic.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %s", util.ObjectDiff(expected, actual)) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestGetByNameForcesFlag(t *testing.T) { - pods, _, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Resp: &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - cmd.Run(cmd, []string{"pods", "foo"}) - - showAllFlag, _ := cmd.Flags().GetBool("show-all") - if !showAllFlag { - t.Errorf("expected showAll to be true when getting resource by name") - } -} - -func watchTestData() ([]api.Pod, []watch.Event) { - pods := []api.Pod{ - { - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "test", - ResourceVersion: "10", - }, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - } - events := []watch.Event{ - { - Type: watch.Modified, - Object: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "test", - ResourceVersion: "11", - }, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - }, - { - Type: watch.Deleted, - Object: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Namespace: "test", - ResourceVersion: "12", - }, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - }, - } - return pods, events -} - -func TestWatchSelector(t *testing.T) { - pods, events := watchTestData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - if req.URL.Query().Get(unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String())) != "a=b" { - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - } - switch req.URL.Path { - case "/namespaces/test/pods": - return &http.Response{StatusCode: 200, Body: objBody(codec, &api.PodList{Items: pods})}, nil - case "/watch/namespaces/test/pods": - return &http.Response{StatusCode: 200, Body: watchBody(codec, events)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - - cmd.Flags().Set("watch", "true") - cmd.Flags().Set("selector", "a=b") - cmd.Run(cmd, []string{"pods"}) - - expected := []runtime.Object{&api.PodList{Items: pods}, events[0].Object, events[1].Object} - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object:\nExpected: %#v\n\nGot: %#v\n\n", expected[0], actual[0]) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestWatchResource(t *testing.T) { - pods, events := watchTestData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.URL.Path { - case "/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods[0])}, nil - case "/watch/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: watchBody(codec, events)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - - cmd.Flags().Set("watch", "true") - cmd.Run(cmd, []string{"pods", "foo"}) - - expected := []runtime.Object{&pods[0], events[0].Object, events[1].Object} - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object:\nExpected: %#v\n\nGot: %#v\n\n", expected, actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestWatchResourceIdentifiedByFile(t *testing.T) { - pods, events := watchTestData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.URL.Path { - case "/namespaces/test/pods/cassandra": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods[0])}, nil - case "/watch/namespaces/test/pods/cassandra": - return &http.Response{StatusCode: 200, Body: watchBody(codec, events)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - - cmd.Flags().Set("watch", "true") - cmd.Flags().Set("filename", "../../../examples/cassandra/cassandra.yaml") - cmd.Run(cmd, []string{}) - - expected := []runtime.Object{&pods[0], events[0].Object, events[1].Object} - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("expected object: %#v unexpected object: %#v", expected, actual) - } - - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func TestWatchOnlyResource(t *testing.T) { - pods, events := watchTestData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.URL.Path { - case "/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods[0])}, nil - case "/watch/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: watchBody(codec, events)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdGet(f, buf) - cmd.SetOutput(buf) - - cmd.Flags().Set("watch-only", "true") - cmd.Run(cmd, []string{"pods", "foo"}) - - expected := []runtime.Object{events[0].Object, events[1].Object} - actual := tf.Printer.(*testPrinter).Objects - if !reflect.DeepEqual(expected, actual) { - t.Errorf("unexpected object: %#v", actual) - } - if len(buf.String()) == 0 { - t.Errorf("unexpected empty output") - } -} - -func watchBody(codec runtime.Codec, events []watch.Event) io.ReadCloser { - buf := bytes.NewBuffer([]byte{}) - enc := json.NewEncoder(buf, codec) - for i := range events { - enc.Encode(&events[i]) - } - return ioutil.NopCloser(buf) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/label.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/label.go deleted file mode 100644 index 39c401d52..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/label.go +++ /dev/null @@ -1,297 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "encoding/json" - "fmt" - "io" - "reflect" - "strings" - - "github.com/golang/glog" - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - utilerrors "k8s.io/kubernetes/pkg/util/errors" - "k8s.io/kubernetes/pkg/util/strategicpatch" - "k8s.io/kubernetes/pkg/util/validation" -) - -// LabelOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type LabelOptions struct { - Filenames []string -} - -const ( - label_long = `Update the labels on a resource. - -A label must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters. -If --overwrite is true, then existing labels can be overwritten, otherwise attempting to overwrite a label will result in an error. -If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.` - label_example = `# Update pod 'foo' with the label 'unhealthy' and the value 'true'. -$ kubectl label pods foo unhealthy=true - -# Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value. -$ kubectl label --overwrite pods foo status=unhealthy - -# Update all pods in the namespace -$ kubectl label pods --all status=unhealthy - -# Update a pod identified by the type and name in "pod.json" -$ kubectl label -f pod.json status=unhealthy - -# Update pod 'foo' only if the resource is unchanged from version 1. -$ kubectl label pods foo status=unhealthy --resource-version=1 - -# Update pod 'foo' by removing a label named 'bar' if it exists. -# Does not require the --overwrite flag. -$ kubectl label pods foo bar-` -) - -func NewCmdLabel(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &LabelOptions{} - - // retrieve a list of handled resources from printer as valid args - validArgs := []string{} - p, err := f.Printer(nil, false, false, false, false, false, false, []string{}) - cmdutil.CheckErr(err) - if p != nil { - validArgs = p.HandledResources() - } - - cmd := &cobra.Command{ - Use: "label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]", - Short: "Update the labels on a resource", - Long: fmt.Sprintf(label_long, validation.LabelValueMaxLength), - Example: label_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunLabel(f, out, cmd, args, options) - cmdutil.CheckErr(err) - }, - ValidArgs: validArgs, - } - cmdutil.AddPrinterFlags(cmd) - cmd.Flags().Bool("overwrite", false, "If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing labels.") - cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on") - cmd.Flags().Bool("all", false, "select all resources in the namespace of the specified resource types") - cmd.Flags().String("resource-version", "", "If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.") - usage := "Filename, directory, or URL to a file identifying the resource to update the labels" - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without sending it.") - cmdutil.AddRecordFlag(cmd) - - return cmd -} - -func validateNoOverwrites(meta *api.ObjectMeta, labels map[string]string) error { - allErrs := []error{} - for key := range labels { - if value, found := meta.Labels[key]; found { - allErrs = append(allErrs, fmt.Errorf("'%s' already has a value (%s), and --overwrite is false", key, value)) - } - } - return utilerrors.NewAggregate(allErrs) -} - -func parseLabels(spec []string) (map[string]string, []string, error) { - labels := map[string]string{} - var remove []string - for _, labelSpec := range spec { - if strings.Index(labelSpec, "=") != -1 { - parts := strings.Split(labelSpec, "=") - if len(parts) != 2 || len(parts[1]) == 0 || !validation.IsValidLabelValue(parts[1]) { - return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec) - } - labels[parts[0]] = parts[1] - } else if strings.HasSuffix(labelSpec, "-") { - remove = append(remove, labelSpec[:len(labelSpec)-1]) - } else { - return nil, nil, fmt.Errorf("unknown label spec: %v", labelSpec) - } - } - for _, removeLabel := range remove { - if _, found := labels[removeLabel]; found { - return nil, nil, fmt.Errorf("can not both modify and remove a label in the same command") - } - } - return labels, remove, nil -} - -func labelFunc(obj runtime.Object, overwrite bool, resourceVersion string, labels map[string]string, remove []string) error { - meta, err := api.ObjectMetaFor(obj) - if err != nil { - return err - } - if !overwrite { - if err := validateNoOverwrites(meta, labels); err != nil { - return err - } - } - - if meta.Labels == nil { - meta.Labels = make(map[string]string) - } - - for key, value := range labels { - meta.Labels[key] = value - } - for _, label := range remove { - delete(meta.Labels, label) - } - - if len(resourceVersion) != 0 { - meta.ResourceVersion = resourceVersion - } - return nil -} - -func RunLabel(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *LabelOptions) error { - resources, labelArgs := []string{}, []string{} - first := true - for _, s := range args { - isLabel := strings.Contains(s, "=") || strings.HasSuffix(s, "-") - switch { - case first && isLabel: - first = false - fallthrough - case !first && isLabel: - labelArgs = append(labelArgs, s) - case first && !isLabel: - resources = append(resources, s) - case !first && !isLabel: - return cmdutil.UsageError(cmd, "all resources must be specified before label changes: %s", s) - } - } - if len(resources) < 1 && len(options.Filenames) == 0 { - return cmdutil.UsageError(cmd, "one or more resources must be specified as or /") - } - if len(labelArgs) < 1 { - return cmdutil.UsageError(cmd, "at least one label update is required") - } - - selector := cmdutil.GetFlagString(cmd, "selector") - all := cmdutil.GetFlagBool(cmd, "all") - overwrite := cmdutil.GetFlagBool(cmd, "overwrite") - resourceVersion := cmdutil.GetFlagString(cmd, "resource-version") - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - lbls, remove, err := parseLabels(labelArgs) - if err != nil { - return cmdutil.UsageError(cmd, err.Error()) - } - mapper, typer := f.Object() - b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - SelectorParam(selector). - ResourceTypeOrNameArgs(all, resources...). - Flatten(). - Latest() - - one := false - r := b.Do().IntoSingular(&one) - if err := r.Err(); err != nil { - return err - } - - // only apply resource version locking on a single resource - if !one && len(resourceVersion) > 0 { - return cmdutil.UsageError(cmd, "--resource-version may only be used with a single resource") - } - - // TODO: support bulk generic output a la Get - return r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - - var outputObj runtime.Object - dataChangeMsg := "not labeled" - if cmdutil.GetFlagBool(cmd, "dry-run") { - err = labelFunc(info.Object, overwrite, resourceVersion, lbls, remove) - if err != nil { - return err - } - outputObj = info.Object - } else { - name, namespace, obj := info.Name, info.Namespace, info.Object - oldData, err := json.Marshal(obj) - if err != nil { - return err - } - meta, err := api.ObjectMetaFor(obj) - for _, label := range remove { - if _, ok := meta.Labels[label]; !ok { - fmt.Fprintf(out, "label %q not found.\n", label) - } - } - - if err := labelFunc(obj, overwrite, resourceVersion, lbls, remove); err != nil { - return err - } - if cmdutil.ShouldRecord(cmd, info) { - if err := cmdutil.RecordChangeCause(obj, f.Command()); err != nil { - return err - } - } - newData, err := json.Marshal(obj) - if err != nil { - return err - } - if !reflect.DeepEqual(oldData, newData) { - dataChangeMsg = "labeled" - } - patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj) - createdPatch := err == nil - if err != nil { - glog.V(2).Infof("couldn't compute patch: %v", err) - } - - mapping := info.ResourceMapping() - client, err := f.ClientForMapping(mapping) - if err != nil { - return err - } - helper := resource.NewHelper(client, mapping) - - if createdPatch { - outputObj, err = helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes) - } else { - outputObj, err = helper.Replace(namespace, name, false, obj) - } - if err != nil { - return err - } - } - outputFormat := cmdutil.GetFlagString(cmd, "output") - if outputFormat != "" { - return f.PrintObject(cmd, outputObj, out) - } - cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, dataChangeMsg) - return nil - }) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/label_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/label_test.go deleted file mode 100644 index 5267bc3cc..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/label_test.go +++ /dev/null @@ -1,418 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestValidateLabels(t *testing.T) { - tests := []struct { - meta *api.ObjectMeta - labels map[string]string - expectErr bool - test string - }{ - { - meta: &api.ObjectMeta{ - Labels: map[string]string{ - "a": "b", - "c": "d", - }, - }, - labels: map[string]string{ - "a": "c", - "d": "b", - }, - test: "one shared", - expectErr: true, - }, - { - meta: &api.ObjectMeta{ - Labels: map[string]string{ - "a": "b", - "c": "d", - }, - }, - labels: map[string]string{ - "b": "d", - "c": "a", - }, - test: "second shared", - expectErr: true, - }, - { - meta: &api.ObjectMeta{ - Labels: map[string]string{ - "a": "b", - "c": "d", - }, - }, - labels: map[string]string{ - "b": "a", - "d": "c", - }, - test: "no overlap", - }, - { - meta: &api.ObjectMeta{}, - labels: map[string]string{ - "b": "a", - "d": "c", - }, - test: "no labels", - }, - } - for _, test := range tests { - err := validateNoOverwrites(test.meta, test.labels) - if test.expectErr && err == nil { - t.Errorf("%s: unexpected non-error", test.test) - } - if !test.expectErr && err != nil { - t.Errorf("%s: unexpected error: %v", test.test, err) - } - } -} - -func TestParseLabels(t *testing.T) { - tests := []struct { - labels []string - expected map[string]string - expectedRemove []string - expectErr bool - }{ - { - labels: []string{"a=b", "c=d"}, - expected: map[string]string{"a": "b", "c": "d"}, - }, - { - labels: []string{}, - expected: map[string]string{}, - }, - { - labels: []string{"a=b", "c=d", "e-"}, - expected: map[string]string{"a": "b", "c": "d"}, - expectedRemove: []string{"e"}, - }, - { - labels: []string{"ab", "c=d"}, - expectErr: true, - }, - { - labels: []string{"a=b", "c=d", "a-"}, - expectErr: true, - }, - { - labels: []string{"a="}, - expectErr: true, - }, - { - labels: []string{"a=%^$"}, - expectErr: true, - }, - } - for _, test := range tests { - labels, remove, err := parseLabels(test.labels) - if test.expectErr && err == nil { - t.Errorf("unexpected non-error: %v", test) - } - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v %v", err, test) - } - if !reflect.DeepEqual(labels, test.expected) { - t.Errorf("expected: %v, got %v", test.expected, labels) - } - if !reflect.DeepEqual(remove, test.expectedRemove) { - t.Errorf("expected: %v, got %v", test.expectedRemove, remove) - } - } -} - -func TestLabelFunc(t *testing.T) { - tests := []struct { - obj runtime.Object - overwrite bool - version string - labels map[string]string - remove []string - expected runtime.Object - expectErr bool - }{ - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b"}, - }, - }, - labels: map[string]string{"a": "b"}, - expectErr: true, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b"}, - }, - }, - labels: map[string]string{"a": "c"}, - overwrite: true, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "c"}, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b"}, - }, - }, - labels: map[string]string{"c": "d"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b", "c": "d"}, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b"}, - }, - }, - labels: map[string]string{"c": "d"}, - version: "2", - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b", "c": "d"}, - ResourceVersion: "2", - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b"}, - }, - }, - labels: map[string]string{}, - remove: []string{"a"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{}, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b", "c": "d"}, - }, - }, - labels: map[string]string{"e": "f"}, - remove: []string{"a"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "c": "d", - "e": "f", - }, - }, - }, - }, - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{}, - }, - labels: map[string]string{"a": "b"}, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"a": "b"}, - }, - }, - }, - } - for _, test := range tests { - err := labelFunc(test.obj, test.overwrite, test.version, test.labels, test.remove) - if test.expectErr { - if err == nil { - t.Errorf("unexpected non-error: %v", test) - } - continue - } - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v %v", err, test) - } - if !reflect.DeepEqual(test.obj, test.expected) { - t.Errorf("expected: %v, got %v", test.expected, test.obj) - } - } -} - -func TestLabelErrors(t *testing.T) { - testCases := map[string]struct { - args []string - flags map[string]string - errFn func(error) bool - }{ - "no args": { - args: []string{}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") }, - }, - "not enough labels": { - args: []string{"pods"}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "at least one label update is required") }, - }, - "no resources": { - args: []string{"pods-"}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") }, - }, - "no resources 2": { - args: []string{"pods=bar"}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "one or more resources must be specified") }, - }, - } - - for k, testCase := range testCases { - f, tf, _ := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdLabel(f, buf) - cmd.SetOutput(buf) - - for k, v := range testCase.flags { - cmd.Flags().Set(k, v) - } - err := RunLabel(f, buf, cmd, testCase.args, &LabelOptions{}) - if !testCase.errFn(err) { - t.Errorf("%s: unexpected error: %v", k, err) - continue - } - if tf.Printer.(*testPrinter).Objects != nil { - t.Errorf("unexpected print to default printer") - } - if buf.Len() > 0 { - t.Errorf("buffer should be empty: %s", string(buf.Bytes())) - } - } -} - -func TestLabelForResourceFromFile(t *testing.T) { - pods, _, _ := testData() - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.Method { - case "GET": - switch req.URL.Path { - case "/namespaces/test/pods/cassandra": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - case "PATCH": - switch req.URL.Path { - case "/namespaces/test/pods/cassandra": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - default: - t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdLabel(f, buf) - options := &LabelOptions{ - Filenames: []string{"../../../examples/cassandra/cassandra.yaml"}, - } - - err := RunLabel(f, buf, cmd, []string{"a=b"}, options) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !strings.Contains(buf.String(), "labeled") { - t.Errorf("did not set labels: %s", buf.String()) - } -} - -func TestLabelMultipleObjects(t *testing.T) { - pods, _, _ := testData() - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch req.Method { - case "GET": - switch req.URL.Path { - case "/namespaces/test/pods": - return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - case "PATCH": - switch req.URL.Path { - case "/namespaces/test/pods/foo": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil - case "/namespaces/test/pods/bar": - return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[1])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - default: - t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - - buf := bytes.NewBuffer([]byte{}) - cmd := NewCmdLabel(f, buf) - cmd.Flags().Set("all", "true") - - if err := RunLabel(f, buf, cmd, []string{"pods", "a=b"}, &LabelOptions{}); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if strings.Count(buf.String(), "labeled") != len(pods.Items) { - t.Errorf("not all labels are set: %s", buf.String()) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/logs.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/logs.go deleted file mode 100644 index 369d41d8a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/logs.go +++ /dev/null @@ -1,206 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "errors" - "io" - "math" - "os" - "time" - - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/validation" - client "k8s.io/kubernetes/pkg/client/unversioned" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" -) - -const ( - logs_example = `# Return snapshot logs from pod nginx with only one container -$ kubectl logs nginx - -# Return snapshot of previous terminated ruby container logs from pod web-1 -$ kubectl logs -p -c ruby web-1 - -# Begin streaming the logs of the ruby container in pod web-1 -$ kubectl logs -f -c ruby web-1 - -# Display only the most recent 20 lines of output in pod nginx -$ kubectl logs --tail=20 nginx - -# Show all logs from pod nginx written in the last hour -$ kubectl logs --since=1h nginx` -) - -type LogsOptions struct { - Namespace string - ResourceArg string - Options runtime.Object - - Mapper meta.RESTMapper - Typer runtime.ObjectTyper - ClientMapper resource.ClientMapper - Decoder runtime.Decoder - - LogsForObject func(object, options runtime.Object) (*client.Request, error) - - Out io.Writer -} - -// NewCmdLog creates a new pod logs command -func NewCmdLogs(f *cmdutil.Factory, out io.Writer) *cobra.Command { - o := &LogsOptions{} - cmd := &cobra.Command{ - Use: "logs [-f] [-p] POD [-c CONTAINER]", - Short: "Print the logs for a container in a pod.", - Long: "Print the logs for a container in a pod. If the pod has only one container, the container name is optional.", - Example: logs_example, - PreRun: func(cmd *cobra.Command, args []string) { - if len(os.Args) > 1 && os.Args[1] == "log" { - printDeprecationWarning("logs", "log") - } - }, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(o.Complete(f, out, cmd, args)) - if err := o.Validate(); err != nil { - cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error())) - } - _, err := o.RunLogs() - cmdutil.CheckErr(err) - }, - Aliases: []string{"log"}, - } - cmd.Flags().BoolP("follow", "f", false, "Specify if the logs should be streamed.") - cmd.Flags().Bool("timestamps", false, "Include timestamps on each line in the log output") - cmd.Flags().Int64("limit-bytes", 0, "Maximum bytes of logs to return. Defaults to no limit.") - cmd.Flags().BoolP("previous", "p", false, "If true, print the logs for the previous instance of the container in a pod if it exists.") - cmd.Flags().Int64("tail", -1, "Lines of recent log file to display. Defaults to -1, showing all log lines.") - cmd.Flags().String("since-time", "", "Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used.") - cmd.Flags().Duration("since", 0, "Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of since-time / since may be used.") - cmd.Flags().StringP("container", "c", "", "Print the logs of this container") - - cmd.Flags().Bool("interactive", false, "If true, prompt the user for input when required.") - cmd.Flags().MarkDeprecated("interactive", "This flag is no longer respected and there is no replacement.") - return cmd -} - -func (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error { - containerName := cmdutil.GetFlagString(cmd, "container") - switch len(args) { - case 0: - return cmdutil.UsageError(cmd, "POD is required for logs") - case 1: - o.ResourceArg = args[0] - case 2: - if cmd.Flag("container").Changed { - return cmdutil.UsageError(cmd, "only one of -c, [CONTAINER] arg is allowed") - } - o.ResourceArg = args[0] - containerName = args[1] - default: - return cmdutil.UsageError(cmd, "logs POD [-c CONTAINER]") - } - var err error - o.Namespace, _, err = f.DefaultNamespace() - if err != nil { - return err - } - - logOptions := &api.PodLogOptions{ - Container: containerName, - Follow: cmdutil.GetFlagBool(cmd, "follow"), - Previous: cmdutil.GetFlagBool(cmd, "previous"), - Timestamps: cmdutil.GetFlagBool(cmd, "timestamps"), - } - if sinceTime := cmdutil.GetFlagString(cmd, "since-time"); len(sinceTime) > 0 { - t, err := api.ParseRFC3339(sinceTime, unversioned.Now) - if err != nil { - return err - } - logOptions.SinceTime = &t - } - if limit := cmdutil.GetFlagInt64(cmd, "limit-bytes"); limit != 0 { - logOptions.LimitBytes = &limit - } - if tail := cmdutil.GetFlagInt64(cmd, "tail"); tail != -1 { - logOptions.TailLines = &tail - } - if sinceSeconds := cmdutil.GetFlagDuration(cmd, "since"); sinceSeconds != 0 { - // round up to the nearest second - sec := int64(math.Ceil(float64(sinceSeconds) / float64(time.Second))) - logOptions.SinceSeconds = &sec - } - o.Options = logOptions - - o.Mapper, o.Typer = f.Object() - o.Decoder = f.Decoder(true) - o.ClientMapper = resource.ClientMapperFunc(f.ClientForMapping) - o.LogsForObject = f.LogsForObject - - o.Out = out - - return nil -} - -func (o LogsOptions) Validate() error { - if len(o.ResourceArg) == 0 { - return errors.New("a pod must be specified") - } - logsOptions, ok := o.Options.(*api.PodLogOptions) - if !ok { - return errors.New("unexpected logs options object") - } - if errs := validation.ValidatePodLogOptions(logsOptions); len(errs) > 0 { - return errs.ToAggregate() - } - - return nil -} - -// RunLogs retrieves a pod log -func (o LogsOptions) RunLogs() (int64, error) { - infos, err := resource.NewBuilder(o.Mapper, o.Typer, o.ClientMapper, o.Decoder). - NamespaceParam(o.Namespace).DefaultNamespace(). - ResourceNames("pods", o.ResourceArg). - SingleResourceType(). - Do().Infos() - if err != nil { - return 0, err - } - if len(infos) != 1 { - return 0, errors.New("expected a resource") - } - info := infos[0] - - req, err := o.LogsForObject(info.Object, o.Options) - if err != nil { - return 0, err - } - - readCloser, err := req.Stream() - if err != nil { - return 0, err - } - defer readCloser.Close() - - return io.Copy(o.Out, readCloser) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/logs_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/logs_test.go deleted file mode 100644 index caa867031..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/logs_test.go +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "io/ioutil" - "net/http" - "os" - "strings" - "testing" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func TestLog(t *testing.T) { - tests := []struct { - name, version, podPath, logPath, container string - pod *api.Pod - }{ - { - name: "v1 - pod log", - version: "v1", - podPath: "/namespaces/test/pods/foo", - logPath: "/api/v1/namespaces/test/pods/foo/log", - pod: testPod(), - }, - } - for _, test := range tests { - logContent := "test log content" - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == test.podPath && m == "GET": - body := objBody(codec, test.pod) - return &http.Response{StatusCode: 200, Body: body}, nil - case p == test.logPath && m == "GET": - body := ioutil.NopCloser(bytes.NewBufferString(logContent)) - return &http.Response{StatusCode: 200, Body: body}, nil - default: - // Ensures no GET is performed when deleting by name - t.Errorf("%s: unexpected request: %#v\n%#v", test.name, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}} - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdLogs(f, buf) - cmd.Flags().Set("namespace", "test") - cmd.Run(cmd, []string{"foo"}) - - if buf.String() != logContent { - t.Errorf("%s: did not get expected log content. Got: %s", test.name, buf.String()) - } - } -} - -func testPod() *api.Pod { - return &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"}, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - Containers: []api.Container{ - { - Name: "bar", - }, - }, - }, - } -} - -func TestValidateLogFlags(t *testing.T) { - f, _, _ := NewAPIFactory() - - tests := []struct { - name string - flags map[string]string - expected string - }{ - { - name: "since & since-time", - flags: map[string]string{"since": "1h", "since-time": "2006-01-02T15:04:05Z"}, - expected: "at most one of `sinceTime` or `sinceSeconds` may be specified", - }, - { - name: "negative limit-bytes", - flags: map[string]string{"limit-bytes": "-100"}, - expected: "must be greater than 0", - }, - { - name: "negative tail", - flags: map[string]string{"tail": "-100"}, - expected: "must be greater than or equal to 0", - }, - } - for _, test := range tests { - cmd := NewCmdLogs(f, bytes.NewBuffer([]byte{})) - out := "" - for flag, value := range test.flags { - cmd.Flags().Set(flag, value) - } - // checkErr breaks tests in case of errors, plus we just - // need to check errors returned by the command validation - o := &LogsOptions{} - cmd.Run = func(cmd *cobra.Command, args []string) { - o.Complete(f, os.Stdout, cmd, args) - out = o.Validate().Error() - o.RunLogs() - } - cmd.Run(cmd, []string{"foo"}) - - if !strings.Contains(out, test.expected) { - t.Errorf("%s: expected to find:\n\t%s\nfound:\n\t%s\n", test.name, test.expected, out) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/namespace.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/namespace.go deleted file mode 100644 index e50e4c078..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/namespace.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -// TODO remove once people have been given enough time to notice -func NewCmdNamespace(out io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "namespace [namespace]", - Short: "SUPERSEDED: Set and view the current Kubernetes namespace", - Long: `SUPERSEDED: Set and view the current Kubernetes namespace scope for command line requests. - -namespace has been superseded by the context.namespace field of .kubeconfig files. See 'kubectl config set-context --help' for more details. -`, - Run: func(cmd *cobra.Command, args []string) { - util.CheckErr(fmt.Errorf("namespace has been superseded by the context.namespace field of .kubeconfig files. See 'kubectl config set-context --help' for more details.")) - }, - } - return cmd -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/patch.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/patch.go deleted file mode 100644 index 5b0b6b8d3..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/patch.go +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "strings" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/util/sets" - "k8s.io/kubernetes/pkg/util/yaml" -) - -var patchTypes = map[string]api.PatchType{"json": api.JSONPatchType, "merge": api.MergePatchType, "strategic": api.StrategicMergePatchType} - -// PatchOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type PatchOptions struct { - Filenames []string -} - -const ( - patch_long = `Update field(s) of a resource using strategic merge patch - -JSON and YAML formats are accepted. - -Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.` - patch_example = ` -# Partially update a node using strategic merge patch -kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' - -# Partially update a node identified by the type and name specified in "node.json" using strategic merge patch -kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}' - -# Update a container's image; spec.containers[*].name is required because it's a merge key -kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}' - -# Update a container's image using a json patch with positional arrays -kubectl patch pod valid-pod -type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'` -) - -func NewCmdPatch(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &PatchOptions{} - - cmd := &cobra.Command{ - Use: "patch (-f FILENAME | TYPE NAME) -p PATCH", - Short: "Update field(s) of a resource using strategic merge patch.", - Long: patch_long, - Example: patch_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) - shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" - err := RunPatch(f, out, cmd, args, shortOutput, options) - cmdutil.CheckErr(err) - }, - } - cmd.Flags().StringP("patch", "p", "", "The patch to be applied to the resource JSON file.") - cmd.MarkFlagRequired("patch") - cmd.Flags().String("type", "strategic", fmt.Sprintf("The type of patch being provided; one of %v", sets.StringKeySet(patchTypes).List())) - cmdutil.AddOutputFlagsForMutation(cmd) - cmdutil.AddRecordFlag(cmd) - - usage := "Filename, directory, or URL to a file identifying the resource to update" - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - return cmd -} - -func RunPatch(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *PatchOptions) error { - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - patchType := api.StrategicMergePatchType - patchTypeString := strings.ToLower(cmdutil.GetFlagString(cmd, "type")) - if len(patchTypeString) != 0 { - ok := false - patchType, ok = patchTypes[patchTypeString] - if !ok { - return cmdutil.UsageError(cmd, fmt.Sprintf("--type must be one of %v, not %q", sets.StringKeySet(patchTypes).List(), patchTypeString)) - } - } - - patch := cmdutil.GetFlagString(cmd, "patch") - if len(patch) == 0 { - return cmdutil.UsageError(cmd, "Must specify -p to patch") - } - patchBytes, err := yaml.ToJSON([]byte(patch)) - if err != nil { - return fmt.Errorf("unable to parse %q: %v", patch, err) - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - ResourceTypeOrNameArgs(false, args...). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - infos, err := r.Infos() - if err != nil { - return err - } - if len(infos) > 1 { - return fmt.Errorf("multiple resources provided") - } - info := infos[0] - name, namespace := info.Name, info.Namespace - mapping := info.ResourceMapping() - client, err := f.ClientForMapping(mapping) - if err != nil { - return err - } - - helper := resource.NewHelper(client, mapping) - patchedObject, err := helper.Patch(namespace, name, patchType, patchBytes) - if err != nil { - return err - } - if cmdutil.ShouldRecord(cmd, info) { - if err := cmdutil.RecordChangeCause(patchedObject, f.Command()); err == nil { - // don't return an error on failure. The patch itself succeeded, its only the hint for that change that failed - // don't bother checking for failures of this replace, because a failure to indicate the hint doesn't fail the command - // also, don't force the replacement. If the replacement fails on a resourceVersion conflict, then it means this - // record hint is likely to be invalid anyway, so avoid the bad hint - resource.NewHelper(client, mapping).Replace(namespace, name, false, patchedObject) - } - } - cmdutil.PrintSuccess(mapper, shortOutput, out, "", name, "patched") - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/patch_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/patch_test.go deleted file mode 100644 index fd22dcaf4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/patch_test.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "testing" - - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func TestPatchObject(t *testing.T) { - _, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/services/frontend" && (m == "PATCH" || m == "GET"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdPatch(f, buf) - cmd.Flags().Set("namespace", "test") - cmd.Flags().Set("patch", `{"spec":{"type":"NodePort"}}`) - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{"services/frontend"}) - - // uses the name from the file, not the response - if buf.String() != "frontend\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestPatchObjectFromFile(t *testing.T) { - _, svc, _ := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/services/frontend" && (m == "PATCH" || m == "GET"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdPatch(f, buf) - cmd.Flags().Set("namespace", "test") - cmd.Flags().Set("patch", `{"spec":{"type":"NodePort"}}`) - cmd.Flags().Set("output", "name") - cmd.Flags().Set("filename", "../../../examples/guestbook/frontend-service.yaml") - cmd.Run(cmd, []string{}) - - // uses the name from the file, not the response - if buf.String() != "frontend\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/portforward.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/portforward.go deleted file mode 100644 index 942a1c500..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/portforward.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "net/url" - "os" - "os/signal" - - "github.com/golang/glog" - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/portforward" - "k8s.io/kubernetes/pkg/client/unversioned/remotecommand" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -const ( - portforward_example = ` -# Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod -$ kubectl port-forward mypod 5000 6000 - -# Listen on port 8888 locally, forwarding to 5000 in the pod -$ kubectl port-forward mypod 8888:5000 - -# Listen on a random port locally, forwarding to 5000 in the pod -$ kubectl port-forward mypod :5000 - -# Listen on a random port locally, forwarding to 5000 in the pod -$ kubectl port-forward mypod 0:5000` -) - -func NewCmdPortForward(f *cmdutil.Factory) *cobra.Command { - cmd := &cobra.Command{ - Use: "port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]", - Short: "Forward one or more local ports to a pod.", - Long: "Forward one or more local ports to a pod.", - Example: portforward_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunPortForward(f, cmd, args, &defaultPortForwarder{}) - cmdutil.CheckErr(err) - }, - } - cmd.Flags().StringP("pod", "p", "", "Pod name") - // TODO support UID - return cmd -} - -type portForwarder interface { - ForwardPorts(method string, url *url.URL, config *client.Config, ports []string, stopChan <-chan struct{}) error -} - -type defaultPortForwarder struct{} - -func (*defaultPortForwarder) ForwardPorts(method string, url *url.URL, config *client.Config, ports []string, stopChan <-chan struct{}) error { - dialer, err := remotecommand.NewExecutor(config, method, url) - if err != nil { - return err - } - fw, err := portforward.New(dialer, ports, stopChan) - if err != nil { - return err - } - return fw.ForwardPorts() -} - -func RunPortForward(f *cmdutil.Factory, cmd *cobra.Command, args []string, fw portForwarder) error { - podName := cmdutil.GetFlagString(cmd, "pod") - if len(podName) == 0 && len(args) == 0 { - return cmdutil.UsageError(cmd, "POD is required for port-forward") - } - - if len(podName) != 0 { - printDeprecationWarning("port-forward POD", "-p POD") - } else { - podName = args[0] - args = args[1:] - } - - if len(args) < 1 { - return cmdutil.UsageError(cmd, "at least 1 PORT is required for port-forward") - } - - namespace, _, err := f.DefaultNamespace() - if err != nil { - return err - } - - client, err := f.Client() - if err != nil { - return err - } - - pod, err := client.Pods(namespace).Get(podName) - if err != nil { - return err - } - - if pod.Status.Phase != api.PodRunning { - glog.Fatalf("Unable to execute command because pod is not running. Current status=%v", pod.Status.Phase) - } - - config, err := f.ClientConfig() - if err != nil { - return err - } - - signals := make(chan os.Signal, 1) - signal.Notify(signals, os.Interrupt) - defer signal.Stop(signals) - - stopCh := make(chan struct{}, 1) - go func() { - <-signals - close(stopCh) - }() - - req := client.RESTClient.Post(). - Resource("pods"). - Namespace(namespace). - Name(pod.Name). - SubResource("portforward") - - return fw.ForwardPorts("POST", req.URL(), config, args, stopCh) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/portforward_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/portforward_test.go deleted file mode 100644 index eebda28b8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/portforward_test.go +++ /dev/null @@ -1,176 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "net/http" - "net/url" - "testing" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -type fakePortForwarder struct { - method string - url *url.URL - pfErr error -} - -func (f *fakePortForwarder) ForwardPorts(method string, url *url.URL, config *client.Config, ports []string, stopChan <-chan struct{}) error { - f.method = method - f.url = url - return f.pfErr -} - -func TestPortForward(t *testing.T) { - version := testapi.Default.GroupVersion().Version - - tests := []struct { - name, version, podPath, pfPath, container string - pod *api.Pod - pfErr bool - }{ - { - name: "pod portforward", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - pfPath: "/api/" + version + "/namespaces/test/pods/foo/portforward", - pod: execPod(), - }, - { - name: "pod portforward error", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - pfPath: "/api/" + version + "/namespaces/test/pods/foo/portforward", - pod: execPod(), - pfErr: true, - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == test.podPath && m == "GET": - body := objBody(codec, test.pod) - return &http.Response{StatusCode: 200, Body: body}, nil - default: - // Ensures no GET is performed when deleting by name - t.Errorf("%s: unexpected request: %#v\n%#v", test.name, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}} - ff := &fakePortForwarder{} - if test.pfErr { - ff.pfErr = fmt.Errorf("pf error") - } - cmd := &cobra.Command{} - cmd.Flags().StringP("pod", "p", "", "Pod name") - err := RunPortForward(f, cmd, []string{"foo", ":5000", ":1000"}, ff) - - if test.pfErr && err != ff.pfErr { - t.Errorf("%s: Unexpected exec error: %v", test.name, err) - } - if !test.pfErr && err != nil { - t.Errorf("%s: Unexpected error: %v", test.name, err) - } - if test.pfErr { - continue - } - - if ff.url.Path != test.pfPath { - t.Errorf("%s: Did not get expected path for portforward request", test.name) - } - if ff.method != "POST" { - t.Errorf("%s: Did not get method for attach request: %s", test.name, ff.method) - } - - } -} - -func TestPortForwardWithPFlag(t *testing.T) { - version := testapi.Default.GroupVersion().Version - - tests := []struct { - name, version, podPath, pfPath, container string - pod *api.Pod - pfErr bool - }{ - { - name: "pod portforward", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - pfPath: "/api/" + version + "/namespaces/test/pods/foo/portforward", - pod: execPod(), - }, - { - name: "pod portforward error", - version: version, - podPath: "/api/" + version + "/namespaces/test/pods/foo", - pfPath: "/api/" + version + "/namespaces/test/pods/foo/portforward", - pod: execPod(), - pfErr: true, - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == test.podPath && m == "GET": - body := objBody(codec, test.pod) - return &http.Response{StatusCode: 200, Body: body}, nil - default: - // Ensures no GET is performed when deleting by name - t.Errorf("%s: unexpected request: %#v\n%#v", test.name, req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}} - ff := &fakePortForwarder{} - if test.pfErr { - ff.pfErr = fmt.Errorf("pf error") - } - cmd := &cobra.Command{} - podPtr := cmd.Flags().StringP("pod", "p", "", "Pod name") - *podPtr = "foo" - err := RunPortForward(f, cmd, []string{":5000", ":1000"}, ff) - if test.pfErr && err != ff.pfErr { - t.Errorf("%s: Unexpected exec error: %v", test.name, err) - } - if !test.pfErr && ff.url.Path != test.pfPath { - t.Errorf("%s: Did not get expected path for portforward request", test.name) - } - if !test.pfErr && err != nil { - t.Errorf("%s: Unexpected error: %v", test.name, err) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/proxy.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/proxy.go deleted file mode 100644 index 130e2ae59..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/proxy.go +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "errors" - "fmt" - "io" - "net" - "strings" - - "github.com/golang/glog" - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -const ( - default_port = 8001 - proxy_example = `# Run a proxy to kubernetes apiserver on port 8011, serving static content from ./local/www/ -$ kubectl proxy --port=8011 --www=./local/www/ - -# Run a proxy to kubernetes apiserver on an arbitrary local port. -# The chosen port for the server will be output to stdout. -$ kubectl proxy --port=0 - -# Run a proxy to kubernetes apiserver, changing the api prefix to k8s-api -# This makes e.g. the pods api available at localhost:8011/k8s-api/v1/pods/ -$ kubectl proxy --api-prefix=/k8s-api` -) - -func NewCmdProxy(f *cmdutil.Factory, out io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix]", - Short: "Run a proxy to the Kubernetes API server", - Long: `To proxy all of the kubernetes api and nothing else, use: - -kubectl proxy --api-prefix=/ - -To proxy only part of the kubernetes api and also some static files: - -kubectl proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/ - -The above lets you 'curl localhost:8001/api/v1/pods'. - -To proxy the entire kubernetes api at a different root, use: - -kubectl proxy --api-prefix=/custom/ - -The above lets you 'curl localhost:8001/custom/api/v1/pods' -`, - Example: proxy_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunProxy(f, out, cmd) - cmdutil.CheckErr(err) - }, - } - cmd.Flags().StringP("www", "w", "", "Also serve static files from the given directory under the specified prefix.") - cmd.Flags().StringP("www-prefix", "P", "/static/", "Prefix to serve static files under, if static file directory is specified.") - cmd.Flags().StringP("api-prefix", "", "/", "Prefix to serve the proxied API under.") - cmd.Flags().String("accept-paths", kubectl.DefaultPathAcceptRE, "Regular expression for paths that the proxy should accept.") - cmd.Flags().String("reject-paths", kubectl.DefaultPathRejectRE, "Regular expression for paths that the proxy should reject.") - cmd.Flags().String("accept-hosts", kubectl.DefaultHostAcceptRE, "Regular expression for hosts that the proxy should accept.") - cmd.Flags().String("reject-methods", kubectl.DefaultMethodRejectRE, "Regular expression for HTTP methods that the proxy should reject.") - cmd.Flags().IntP("port", "p", default_port, "The port on which to run the proxy. Set to 0 to pick a random port.") - cmd.Flags().StringP("address", "", "127.0.0.1", "The IP address on which to serve on.") - cmd.Flags().Bool("disable-filter", false, "If true, disable request filtering in the proxy. This is dangerous, and can leave you vulnerable to XSRF attacks, when used with an accessible port.") - cmd.Flags().StringP("unix-socket", "u", "", "Unix socket on which to run the proxy.") - return cmd -} - -func RunProxy(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { - path := cmdutil.GetFlagString(cmd, "unix-socket") - port := cmdutil.GetFlagInt(cmd, "port") - address := cmdutil.GetFlagString(cmd, "address") - - if port != default_port && path != "" { - return errors.New("Don't specify both --unix-socket and --port") - } - - clientConfig, err := f.ClientConfig() - if err != nil { - return err - } - - staticPrefix := cmdutil.GetFlagString(cmd, "www-prefix") - if !strings.HasSuffix(staticPrefix, "/") { - staticPrefix += "/" - } - - apiProxyPrefix := cmdutil.GetFlagString(cmd, "api-prefix") - if !strings.HasSuffix(apiProxyPrefix, "/") { - apiProxyPrefix += "/" - } - filter := &kubectl.FilterServer{ - AcceptPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-paths")), - RejectPaths: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "reject-paths")), - AcceptHosts: kubectl.MakeRegexpArrayOrDie(cmdutil.GetFlagString(cmd, "accept-hosts")), - } - if cmdutil.GetFlagBool(cmd, "disable-filter") { - if path == "" { - glog.Warning("Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious") - } - filter = nil - } - - server, err := kubectl.NewProxyServer(cmdutil.GetFlagString(cmd, "www"), apiProxyPrefix, staticPrefix, filter, clientConfig) - - // Separate listening from serving so we can report the bound port - // when it is chosen by os (eg: port == 0) - var l net.Listener - if path == "" { - l, err = server.Listen(address, port) - } else { - l, err = server.ListenUnix(path) - } - if err != nil { - glog.Fatal(err) - } - fmt.Fprintf(out, "Starting to serve on %s", l.Addr().String()) - glog.Fatal(server.ServeOnListener(l)) - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/replace.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/replace.go deleted file mode 100644 index 81eacecbd..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/replace.go +++ /dev/null @@ -1,254 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - - "github.com/spf13/cobra" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" -) - -// ReplaceOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type ReplaceOptions struct { - Filenames []string -} - -const ( - replace_long = `Replace a resource by filename or stdin. - -JSON and YAML formats are accepted. If replacing an existing resource, the -complete resource spec must be provided. This can be obtained by -$ kubectl get TYPE NAME -o yaml - -Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.` - replace_example = `# Replace a pod using the data in pod.json. -$ kubectl replace -f ./pod.json - -# Replace a pod based on the JSON passed into stdin. -$ cat pod.json | kubectl replace -f - - -# Update a single-container pod's image version (tag) to v4 -kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - - -# Force replace, delete and then re-create the resource -kubectl replace --force -f ./pod.json` -) - -func NewCmdReplace(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &ReplaceOptions{} - - cmd := &cobra.Command{ - Use: "replace -f FILENAME", - // update is deprecated. - Aliases: []string{"update"}, - Short: "Replace a resource by filename or stdin.", - Long: replace_long, - Example: replace_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) - err := RunReplace(f, out, cmd, args, options) - cmdutil.CheckErr(err) - }, - } - usage := "Filename, directory, or URL to file to use to replace the resource." - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.MarkFlagRequired("filename") - cmd.Flags().Bool("force", false, "Delete and re-create the specified resource") - cmd.Flags().Bool("cascade", false, "Only relevant during a force replace. If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController).") - cmd.Flags().Int("grace-period", -1, "Only relevant during a force replace. Period of time in seconds given to the old resource to terminate gracefully. Ignored if negative.") - cmd.Flags().Duration("timeout", 0, "Only relevant during a force replace. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object") - cmdutil.AddValidateFlags(cmd) - cmdutil.AddOutputFlagsForMutation(cmd) - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddRecordFlag(cmd) - return cmd -} - -func RunReplace(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *ReplaceOptions) error { - if len(os.Args) > 1 && os.Args[1] == "update" { - printDeprecationWarning("replace", "update") - } - schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) - if err != nil { - return err - } - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - force := cmdutil.GetFlagBool(cmd, "force") - if len(options.Filenames) == 0 { - return cmdutil.UsageError(cmd, "Must specify --filename to replace") - } - - shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" - if force { - return forceReplace(f, out, cmd, args, shortOutput, options) - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - Schema(schema). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - return r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - - if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { - return cmdutil.AddSourceToErr("replacing", info.Source, err) - } - - if cmdutil.ShouldRecord(cmd, info) { - if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil { - return cmdutil.AddSourceToErr("replacing", info.Source, err) - } - } - - // Serialize the object with the annotation applied. - obj, err := resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, true, info.Object) - if err != nil { - return cmdutil.AddSourceToErr("replacing", info.Source, err) - } - - info.Refresh(obj, true) - printObjectSpecificMessage(obj, out) - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "replaced") - return nil - }) -} - -func forceReplace(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *ReplaceOptions) error { - schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) - if err != nil { - return err - } - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - for i, filename := range options.Filenames { - if filename == "-" { - tempDir, err := ioutil.TempDir("", "kubectl_replace_") - if err != nil { - return err - } - defer os.RemoveAll(tempDir) - tempFilename := filepath.Join(tempDir, "resource.stdin") - err = cmdutil.DumpReaderToFile(os.Stdin, tempFilename) - if err != nil { - return err - } - options.Filenames[i] = tempFilename - } - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - ResourceTypeOrNameArgs(false, args...).RequireObject(false). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - //Replace will create a resource if it doesn't exist already, so ignore not found error - ignoreNotFound := true - // By default use a reaper to delete all related resources. - if cmdutil.GetFlagBool(cmd, "cascade") { - glog.Warningf("\"cascade\" is set, kubectl will delete and re-create all resources managed by this resource (e.g. Pods created by a ReplicationController). Consider using \"kubectl rolling-update\" if you want to update a ReplicationController together with its Pods.") - err = ReapResult(r, f, out, cmdutil.GetFlagBool(cmd, "cascade"), ignoreNotFound, cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper) - } else { - err = DeleteResult(r, out, ignoreNotFound, shortOutput, mapper) - } - if err != nil { - return err - } - - r = resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - Schema(schema). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - count := 0 - err = r.Visit(func(info *resource.Info, err error) error { - if err != nil { - return err - } - - if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { - return err - } - - if cmdutil.ShouldRecord(cmd, info) { - if err := cmdutil.RecordChangeCause(info.Object, f.Command()); err != nil { - return cmdutil.AddSourceToErr("replacing", info.Source, err) - } - } - - obj, err := resource.NewHelper(info.Client, info.Mapping).Create(info.Namespace, true, info.Object) - if err != nil { - return err - } - - count++ - info.Refresh(obj, true) - printObjectSpecificMessage(obj, out) - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "replaced") - return nil - }) - if err != nil { - return err - } - if count == 0 { - return fmt.Errorf("no objects passed to replace") - } - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/replace_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/replace_test.go deleted file mode 100644 index 5ca2b2ec8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/replace_test.go +++ /dev/null @@ -1,197 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package cmd - -import ( - "bytes" - "net/http" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/client/unversioned/fake" -) - -func TestReplaceObject(t *testing.T) { - _, _, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && (m == "GET" || m == "PUT" || m == "DELETE"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - case p == "/namespaces/test/replicationcontrollers" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdReplace(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - // uses the name from the file, not the response - if buf.String() != "replicationcontroller/rc1\n" { - t.Errorf("unexpected output: %s", buf.String()) - } - - buf.Reset() - cmd.Flags().Set("force", "true") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/redis-master\nreplicationcontroller/rc1\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestReplaceMultipleObject(t *testing.T) { - _, svc, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && (m == "GET" || m == "PUT" || m == "DELETE"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - case p == "/namespaces/test/replicationcontrollers" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - case p == "/namespaces/test/services/frontend" && (m == "GET" || m == "PUT" || m == "DELETE"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - case p == "/namespaces/test/services" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &svc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdReplace(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("filename", "../../../examples/guestbook/frontend-service.yaml") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/rc1\nservice/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } - - buf.Reset() - cmd.Flags().Set("force", "true") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/redis-master\nservice/frontend\nreplicationcontroller/rc1\nservice/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestReplaceDirectory(t *testing.T) { - _, svc, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case strings.HasPrefix(p, "/namespaces/test/services/") && (m == "GET" || m == "PUT" || m == "DELETE"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil - case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers/") && (m == "GET" || m == "PUT" || m == "DELETE"): - return &http.Response{StatusCode: 200, Body: objBody(codec, &rc.Items[0])}, nil - case strings.HasPrefix(p, "/namespaces/test/services") && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &svc.Items[0])}, nil - case strings.HasPrefix(p, "/namespaces/test/replicationcontrollers") && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdReplace(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook") - cmd.Flags().Set("namespace", "test") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/rc1\nservice/baz\nreplicationcontroller/rc1\nservice/baz\nreplicationcontroller/rc1\nservice/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } - - buf.Reset() - cmd.Flags().Set("force", "true") - cmd.Flags().Set("cascade", "false") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/frontend\nservice/frontend\nreplicationcontroller/redis-master\nservice/redis-master\nreplicationcontroller/redis-slave\nservice/redis-slave\n"+ - "replicationcontroller/rc1\nservice/baz\nreplicationcontroller/rc1\nservice/baz\nreplicationcontroller/rc1\nservice/baz\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} - -func TestForceReplaceObjectNotFound(t *testing.T) { - _, _, rc := testData() - - f, tf, codec := NewAPIFactory() - tf.Printer = &testPrinter{} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == "/namespaces/test/replicationcontrollers/redis-master" && m == "DELETE": - return &http.Response{StatusCode: 404, Body: stringBody("")}, nil - case p == "/namespaces/test/replicationcontrollers" && m == "POST": - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - tf.Namespace = "test" - buf := bytes.NewBuffer([]byte{}) - - cmd := NewCmdReplace(f, buf) - cmd.Flags().Set("filename", "../../../examples/guestbook/redis-master-controller.yaml") - cmd.Flags().Set("force", "true") - cmd.Flags().Set("cascade", "false") - cmd.Flags().Set("output", "name") - cmd.Run(cmd, []string{}) - - if buf.String() != "replicationcontroller/rc1\n" { - t.Errorf("unexpected output: %s", buf.String()) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollingupdate.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollingupdate.go deleted file mode 100644 index c3e796371..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollingupdate.go +++ /dev/null @@ -1,394 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "fmt" - "io" - "os" - "time" - - "github.com/golang/glog" - - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/util/intstr" -) - -// RollingUpdateOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type RollingUpdateOptions struct { - Filenames []string -} - -const ( - rollingUpdate_long = `Perform a rolling update of the given ReplicationController. - -Replaces the specified replication controller with a new replication controller by updating one pod at a time to use the -new PodTemplate. The new-controller.json must specify the same namespace as the -existing replication controller and overwrite at least one (common) label in its replicaSelector.` - rollingUpdate_example = `# Update pods of frontend-v1 using new replication controller data in frontend-v2.json. -$ kubectl rolling-update frontend-v1 -f frontend-v2.json - -# Update pods of frontend-v1 using JSON data passed into stdin. -$ cat frontend-v2.json | kubectl rolling-update frontend-v1 -f - - -# Update the pods of frontend-v1 to frontend-v2 by just changing the image, and switching the -# name of the replication controller. -$ kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 - -# Update the pods of frontend by just changing the image, and keeping the old name. -$ kubectl rolling-update frontend --image=image:v2 - -# Abort and reverse an existing rollout in progress (from frontend-v1 to frontend-v2). -$ kubectl rolling-update frontend-v1 frontend-v2 --rollback -` -) - -var ( - updatePeriod, _ = time.ParseDuration("1m0s") - timeout, _ = time.ParseDuration("5m0s") - pollInterval, _ = time.ParseDuration("3s") -) - -func NewCmdRollingUpdate(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &RollingUpdateOptions{} - - cmd := &cobra.Command{ - Use: "rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] --image=NEW_CONTAINER_IMAGE | -f NEW_CONTROLLER_SPEC)", - // rollingupdate is deprecated. - Aliases: []string{"rollingupdate"}, - Short: "Perform a rolling update of the given ReplicationController.", - Long: rollingUpdate_long, - Example: rollingUpdate_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunRollingUpdate(f, out, cmd, args, options) - cmdutil.CheckErr(err) - }, - } - cmd.Flags().Duration("update-period", updatePeriod, `Time to wait between updating pods. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`) - cmd.Flags().Duration("poll-interval", pollInterval, `Time delay between polling for replication controller status after the update. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`) - cmd.Flags().Duration("timeout", timeout, `Max time to wait for a replication controller to update before giving up. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".`) - usage := "Filename or URL to file to use to create the new replication controller." - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.MarkFlagRequired("filename") - cmd.Flags().String("image", "", "Image to use for upgrading the replication controller. Must be distinct from the existing image (either new image or new image tag). Can not be used with --filename/-f") - cmd.MarkFlagRequired("image") - cmd.Flags().String("deployment-label-key", "deployment", "The key to use to differentiate between two different controllers, default 'deployment'. Only relevant when --image is specified, ignored otherwise") - cmd.Flags().String("container", "", "Container name which will have its image upgraded. Only relevant when --image is specified, ignored otherwise. Required when using --image on a multi-container pod") - cmd.Flags().Bool("dry-run", false, "If true, print out the changes that would be made, but don't actually make them.") - cmd.Flags().Bool("rollback", false, "If true, this is a request to abort an existing rollout that is partially rolled out. It effectively reverses current and next and runs a rollout") - cmdutil.AddValidateFlags(cmd) - cmdutil.AddPrinterFlags(cmd) - return cmd -} - -func validateArguments(cmd *cobra.Command, filenames, args []string) error { - deploymentKey := cmdutil.GetFlagString(cmd, "deployment-label-key") - image := cmdutil.GetFlagString(cmd, "image") - rollback := cmdutil.GetFlagBool(cmd, "rollback") - - if len(deploymentKey) == 0 { - return cmdutil.UsageError(cmd, "--deployment-label-key can not be empty") - } - if len(filenames) > 1 { - return cmdutil.UsageError(cmd, "May only specify a single filename for new controller") - } - - if !rollback { - if len(filenames) == 0 && len(image) == 0 { - return cmdutil.UsageError(cmd, "Must specify --filename or --image for new controller") - } - if len(filenames) != 0 && len(image) != 0 { - return cmdutil.UsageError(cmd, "--filename and --image can not both be specified") - } - } else { - if len(filenames) != 0 || len(image) != 0 { - return cmdutil.UsageError(cmd, "Don't specify --filename or --image on rollback") - } - } - - if len(args) < 1 { - return cmdutil.UsageError(cmd, "Must specify the controller to update") - } - - return nil -} - -func RunRollingUpdate(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *RollingUpdateOptions) error { - if len(os.Args) > 1 && os.Args[1] == "rollingupdate" { - printDeprecationWarning("rolling-update", "rollingupdate") - } - err := validateArguments(cmd, options.Filenames, args) - if err != nil { - return err - } - - deploymentKey := cmdutil.GetFlagString(cmd, "deployment-label-key") - filename := "" - image := cmdutil.GetFlagString(cmd, "image") - oldName := args[0] - rollback := cmdutil.GetFlagBool(cmd, "rollback") - period := cmdutil.GetFlagDuration(cmd, "update-period") - interval := cmdutil.GetFlagDuration(cmd, "poll-interval") - timeout := cmdutil.GetFlagDuration(cmd, "timeout") - dryrun := cmdutil.GetFlagBool(cmd, "dry-run") - outputFormat := cmdutil.GetFlagString(cmd, "output") - container := cmdutil.GetFlagString(cmd, "container") - - if len(options.Filenames) > 0 { - filename = options.Filenames[0] - } - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - client, err := f.Client() - if err != nil { - return err - } - - var newRc *api.ReplicationController - // fetch rc - oldRc, err := client.ReplicationControllers(cmdNamespace).Get(oldName) - if err != nil { - if !errors.IsNotFound(err) || len(image) == 0 || len(args) > 1 { - return err - } - // We're in the middle of a rename, look for an RC with a source annotation of oldName - newRc, err := kubectl.FindSourceController(client, cmdNamespace, oldName) - if err != nil { - return err - } - return kubectl.Rename(client, newRc, oldName) - } - - var keepOldName bool - var replicasDefaulted bool - - mapper, typer := f.Object() - - if len(filename) != 0 { - schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) - if err != nil { - return err - } - - request := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - Schema(schema). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, filename). - Do() - obj, err := request.Object() - if err != nil { - return err - } - var ok bool - // Handle filename input from stdin. The resource builder always returns an api.List - // when creating resource(s) from a stream. - if list, ok := obj.(*api.List); ok { - if len(list.Items) > 1 { - return cmdutil.UsageError(cmd, "%s specifies multiple items", filename) - } - obj = list.Items[0] - } - newRc, ok = obj.(*api.ReplicationController) - if !ok { - if gvk, err := typer.ObjectKind(obj); err == nil { - return cmdutil.UsageError(cmd, "%s contains a %v not a ReplicationController", filename, gvk) - } - glog.V(4).Infof("Object %#v is not a ReplicationController", obj) - return cmdutil.UsageError(cmd, "%s does not specify a valid ReplicationController", filename) - } - infos, err := request.Infos() - if err != nil || len(infos) != 1 { - glog.V(2).Infof("was not able to recover adequate information to discover if .spec.replicas was defaulted") - } else { - replicasDefaulted = isReplicasDefaulted(infos[0]) - } - } - // If the --image option is specified, we need to create a new rc with at least one different selector - // than the old rc. This selector is the hash of the rc, which will differ because the new rc has a - // different image. - if len(image) != 0 { - codec := registered.GroupOrDie(client.APIVersion().Group).Codec - keepOldName = len(args) == 1 - newName := findNewName(args, oldRc) - if newRc, err = kubectl.LoadExistingNextReplicationController(client, cmdNamespace, newName); err != nil { - return err - } - if newRc != nil { - if inProgressImage := newRc.Spec.Template.Spec.Containers[0].Image; inProgressImage != image { - return cmdutil.UsageError(cmd, "Found existing in-progress update to image (%s).\nEither continue in-progress update with --image=%s or rollback with --rollback", inProgressImage, inProgressImage) - } - fmt.Fprintf(out, "Found existing update in progress (%s), resuming.\n", newRc.Name) - } else { - if oldRc.Spec.Template.Spec.Containers[0].Image == image { - return cmdutil.UsageError(cmd, "Specified --image must be distinct from existing container image") - } - newRc, err = kubectl.CreateNewControllerFromCurrentController(client, codec, cmdNamespace, oldName, newName, image, container, deploymentKey) - if err != nil { - return err - } - } - // Update the existing replication controller with pointers to the 'next' controller - // and adding the label if necessary to distinguish it from the 'next' controller. - oldHash, err := api.HashObject(oldRc, codec) - if err != nil { - return err - } - oldRc, err = kubectl.UpdateExistingReplicationController(client, oldRc, cmdNamespace, newRc.Name, deploymentKey, oldHash, out) - if err != nil { - return err - } - } - - if rollback { - keepOldName = len(args) == 1 - newName := findNewName(args, oldRc) - if newRc, err = kubectl.LoadExistingNextReplicationController(client, cmdNamespace, newName); err != nil { - return err - } - - if newRc == nil { - return cmdutil.UsageError(cmd, "Could not find %s to rollback.\n", newName) - } - } - - if oldName == newRc.Name { - return cmdutil.UsageError(cmd, "%s cannot have the same name as the existing ReplicationController %s", - filename, oldName) - } - - updater := kubectl.NewRollingUpdater(newRc.Namespace, client) - - // To successfully pull off a rolling update the new and old rc have to differ - // by at least one selector. Every new pod should have the selector and every - // old pod should not have the selector. - var hasLabel bool - for key, oldValue := range oldRc.Spec.Selector { - if newValue, ok := newRc.Spec.Selector[key]; ok && newValue != oldValue { - hasLabel = true - break - } - } - if !hasLabel { - return cmdutil.UsageError(cmd, "%s must specify a matching key with non-equal value in Selector for %s", - filename, oldName) - } - // TODO: handle scales during rolling update - if replicasDefaulted { - newRc.Spec.Replicas = oldRc.Spec.Replicas - } - if dryrun { - oldRcData := &bytes.Buffer{} - newRcData := &bytes.Buffer{} - if outputFormat == "" { - oldRcData.WriteString(oldRc.Name) - newRcData.WriteString(newRc.Name) - } else { - if err := f.PrintObject(cmd, oldRc, oldRcData); err != nil { - return err - } - if err := f.PrintObject(cmd, newRc, newRcData); err != nil { - return err - } - } - fmt.Fprintf(out, "Rolling from:\n%s\nTo:\n%s\n", string(oldRcData.Bytes()), string(newRcData.Bytes())) - return nil - } - updateCleanupPolicy := kubectl.DeleteRollingUpdateCleanupPolicy - if keepOldName { - updateCleanupPolicy = kubectl.RenameRollingUpdateCleanupPolicy - } - config := &kubectl.RollingUpdaterConfig{ - Out: out, - OldRc: oldRc, - NewRc: newRc, - UpdatePeriod: period, - Interval: interval, - Timeout: timeout, - CleanupPolicy: updateCleanupPolicy, - MaxUnavailable: intstr.FromInt(1), - MaxSurge: intstr.FromInt(1), - } - if rollback { - err = kubectl.AbortRollingUpdate(config) - if err != nil { - return err - } - client.ReplicationControllers(config.NewRc.Namespace).Update(config.NewRc) - } - err = updater.Update(config) - if err != nil { - return err - } - - message := "rolling updated" - if keepOldName { - newRc.Name = oldName - } else { - message = fmt.Sprintf("rolling updated to %q", newRc.Name) - } - newRc, err = client.ReplicationControllers(cmdNamespace).Get(newRc.Name) - if err != nil { - return err - } - if outputFormat != "" { - return f.PrintObject(cmd, newRc, out) - } - kind, err := api.Scheme.ObjectKind(newRc) - if err != nil { - return err - } - _, res := meta.KindToResource(kind) - cmdutil.PrintSuccess(mapper, false, out, res.Resource, oldName, message) - return nil -} - -func findNewName(args []string, oldRc *api.ReplicationController) string { - if len(args) >= 2 { - return args[1] - } - if oldRc != nil { - newName, _ := kubectl.GetNextControllerAnnotation(oldRc) - return newName - } - return "" -} - -func isReplicasDefaulted(info *resource.Info) bool { - if info == nil || info.VersionedObject == nil { - // was unable to recover versioned info - return false - } - switch t := info.VersionedObject.(type) { - case *v1.ReplicationController: - return t.Spec.Replicas == nil - } - return false -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollingupdate_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollingupdate_test.go deleted file mode 100644 index bf2204b27..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollingupdate_test.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "testing" -) - -func TestValidateArgs(t *testing.T) { - f, _, _ := NewAPIFactory() - - tests := []struct { - flags map[string]string - filenames []string - args []string - expectErr bool - testName string - }{ - { - expectErr: true, - testName: "nothing", - }, - { - flags: map[string]string{}, - args: []string{"foo"}, - expectErr: true, - testName: "no file, no image", - }, - { - filenames: []string{"bar.yaml"}, - args: []string{"foo"}, - testName: "valid file example", - }, - { - flags: map[string]string{ - "image": "foo:v2", - }, - args: []string{"foo"}, - testName: "missing second image name", - }, - { - flags: map[string]string{ - "image": "foo:v2", - }, - args: []string{"foo", "foo-v2"}, - testName: "valid image example", - }, - { - flags: map[string]string{ - "image": "foo:v2", - }, - filenames: []string{"bar.yaml"}, - args: []string{"foo", "foo-v2"}, - expectErr: true, - testName: "both filename and image example", - }, - } - for _, test := range tests { - out := &bytes.Buffer{} - cmd := NewCmdRollingUpdate(f, out) - - if test.flags != nil { - for key, val := range test.flags { - cmd.Flags().Set(key, val) - } - } - err := validateArguments(cmd, test.filenames, test.args) - if err != nil && !test.expectErr { - t.Errorf("unexpected error: %v (%s)", err, test.testName) - } - if err == nil && test.expectErr { - t.Errorf("unexpected non-error (%s)", test.testName) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout.go deleted file mode 100644 index 8fbb53595..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -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. -*/ - -package rollout - -import ( - "io" - - "github.com/spf13/cobra" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -const ( - rollout_long = `rollout manages a deployment using subcommands like "kubectl rollout undo deployment/abc"` - rollout_example = `# Rollback to the previous deployment -$ kubectl rollout undo deployment/abc` - rollout_valid_resources = `Valid resource types include: - * deployments -` -) - -func NewCmdRollout(f *cmdutil.Factory, out io.Writer) *cobra.Command { - - cmd := &cobra.Command{ - Use: "rollout SUBCOMMAND", - Short: "rollout manages a deployment", - Long: rollout_long, - Example: rollout_example, - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, - } - - // subcommands - cmd.AddCommand(NewCmdRolloutHistory(f, out)) - cmd.AddCommand(NewCmdRolloutPause(f, out)) - cmd.AddCommand(NewCmdRolloutResume(f, out)) - cmd.AddCommand(NewCmdRolloutUndo(f, out)) - - return cmd -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_history.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_history.go deleted file mode 100644 index f3eeb4a71..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_history.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -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. -*/ - -package rollout - -import ( - "fmt" - "io" - - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/util/errors" - - "github.com/spf13/cobra" -) - -// HistoryOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type HistoryOptions struct { - Filenames []string -} - -const ( - history_long = `view previous rollout revisions and configurations.` - history_example = `# View the rollout history of a deployment -$ kubectl rollout history deployment/abc` -) - -func NewCmdRolloutHistory(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &HistoryOptions{} - - cmd := &cobra.Command{ - Use: "history (TYPE NAME | TYPE/NAME) [flags]", - Short: "view rollout history", - Long: history_long, - Example: history_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(RunHistory(f, cmd, out, args, options)) - }, - } - - cmd.Flags().Int64("revision", 0, "See the details, including podTemplate of the revision specified") - usage := "Filename, directory, or URL to a file identifying the resource to get from a server." - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - return cmd -} - -func RunHistory(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string, options *HistoryOptions) error { - if len(args) == 0 && len(options.Filenames) == 0 { - return cmdutil.UsageError(cmd, "Required resource not specified.") - } - revisionDetail := cmdutil.GetFlagInt64(cmd, "revision") - - mapper, typer := f.Object() - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - infos, err := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - ResourceTypeOrNameArgs(true, args...). - Latest(). - Flatten(). - Do(). - Infos() - if err != nil { - return err - } - - errs := []error{} - for _, info := range infos { - mapping := info.ResourceMapping() - historyViewer, err := f.HistoryViewer(mapping) - if err != nil { - errs = append(errs, err) - continue - } - historyInfo, err := historyViewer.History(info.Namespace, info.Name) - if err != nil { - errs = append(errs, err) - continue - } - - formattedOutput := "" - if revisionDetail > 0 { - // Print details of a specific revision - template, ok := historyInfo.RevisionToTemplate[revisionDetail] - if !ok { - return fmt.Errorf("unable to find revision %d of %s %q", revisionDetail, mapping.Resource, info.Name) - } - fmt.Fprintf(out, "%s %q revision %d\n", mapping.Resource, info.Name, revisionDetail) - formattedOutput, err = kubectl.DescribePodTemplate(template) - } else { - // Print all revisions - formattedOutput, err = kubectl.PrintRolloutHistory(historyInfo, mapping.Resource, info.Name) - } - if err != nil { - errs = append(errs, err) - continue - } - fmt.Fprintf(out, "%s\n", formattedOutput) - } - - return errors.NewAggregate(errs) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_pause.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_pause.go deleted file mode 100644 index ae07dcefd..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_pause.go +++ /dev/null @@ -1,118 +0,0 @@ -/* -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. -*/ - -package rollout - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" -) - -// PauseConfig is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type PauseConfig struct { - PauseObject func(object runtime.Object) (bool, error) - Mapper meta.RESTMapper - Typer runtime.ObjectTyper - Info *resource.Info - - Out io.Writer - Filenames []string -} - -const ( - pause_long = `Mark the provided resource as paused - -Paused resources will not be reconciled by a controller. -Use \"kubectl rollout resume\" to resume a paused resource. -Currently only deployments support being paused.` - - pause_example = `# Mark the nginx deployment as paused. Any current state of -# the deployment will continue its function, new updates to the deployment will not -# have an effect as long as the deployment is paused. -$ kubectl rollout pause deployment/nginx` -) - -func NewCmdRolloutPause(f *cmdutil.Factory, out io.Writer) *cobra.Command { - opts := &PauseConfig{} - - cmd := &cobra.Command{ - Use: "pause RESOURCE", - Short: "Mark the provided resource as paused", - Long: pause_long, - Example: pause_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(opts.CompletePause(f, cmd, out, args)) - cmdutil.CheckErr(opts.RunPause()) - }, - } - - usage := "Filename, directory, or URL to a file identifying the resource to get from a server." - kubectl.AddJsonFilenameFlag(cmd, &opts.Filenames, usage) - return cmd -} - -func (o *PauseConfig) CompletePause(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error { - if len(args) == 0 && len(o.Filenames) == 0 { - return cmdutil.UsageError(cmd, cmd.Use) - } - - o.Mapper, o.Typer = f.Object() - o.PauseObject = f.PauseObject - o.Out = out - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - infos, err := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, o.Filenames...). - ResourceTypeOrNameArgs(true, args...). - SingleResourceType(). - Latest(). - Do().Infos() - if err != nil { - return err - } - if len(infos) != 1 { - return fmt.Errorf("rollout pause is only supported on individual resources - %d resources were found", len(infos)) - } - o.Info = infos[0] - return nil -} - -func (o PauseConfig) RunPause() error { - isAlreadyPaused, err := o.PauseObject(o.Info.Object) - if err != nil { - return err - } - if isAlreadyPaused { - cmdutil.PrintSuccess(o.Mapper, false, o.Out, o.Info.Mapping.Resource, o.Info.Name, "already paused") - return nil - } - cmdutil.PrintSuccess(o.Mapper, false, o.Out, o.Info.Mapping.Resource, o.Info.Name, "paused") - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_resume.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_resume.go deleted file mode 100644 index a38147e75..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_resume.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -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. -*/ - -package rollout - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" -) - -// ResumeConfig is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type ResumeConfig struct { - ResumeObject func(object runtime.Object) (bool, error) - Mapper meta.RESTMapper - Typer runtime.ObjectTyper - Info *resource.Info - - Out io.Writer - Filenames []string -} - -const ( - resume_long = `Resume a paused resource - -Paused resources will not be reconciled by a controller. By resuming a -resource, we allow it to be reconciled again. -Currently only deployments support being resumed.` - - resume_example = `# Resume an already paused deployment -$ kubectl rollout resume deployment/nginx` -) - -func NewCmdRolloutResume(f *cmdutil.Factory, out io.Writer) *cobra.Command { - opts := &ResumeConfig{} - - cmd := &cobra.Command{ - Use: "resume RESOURCE", - Short: "Resume a paused resource", - Long: resume_long, - Example: resume_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(opts.CompleteResume(f, cmd, out, args)) - cmdutil.CheckErr(opts.RunResume()) - }, - } - - usage := "Filename, directory, or URL to a file identifying the resource to get from a server." - kubectl.AddJsonFilenameFlag(cmd, &opts.Filenames, usage) - return cmd -} - -func (o *ResumeConfig) CompleteResume(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error { - if len(args) == 0 && len(o.Filenames) == 0 { - return cmdutil.UsageError(cmd, cmd.Use) - } - - o.Mapper, o.Typer = f.Object() - o.ResumeObject = f.ResumeObject - o.Out = out - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - infos, err := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, o.Filenames...). - ResourceTypeOrNameArgs(true, args...). - SingleResourceType(). - Latest(). - Do().Infos() - if err != nil { - return err - } - if len(infos) != 1 { - return fmt.Errorf("rollout resume is only supported on individual resources - %d resources were found", len(infos)) - } - o.Info = infos[0] - return nil -} - -func (o ResumeConfig) RunResume() error { - isAlreadyResumed, err := o.ResumeObject(o.Info.Object) - if err != nil { - return err - } - if isAlreadyResumed { - cmdutil.PrintSuccess(o.Mapper, false, o.Out, o.Info.Mapping.Resource, o.Info.Name, "already resumed") - return nil - } - cmdutil.PrintSuccess(o.Mapper, false, o.Out, o.Info.Mapping.Resource, o.Info.Name, "resumed") - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_undo.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_undo.go deleted file mode 100644 index ccaf429ee..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/rollout/rollout_undo.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -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. -*/ - -package rollout - -import ( - "fmt" - "io" - - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" - - "github.com/spf13/cobra" -) - -// UndoOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type UndoOptions struct { - Rollbacker kubectl.Rollbacker - Mapper meta.RESTMapper - Typer runtime.ObjectTyper - Info *resource.Info - ToRevision int64 - Out io.Writer - Filenames []string -} - -const ( - undo_long = `undo rolls back to a previous rollout.` - undo_example = `# Rollback to the previous deployment -$ kubectl rollout undo deployment/abc` -) - -func NewCmdRolloutUndo(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &UndoOptions{} - - cmd := &cobra.Command{ - Use: "undo (TYPE NAME | TYPE/NAME) [flags]", - Short: "undoes a previous rollout", - Long: undo_long, - Example: undo_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(options.CompleteUndo(f, cmd, out, args)) - cmdutil.CheckErr(options.RunUndo()) - }, - } - - cmd.Flags().Int64("to-revision", 0, "The revision to rollback to. Default to 0 (last revision).") - usage := "Filename, directory, or URL to a file identifying the resource to get from a server." - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - return cmd -} - -func (o *UndoOptions) CompleteUndo(f *cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error { - if len(args) == 0 && len(o.Filenames) == 0 { - return cmdutil.UsageError(cmd, "Required resource not specified.") - } - - o.ToRevision = cmdutil.GetFlagInt64(cmd, "to-revision") - o.Mapper, o.Typer = f.Object() - o.Out = out - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - infos, err := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, o.Filenames...). - ResourceTypeOrNameArgs(true, args...). - Latest(). - Flatten(). - Do(). - Infos() - if err != nil { - return err - } - - if len(infos) != 1 { - return fmt.Errorf("rollout undo is only supported on individual resources - %d resources were found", len(infos)) - } - o.Info = infos[0] - o.Rollbacker, err = f.Rollbacker(o.Info.ResourceMapping()) - return err -} - -func (o *UndoOptions) RunUndo() error { - result, err := o.Rollbacker.Rollback(o.Info.Namespace, o.Info.Name, nil, o.ToRevision, o.Info.Object) - if err != nil { - return err - } - cmdutil.PrintSuccess(o.Mapper, false, o.Out, o.Info.Mapping.Resource, o.Info.Name, result) - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/run.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/run.go deleted file mode 100644 index f95759a58..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/run.go +++ /dev/null @@ -1,459 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "os" - "time" - - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - "k8s.io/kubernetes/pkg/runtime" -) - -const ( - run_long = `Create and run a particular image, possibly replicated. -Creates a deployment or job to manage the created container(s).` - run_example = `# Start a single instance of nginx. -$ kubectl run nginx --image=nginx - -# Start a single instance of hazelcast and let the container expose port 5701 . -$ kubectl run hazelcast --image=hazelcast --port=5701 - -# Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default" in the container. -$ kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default" - -# Start a replicated instance of nginx. -$ kubectl run nginx --image=nginx --replicas=5 - -# Dry run. Print the corresponding API objects without creating them. -$ kubectl run nginx --image=nginx --dry-run - -# Start a single instance of nginx, but overload the spec of the deployment with a partial set of values parsed from JSON. -$ kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }' - -# Start a single instance of busybox and keep it in the foreground, don't restart it if it exits. -$ kubectl run -i --tty busybox --image=busybox --restart=Never - -# Start the nginx container using the default command, but use custom arguments (arg1 .. argN) for that command. -$ kubectl run nginx --image=nginx -- ... - -# Start the nginx container using a different command and custom arguments. -$ kubectl run nginx --image=nginx --command -- ... - -# Start the perl container to compute π to 2000 places and print it out. -$ kubectl run pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'` -) - -func NewCmdRun(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "run NAME --image=image [--env=\"key=value\"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...]", - // run-container is deprecated - Aliases: []string{"run-container"}, - Short: "Run a particular image on the cluster.", - Long: run_long, - Example: run_example, - Run: func(cmd *cobra.Command, args []string) { - argsLenAtDash := cmd.ArgsLenAtDash() - err := Run(f, cmdIn, cmdOut, cmdErr, cmd, args, argsLenAtDash) - cmdutil.CheckErr(err) - }, - } - cmdutil.AddPrinterFlags(cmd) - addRunFlags(cmd) - cmdutil.AddApplyAnnotationFlags(cmd) - cmdutil.AddRecordFlag(cmd) - return cmd -} - -func addRunFlags(cmd *cobra.Command) { - cmd.Flags().String("generator", "", "The name of the API generator to use. Default is 'deployment/v1beta1' if --restart=Always, otherwise the default is 'job/v1beta1'.") - cmd.Flags().String("image", "", "The image for the container to run.") - cmd.MarkFlagRequired("image") - cmd.Flags().IntP("replicas", "r", 1, "Number of replicas to create for this container. Default is 1.") - cmd.Flags().Bool("rm", false, "If true, delete resources created in this command for attached containers.") - cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without sending it.") - cmd.Flags().String("overrides", "", "An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.") - cmd.Flags().StringSlice("env", []string{}, "Environment variables to set in the container") - cmd.Flags().Int("port", -1, "The port that this container exposes. If --expose is true, this is also the port used by the service that is created.") - cmd.Flags().Int("hostport", -1, "The host port mapping for the container port. To demonstrate a single-machine container.") - cmd.Flags().StringP("labels", "l", "", "Labels to apply to the pod(s).") - cmd.Flags().BoolP("stdin", "i", false, "Keep stdin open on the container(s) in the pod, even if nothing is attached.") - cmd.Flags().Bool("tty", false, "Allocated a TTY for each container in the pod. Because -t is currently shorthand for --template, -t is not supported for --tty. This shorthand is deprecated and we expect to adopt -t for --tty soon.") - cmd.Flags().Bool("attach", false, "If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...' were called. Default false, unless '-i/--interactive' is set, in which case the default is true.") - cmd.Flags().Bool("leave-stdin-open", false, "If the pod is started in interactive mode or with stdin, leave stdin open after the first attach completes. By default, stdin will be closed after the first attach completes.") - cmd.Flags().String("restart", "Always", "The restart policy for this Pod. Legal values [Always, OnFailure, Never]. If set to 'Always' a deployment is created for this pod, if set to OnFailure or Never, a job is created for this pod and --replicas must be 1. Default 'Always'") - cmd.Flags().Bool("command", false, "If true and extra arguments are present, use them as the 'command' field in the container, rather than the 'args' field which is the default.") - cmd.Flags().String("requests", "", "The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'") - cmd.Flags().String("limits", "", "The resource requirement limits for this container. For example, 'cpu=200m,memory=512Mi'") - cmd.Flags().Bool("expose", false, "If true, a public, external service is created for the container(s) which are run") - cmd.Flags().String("service-generator", "service/v2", "The name of the generator to use for creating a service. Only used if --expose is true") - cmd.Flags().String("service-overrides", "", "An inline JSON override for the generated service object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose is true.") -} - -func Run(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string, argsLenAtDash int) error { - if len(os.Args) > 1 && os.Args[1] == "run-container" { - printDeprecationWarning("run", "run-container") - } - - // Let kubectl run follow rules for `--`, see #13004 issue - if len(args) == 0 || argsLenAtDash == 0 { - return cmdutil.UsageError(cmd, "NAME is required for run") - } - - interactive := cmdutil.GetFlagBool(cmd, "stdin") - tty := cmdutil.GetFlagBool(cmd, "tty") - if tty && !interactive { - return cmdutil.UsageError(cmd, "-i/--stdin is required for containers with --tty=true") - } - replicas := cmdutil.GetFlagInt(cmd, "replicas") - if interactive && replicas != 1 { - return cmdutil.UsageError(cmd, fmt.Sprintf("-i/--stdin requires that replicas is 1, found %d", replicas)) - } - - namespace, _, err := f.DefaultNamespace() - if err != nil { - return err - } - restartPolicy, err := getRestartPolicy(cmd, interactive) - if err != nil { - return err - } - if restartPolicy != api.RestartPolicyAlways && replicas != 1 { - return cmdutil.UsageError(cmd, fmt.Sprintf("--restart=%s requires that --replicas=1, found %d", restartPolicy, replicas)) - } - - generatorName := cmdutil.GetFlagString(cmd, "generator") - if len(generatorName) == 0 { - if restartPolicy == api.RestartPolicyAlways { - generatorName = "deployment/v1beta1" - } else { - generatorName = "job/v1beta1" - } - } - generators := f.Generators("run") - generator, found := generators[generatorName] - if !found { - return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName)) - } - names := generator.ParamNames() - params := kubectl.MakeParams(cmd, names) - params["name"] = args[0] - if len(args) > 1 { - params["args"] = args[1:] - } - - params["env"] = cmdutil.GetFlagStringSlice(cmd, "env") - - obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "overrides"), namespace) - if err != nil { - return err - } - - if cmdutil.GetFlagBool(cmd, "expose") { - serviceGenerator := cmdutil.GetFlagString(cmd, "service-generator") - if len(serviceGenerator) == 0 { - return cmdutil.UsageError(cmd, fmt.Sprintf("No service generator specified")) - } - if err := generateService(f, cmd, args, serviceGenerator, params, namespace, cmdOut); err != nil { - return err - } - } - - attachFlag := cmd.Flags().Lookup("attach") - attach := cmdutil.GetFlagBool(cmd, "attach") - - if !attachFlag.Changed && interactive { - attach = true - } - - remove := cmdutil.GetFlagBool(cmd, "rm") - if !attach && remove { - return cmdutil.UsageError(cmd, "--rm should only be used for attached containers") - } - - if attach { - opts := &AttachOptions{ - In: cmdIn, - Out: cmdOut, - Err: cmdErr, - Stdin: interactive, - TTY: tty, - - Attach: &DefaultRemoteAttach{}, - } - config, err := f.ClientConfig() - if err != nil { - return err - } - opts.Config = config - - client, err := f.Client() - if err != nil { - return err - } - opts.Client = client - - attachablePod, err := f.AttachablePodForObject(obj) - if err != nil { - return err - } - err = handleAttachPod(f, client, attachablePod, opts) - if err != nil { - return err - } - - if remove { - namespace, err = mapping.MetadataAccessor.Namespace(obj) - if err != nil { - return err - } - var name string - name, err = mapping.MetadataAccessor.Name(obj) - if err != nil { - return err - } - _, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(namespace).DefaultNamespace(). - ResourceNames(mapping.Resource, name). - Flatten(). - Do() - return ReapResult(r, f, cmdOut, true, true, 0, -1, false, mapper) - } - return nil - } - - outputFormat := cmdutil.GetFlagString(cmd, "output") - if outputFormat != "" { - return f.PrintObject(cmd, obj, cmdOut) - } - cmdutil.PrintSuccess(mapper, false, cmdOut, mapping.Resource, args[0], "created") - return nil -} - -func waitForPodRunning(c *client.Client, pod *api.Pod, out io.Writer) (status api.PodPhase, err error) { - for { - pod, err := c.Pods(pod.Namespace).Get(pod.Name) - if err != nil { - return api.PodUnknown, err - } - ready := false - if pod.Status.Phase == api.PodRunning { - ready = true - for _, status := range pod.Status.ContainerStatuses { - if !status.Ready { - ready = false - break - } - } - if ready { - return api.PodRunning, nil - } - } - if pod.Status.Phase == api.PodSucceeded || pod.Status.Phase == api.PodFailed { - return pod.Status.Phase, nil - } - fmt.Fprintf(out, "Waiting for pod %s/%s to be running, status is %s, pod ready: %v\n", pod.Namespace, pod.Name, pod.Status.Phase, ready) - time.Sleep(2 * time.Second) - continue - } -} - -func handleAttachPod(f *cmdutil.Factory, c *client.Client, pod *api.Pod, opts *AttachOptions) error { - status, err := waitForPodRunning(c, pod, opts.Out) - if err != nil { - return err - } - if status == api.PodSucceeded || status == api.PodFailed { - req, err := f.LogsForObject(pod, &api.PodLogOptions{Container: opts.GetContainerName(pod)}) - if err != nil { - return err - } - readCloser, err := req.Stream() - if err != nil { - return err - } - defer readCloser.Close() - _, err = io.Copy(opts.Out, readCloser) - return err - } - opts.Client = c - opts.PodName = pod.Name - opts.Namespace = pod.Namespace - if err := opts.Run(); err != nil { - fmt.Fprintf(opts.Out, "Error attaching, falling back to logs: %v\n", err) - req, err := f.LogsForObject(pod, &api.PodLogOptions{Container: opts.GetContainerName(pod)}) - if err != nil { - return err - } - readCloser, err := req.Stream() - if err != nil { - return err - } - defer readCloser.Close() - _, err = io.Copy(opts.Out, readCloser) - return err - } - return nil -} - -func getRestartPolicy(cmd *cobra.Command, interactive bool) (api.RestartPolicy, error) { - restart := cmdutil.GetFlagString(cmd, "restart") - if len(restart) == 0 { - if interactive { - return api.RestartPolicyOnFailure, nil - } else { - return api.RestartPolicyAlways, nil - } - } - switch api.RestartPolicy(restart) { - case api.RestartPolicyAlways: - return api.RestartPolicyAlways, nil - case api.RestartPolicyOnFailure: - return api.RestartPolicyOnFailure, nil - case api.RestartPolicyNever: - return api.RestartPolicyNever, nil - default: - return "", cmdutil.UsageError(cmd, fmt.Sprintf("invalid restart policy: %s", restart)) - } -} - -func generateService(f *cmdutil.Factory, cmd *cobra.Command, args []string, serviceGenerator string, paramsIn map[string]interface{}, namespace string, out io.Writer) error { - generators := f.Generators("expose") - generator, found := generators[serviceGenerator] - if !found { - return fmt.Errorf("missing service generator: %s", serviceGenerator) - } - names := generator.ParamNames() - - port := cmdutil.GetFlagInt(cmd, "port") - if port < 1 { - return fmt.Errorf("--port must be a positive integer when exposing a service") - } - - params := map[string]interface{}{} - for key, value := range paramsIn { - _, isString := value.(string) - if isString { - params[key] = value - } - } - - name, found := params["name"] - if !found || len(name.(string)) == 0 { - return fmt.Errorf("name is a required parameter") - } - selector, found := params["labels"] - if !found || len(selector.(string)) == 0 { - selector = fmt.Sprintf("run=%s", name.(string)) - } - params["selector"] = selector - - if defaultName, found := params["default-name"]; !found || len(defaultName.(string)) == 0 { - params["default-name"] = name - } - - obj, _, mapper, mapping, err := createGeneratedObject(f, cmd, generator, names, params, cmdutil.GetFlagString(cmd, "service-overrides"), namespace) - if err != nil { - return err - } - - if cmdutil.GetFlagString(cmd, "output") != "" { - return f.PrintObject(cmd, obj, out) - } - cmdutil.PrintSuccess(mapper, false, out, mapping.Resource, args[0], "created") - - return nil -} - -func createGeneratedObject(f *cmdutil.Factory, cmd *cobra.Command, generator kubectl.Generator, names []kubectl.GeneratorParam, params map[string]interface{}, overrides, namespace string) (runtime.Object, string, meta.RESTMapper, *meta.RESTMapping, error) { - err := kubectl.ValidateParams(names, params) - if err != nil { - return nil, "", nil, nil, err - } - - // TODO: Validate flag usage against selected generator. More tricky since --expose was added. - obj, err := generator.Generate(params) - if err != nil { - return nil, "", nil, nil, err - } - - mapper, typer := f.Object() - groupVersionKind, err := typer.ObjectKind(obj) - if err != nil { - return nil, "", nil, nil, err - } - - if len(overrides) > 0 { - codec := runtime.NewCodec(f.JSONEncoder(), f.Decoder(true)) - obj, err = cmdutil.Merge(codec, obj, overrides, groupVersionKind.Kind) - if err != nil { - return nil, "", nil, nil, err - } - } - - mapping, err := mapper.RESTMapping(groupVersionKind.GroupKind(), groupVersionKind.Version) - if err != nil { - return nil, "", nil, nil, err - } - client, err := f.ClientForMapping(mapping) - if err != nil { - return nil, "", nil, nil, err - } - - annotations, err := mapping.MetadataAccessor.Annotations(obj) - if err != nil { - return nil, "", nil, nil, err - } - if cmdutil.GetRecordFlag(cmd) || len(annotations[kubectl.ChangeCauseAnnotation]) > 0 { - if err := cmdutil.RecordChangeCause(obj, f.Command()); err != nil { - return nil, "", nil, nil, err - } - } - // TODO: extract this flag to a central location, when such a location exists. - if !cmdutil.GetFlagBool(cmd, "dry-run") { - resourceMapper := &resource.Mapper{ - ObjectTyper: typer, - RESTMapper: mapper, - ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), - Decoder: f.Decoder(true), - } - info, err := resourceMapper.InfoForObject(obj) - if err != nil { - return nil, "", nil, nil, err - } - - if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info, f.JSONEncoder()); err != nil { - return nil, "", nil, nil, err - } - - obj, err = resource.NewHelper(client, mapping).Create(namespace, false, info.Object) - if err != nil { - return nil, "", nil, nil, err - } - } - return obj, groupVersionKind.Kind, mapper, mapping, err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/run_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/run_test.go deleted file mode 100644 index a728a810e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/run_test.go +++ /dev/null @@ -1,331 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "os" - "reflect" - "testing" - - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/intstr" -) - -func TestGetRestartPolicy(t *testing.T) { - tests := []struct { - input string - interactive bool - expected api.RestartPolicy - expectErr bool - }{ - { - input: "", - expected: api.RestartPolicyAlways, - }, - { - input: "", - interactive: true, - expected: api.RestartPolicyOnFailure, - }, - { - input: string(api.RestartPolicyAlways), - interactive: true, - expected: api.RestartPolicyAlways, - }, - { - input: string(api.RestartPolicyNever), - interactive: true, - expected: api.RestartPolicyNever, - }, - { - input: string(api.RestartPolicyAlways), - expected: api.RestartPolicyAlways, - }, - { - input: string(api.RestartPolicyNever), - expected: api.RestartPolicyNever, - }, - { - input: "foo", - expectErr: true, - }, - } - for _, test := range tests { - cmd := &cobra.Command{} - cmd.Flags().String("restart", "", "dummy restart flag") - cmd.Flags().Lookup("restart").Value.Set(test.input) - policy, err := getRestartPolicy(cmd, test.interactive) - if test.expectErr && err == nil { - t.Error("unexpected non-error") - } - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if !test.expectErr && policy != test.expected { - t.Errorf("expected: %s, saw: %s (%s:%v)", test.expected, policy, test.input, test.interactive) - } - } -} - -func TestGetEnv(t *testing.T) { - test := struct { - input []string - expected []string - }{ - input: []string{"a=b", "c=d"}, - expected: []string{"a=b", "c=d"}, - } - cmd := &cobra.Command{} - cmd.Flags().StringSlice("env", test.input, "") - - envStrings := cmdutil.GetFlagStringSlice(cmd, "env") - if len(envStrings) != 2 || !reflect.DeepEqual(envStrings, test.expected) { - t.Errorf("expected: %s, saw: %s", test.expected, envStrings) - } -} - -func TestRunArgsFollowDashRules(t *testing.T) { - _, _, rc := testData() - - tests := []struct { - args []string - argsLenAtDash int - expectError bool - name string - }{ - { - args: []string{}, - argsLenAtDash: -1, - expectError: true, - name: "empty", - }, - { - args: []string{"foo"}, - argsLenAtDash: -1, - expectError: false, - name: "no cmd", - }, - { - args: []string{"foo", "sleep"}, - argsLenAtDash: -1, - expectError: false, - name: "cmd no dash", - }, - { - args: []string{"foo", "sleep"}, - argsLenAtDash: 1, - expectError: false, - name: "cmd has dash", - }, - { - args: []string{"foo", "sleep"}, - argsLenAtDash: 0, - expectError: true, - name: "no name", - }, - } - for _, test := range tests { - f, tf, codec := NewAPIFactory() - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil - }), - } - tf.Namespace = "test" - tf.ClientConfig = &client.Config{} - cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) - cmd.Flags().Set("image", "nginx") - cmd.Flags().Set("generator", "run/v1") - err := Run(f, os.Stdin, os.Stdout, os.Stderr, cmd, test.args, test.argsLenAtDash) - if test.expectError && err == nil { - t.Errorf("unexpected non-error (%s)", test.name) - } - if !test.expectError && err != nil { - t.Errorf("unexpected error: %v (%s)", err, test.name) - } - } -} - -func TestGenerateService(t *testing.T) { - - tests := []struct { - port string - args []string - serviceGenerator string - params map[string]interface{} - expectErr bool - name string - service api.Service - expectPOST bool - }{ - { - port: "80", - args: []string{"foo"}, - serviceGenerator: "service/v2", - params: map[string]interface{}{ - "name": "foo", - }, - expectErr: false, - name: "basic", - service: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - TargetPort: intstr.FromInt(80), - }, - }, - Selector: map[string]string{ - "run": "foo", - }, - Type: api.ServiceTypeClusterIP, - SessionAffinity: api.ServiceAffinityNone, - }, - }, - expectPOST: true, - }, - { - port: "80", - args: []string{"foo"}, - serviceGenerator: "service/v2", - params: map[string]interface{}{ - "name": "foo", - "labels": "app=bar", - }, - expectErr: false, - name: "custom labels", - service: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"app": "bar"}, - }, - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - TargetPort: intstr.FromInt(80), - }, - }, - Selector: map[string]string{ - "app": "bar", - }, - Type: api.ServiceTypeClusterIP, - SessionAffinity: api.ServiceAffinityNone, - }, - }, - expectPOST: true, - }, - { - expectErr: true, - name: "missing port", - expectPOST: false, - }, - { - port: "80", - args: []string{"foo"}, - serviceGenerator: "service/v2", - params: map[string]interface{}{ - "name": "foo", - }, - expectErr: false, - name: "dry-run", - expectPOST: false, - }, - } - for _, test := range tests { - sawPOST := false - f, tf, codec := NewAPIFactory() - tf.ClientConfig = &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - tf.Client = &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case test.expectPOST && m == "POST" && p == "/namespaces/namespace/services": - sawPOST = true - body := objBody(codec, &test.service) - data, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.FailNow() - } - defer req.Body.Close() - svc := &api.Service{} - if err := runtime.DecodeInto(codec, data, svc); err != nil { - t.Errorf("unexpected error: %v", err) - t.FailNow() - } - // Copy things that are defaulted by the system - test.service.Annotations = svc.Annotations - - if !reflect.DeepEqual(&test.service, svc) { - t.Errorf("expected:\n%v\nsaw:\n%v\n", &test.service, svc) - } - return &http.Response{StatusCode: 200, Body: body}, nil - default: - // Ensures no GET is performed when deleting by name - t.Errorf("%s: unexpected request: %s %#v\n%#v", test.name, req.Method, req.URL, req) - return nil, fmt.Errorf("unexpected request") - } - }), - } - cmd := &cobra.Command{} - cmd.Flags().String("output", "", "") - cmd.Flags().Bool(cmdutil.ApplyAnnotationsFlag, false, "") - cmd.Flags().Bool("record", false, "Record current kubectl command in the resource annotation.") - addRunFlags(cmd) - - if !test.expectPOST { - cmd.Flags().Set("dry-run", "true") - } - - if len(test.port) > 0 { - cmd.Flags().Set("port", test.port) - test.params["port"] = test.port - } - - buff := &bytes.Buffer{} - err := generateService(f, cmd, test.args, test.serviceGenerator, test.params, "namespace", buff) - if test.expectErr { - if err == nil { - t.Error("unexpected non-error") - } - continue - } - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectPOST != sawPOST { - t.Error("expectPost: %v, sawPost: %v", test.expectPOST, sawPOST) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/scale.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/scale.go deleted file mode 100644 index 6ffd43566..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/scale.go +++ /dev/null @@ -1,176 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - "os" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" - utilerrors "k8s.io/kubernetes/pkg/util/errors" -) - -// ScaleOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type ScaleOptions struct { - Filenames []string -} - -const ( - scale_long = `Set a new size for a Replication Controller, Job, or Deployment. - -Scale also allows users to specify one or more preconditions for the scale action. -If --current-replicas or --resource-version is specified, it is validated before the -scale is attempted, and it is guaranteed that the precondition holds true when the -scale is sent to the server.` - scale_example = `# Scale replication controller named 'foo' to 3. -$ kubectl scale --replicas=3 rc/foo - -# Scale a resource identified by type and name specified in "foo.yaml" to 3. -$ kubectl scale --replicas=3 -f foo.yaml - -# If the deployment named mysql's current size is 2, scale mysql to 3. -$ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql - -# Scale multiple replication controllers. -$ kubectl scale --replicas=5 rc/foo rc/bar rc/baz - -# Scale job named 'cron' to 3. -$ kubectl scale --replicas=3 job/cron` -) - -// NewCmdScale returns a cobra command with the appropriate configuration and flags to run scale -func NewCmdScale(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &ScaleOptions{} - - cmd := &cobra.Command{ - Use: "scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)", - // resize is deprecated - Aliases: []string{"resize"}, - Short: "Set a new size for a Replication Controller, Job, or Deployment.", - Long: scale_long, - Example: scale_example, - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) - shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" - err := RunScale(f, out, cmd, args, shortOutput, options) - cmdutil.CheckErr(err) - }, - } - cmd.Flags().String("resource-version", "", "Precondition for resource version. Requires that the current resource version match this value in order to scale.") - cmd.Flags().Int("current-replicas", -1, "Precondition for current size. Requires that the current size of the resource match this value in order to scale.") - cmd.Flags().Int("replicas", -1, "The new desired number of replicas. Required.") - cmd.MarkFlagRequired("replicas") - cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a scale operation, zero means don't wait.") - cmdutil.AddOutputFlagsForMutation(cmd) - cmdutil.AddRecordFlag(cmd) - - usage := "Filename, directory, or URL to a file identifying the resource to set a new size" - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - return cmd -} - -// RunScale executes the scaling -func RunScale(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *ScaleOptions) error { - if len(os.Args) > 1 && os.Args[1] == "resize" { - printDeprecationWarning("scale", "resize") - } - - count := cmdutil.GetFlagInt(cmd, "replicas") - if count < 0 { - return cmdutil.UsageError(cmd, "--replicas=COUNT is required, and COUNT must be greater than or equal to 0") - } - - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - FilenameParam(enforceNamespace, options.Filenames...). - ResourceTypeOrNameArgs(false, args...). - Flatten(). - Do() - err = r.Err() - if err != nil { - return err - } - - infos, err := r.Infos() - if err != nil { - return err - } - info := infos[0] - mapping := info.ResourceMapping() - scaler, err := f.Scaler(mapping) - if err != nil { - return err - } - - resourceVersion := cmdutil.GetFlagString(cmd, "resource-version") - if len(resourceVersion) != 0 && len(infos) > 1 { - return fmt.Errorf("cannot use --resource-version with multiple resources") - } - currentSize := cmdutil.GetFlagInt(cmd, "current-replicas") - if currentSize != -1 && len(infos) > 1 { - return fmt.Errorf("cannot use --current-replicas with multiple resources") - } - precondition := &kubectl.ScalePrecondition{Size: currentSize, ResourceVersion: resourceVersion} - retry := kubectl.NewRetryParams(kubectl.Interval, kubectl.Timeout) - var waitForReplicas *kubectl.RetryParams - if timeout := cmdutil.GetFlagDuration(cmd, "timeout"); timeout != 0 { - waitForReplicas = kubectl.NewRetryParams(kubectl.Interval, timeout) - } - - errs := []error{} - for _, info := range infos { - if err := scaler.Scale(info.Namespace, info.Name, uint(count), precondition, retry, waitForReplicas); err != nil { - errs = append(errs, err) - continue - } - if cmdutil.ShouldRecord(cmd, info) { - patchBytes, err := cmdutil.ChangeResourcePatch(info, f.Command()) - if err != nil { - errs = append(errs, err) - continue - } - mapping := info.ResourceMapping() - client, err := f.ClientForMapping(mapping) - if err != nil { - return err - } - helper := resource.NewHelper(client, mapping) - _, err = helper.Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patchBytes) - if err != nil { - errs = append(errs, err) - continue - } - } - cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "scaled") - } - - return utilerrors.NewAggregate(errs) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/stop.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/stop.go deleted file mode 100644 index 606986617..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/stop.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "fmt" - "io" - - "github.com/spf13/cobra" - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" - "k8s.io/kubernetes/pkg/kubectl/resource" -) - -// StopOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of -// referencing the cmd.Flags() -type StopOptions struct { - Filenames []string -} - -const ( - stop_long = `Deprecated: Gracefully shut down a resource by name or filename. - -The stop command is deprecated, all its functionalities are covered by delete command. -See 'kubectl delete --help' for more details. - -Attempts to shut down and delete a resource that supports graceful termination. -If the resource is scalable it will be scaled to 0 before deletion.` - stop_example = `# Shut down foo. -$ kubectl stop replicationcontroller foo - -# Stop pods and services with label name=myLabel. -$ kubectl stop pods,services -l name=myLabel - -# Shut down the service defined in service.json -$ kubectl stop -f service.json - -# Shut down all resources in the path/to/resources directory -$ kubectl stop -f path/to/resources` -) - -func NewCmdStop(f *cmdutil.Factory, out io.Writer) *cobra.Command { - options := &StopOptions{} - - cmd := &cobra.Command{ - Use: "stop (-f FILENAME | TYPE (NAME | -l label | --all))", - Short: "Deprecated: Gracefully shut down a resource by name or filename.", - Long: stop_long, - Example: stop_example, - Deprecated: fmt.Sprintf("use %q instead.", "delete"), - Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd)) - cmdutil.CheckErr(RunStop(f, cmd, args, out, options)) - }, - } - usage := "Filename, directory, or URL to file of resource(s) to be stopped." - kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage) - cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on.") - cmd.Flags().Bool("all", false, "[-all] to select all the specified resources.") - cmd.Flags().Bool("ignore-not-found", false, "Treat \"resource not found\" as a successful stop.") - cmd.Flags().Int("grace-period", -1, "Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.") - cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object") - cmdutil.AddOutputFlagsForMutation(cmd) - return cmd -} - -func RunStop(f *cmdutil.Factory, cmd *cobra.Command, args []string, out io.Writer, options *StopOptions) error { - cmdNamespace, enforceNamespace, err := f.DefaultNamespace() - if err != nil { - return err - } - - mapper, typer := f.Object() - r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). - ContinueOnError(). - NamespaceParam(cmdNamespace).DefaultNamespace(). - ResourceTypeOrNameArgs(false, args...). - FilenameParam(enforceNamespace, options.Filenames...). - SelectorParam(cmdutil.GetFlagString(cmd, "selector")). - SelectAllParam(cmdutil.GetFlagBool(cmd, "all")). - Flatten(). - Do() - if r.Err() != nil { - return r.Err() - } - shortOutput := cmdutil.GetFlagString(cmd, "output") == "name" - return ReapResult(r, f, out, false, cmdutil.GetFlagBool(cmd, "ignore-not-found"), cmdutil.GetFlagDuration(cmd, "timeout"), cmdutil.GetFlagInt(cmd, "grace-period"), shortOutput, mapper) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go index 523c57750..5e6551cde 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go @@ -19,6 +19,7 @@ package util import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apimachinery/registered" + "k8s.io/kubernetes/pkg/client/restclient" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" ) @@ -26,7 +27,7 @@ import ( func NewClientCache(loader clientcmd.ClientConfig) *ClientCache { return &ClientCache{ clients: make(map[unversioned.GroupVersion]*client.Client), - configs: make(map[unversioned.GroupVersion]*client.Config), + configs: make(map[unversioned.GroupVersion]*restclient.Config), loader: loader, } } @@ -36,14 +37,14 @@ func NewClientCache(loader clientcmd.ClientConfig) *ClientCache { type ClientCache struct { loader clientcmd.ClientConfig clients map[unversioned.GroupVersion]*client.Client - configs map[unversioned.GroupVersion]*client.Config - defaultConfig *client.Config + configs map[unversioned.GroupVersion]*restclient.Config + defaultConfig *restclient.Config defaultClient *client.Client matchVersion bool } // ClientConfigForVersion returns the correct config for a server -func (c *ClientCache) ClientConfigForVersion(version *unversioned.GroupVersion) (*client.Config, error) { +func (c *ClientCache) ClientConfigForVersion(version *unversioned.GroupVersion) (*restclient.Config, error) { if c.defaultConfig == nil { config, err := c.loader.ClientConfig() if err != nil { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/editor.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/editor.go deleted file mode 100644 index f77f8e137..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/editor.go +++ /dev/null @@ -1,226 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package editor - -import ( - "fmt" - "io" - "io/ioutil" - "math/rand" - "os" - "os/exec" - "os/signal" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/docker/pkg/term" - "github.com/golang/glog" -) - -const ( - // sorry, blame Git - // TODO: on Windows rely on 'start' to launch the editor associated - // with the given file type. If we can't because of the need of - // blocking, use a script with 'ftype' and 'assoc' to detect it. - defaultEditor = "vi" - defaultShell = "/bin/bash" - windowsEditor = "notepad" - windowsShell = "cmd" -) - -type Editor struct { - Args []string - Shell bool -} - -// NewDefaultEditor creates a struct Editor that uses the OS environment to -// locate the editor program, looking at EDITOR environment variable to find -// the proper command line. If the provided editor has no spaces, or no quotes, -// it is treated as a bare command to be loaded. Otherwise, the string will -// be passed to the user's shell for execution. -func NewDefaultEditor(envs []string) Editor { - args, shell := defaultEnvEditor(envs) - return Editor{ - Args: args, - Shell: shell, - } -} - -func defaultEnvShell() []string { - shell := os.Getenv("SHELL") - if len(shell) == 0 { - shell = platformize(defaultShell, windowsShell) - } - flag := "-c" - if shell == windowsShell { - flag = "/C" - } - return []string{shell, flag} -} - -func defaultEnvEditor(envs []string) ([]string, bool) { - var editor string - for _, env := range envs { - if len(env) > 0 { - editor = os.Getenv(env) - } - if len(editor) > 0 { - break - } - } - if len(editor) == 0 { - editor = platformize(defaultEditor, windowsEditor) - } - if !strings.Contains(editor, " ") { - return []string{editor}, false - } - if !strings.ContainsAny(editor, "\"'\\") { - return strings.Split(editor, " "), false - } - // rather than parse the shell arguments ourselves, punt to the shell - shell := defaultEnvShell() - return append(shell, editor), true -} - -func (e Editor) args(path string) []string { - args := make([]string, len(e.Args)) - copy(args, e.Args) - if e.Shell { - last := args[len(args)-1] - args[len(args)-1] = fmt.Sprintf("%s %q", last, path) - } else { - args = append(args, path) - } - return args -} - -// Launch opens the described or returns an error. The TTY will be protected, and -// SIGQUIT, SIGTERM, and SIGINT will all be trapped. -func (e Editor) Launch(path string) error { - if len(e.Args) == 0 { - return fmt.Errorf("no editor defined, can't open %s", path) - } - abs, err := filepath.Abs(path) - if err != nil { - return err - } - args := e.args(abs) - cmd := exec.Command(args[0], args[1:]...) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - cmd.Stdin = os.Stdin - glog.V(5).Infof("Opening file with editor %v", args) - if err := withSafeTTYAndInterrupts(cmd.Run); err != nil { - if err, ok := err.(*exec.Error); ok { - if err.Err == exec.ErrNotFound { - return fmt.Errorf("unable to launch the editor %q", strings.Join(e.Args, " ")) - } - } - return fmt.Errorf("there was a problem with the editor %q", strings.Join(e.Args, " ")) - } - return nil -} - -// LaunchTempFile reads the provided stream into a temporary file in the given directory -// and file prefix, and then invokes Launch with the path of that file. It will return -// the contents of the file after launch, any errors that occur, and the path of the -// temporary file so the caller can clean it up as needed. -func (e Editor) LaunchTempFile(prefix, suffix string, r io.Reader) ([]byte, string, error) { - f, err := tempFile(prefix, suffix) - if err != nil { - return nil, "", err - } - defer f.Close() - path := f.Name() - if _, err := io.Copy(f, r); err != nil { - os.Remove(path) - return nil, path, err - } - // This file descriptor needs to close so the next process (Launch) can claim it. - f.Close() - if err := e.Launch(path); err != nil { - return nil, path, err - } - bytes, err := ioutil.ReadFile(path) - return bytes, path, err -} - -// withSafeTTYAndInterrupts invokes the provided function after the terminal -// state has been stored, and then on any error or termination attempts to -// restore the terminal state to its prior behavior. It also eats signals -// for the duration of the function. -func withSafeTTYAndInterrupts(fn func() error) error { - ch := make(chan os.Signal, 1) - signal.Notify(ch, childSignals...) - defer signal.Stop(ch) - - inFd := os.Stdin.Fd() - if !term.IsTerminal(inFd) { - if f, err := os.Open("/dev/tty"); err == nil { - defer f.Close() - inFd = f.Fd() - } - } - - if term.IsTerminal(inFd) { - state, err := term.SaveState(inFd) - if err != nil { - return err - } - go func() { - if _, ok := <-ch; !ok { - return - } - term.RestoreTerminal(inFd, state) - }() - defer term.RestoreTerminal(inFd, state) - return fn() - } - return fn() -} - -func tempFile(prefix, suffix string) (f *os.File, err error) { - dir := os.TempDir() - - for i := 0; i < 10000; i++ { - name := filepath.Join(dir, prefix+randSeq(5)+suffix) - f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - continue - } - break - } - return -} - -var letters = []rune("abcdefghijklmnopqrstuvwxyz0123456789") - -func randSeq(n int) string { - b := make([]rune, n) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - return string(b) -} - -func platformize(linux, windows string) string { - if runtime.GOOS == "windows" { - return windows - } - return linux -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/editor_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/editor_test.go deleted file mode 100644 index 9be83a042..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/editor_test.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package editor - -import ( - "bytes" - "io/ioutil" - "os" - "reflect" - "strings" - "testing" -) - -func TestArgs(t *testing.T) { - if e, a := []string{"/bin/bash", "-c \"test\""}, (Editor{Args: []string{"/bin/bash", "-c"}, Shell: true}).args("test"); !reflect.DeepEqual(e, a) { - t.Errorf("unexpected args: %v", a) - } - if e, a := []string{"/bin/bash", "-c", "test"}, (Editor{Args: []string{"/bin/bash", "-c"}, Shell: false}).args("test"); !reflect.DeepEqual(e, a) { - t.Errorf("unexpected args: %v", a) - } - if e, a := []string{"/bin/bash", "-i -c \"test\""}, (Editor{Args: []string{"/bin/bash", "-i -c"}, Shell: true}).args("test"); !reflect.DeepEqual(e, a) { - t.Errorf("unexpected args: %v", a) - } - if e, a := []string{"/test", "test"}, (Editor{Args: []string{"/test"}}).args("test"); !reflect.DeepEqual(e, a) { - t.Errorf("unexpected args: %v", a) - } -} - -func TestEditor(t *testing.T) { - edit := Editor{Args: []string{"cat"}} - testStr := "test something\n" - contents, path, err := edit.LaunchTempFile("", "someprefix", bytes.NewBufferString(testStr)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, err := os.Stat(path); err != nil { - t.Fatalf("no temp file: %s", path) - } - defer os.Remove(path) - if disk, err := ioutil.ReadFile(path); err != nil || !bytes.Equal(contents, disk) { - t.Errorf("unexpected file on disk: %v %s", err, string(disk)) - } - if !bytes.Equal(contents, []byte(testStr)) { - t.Errorf("unexpected contents: %s", string(contents)) - } - if !strings.Contains(path, "someprefix") { - t.Errorf("path not expected: %s", path) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/term_unsupported.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/term_unsupported.go deleted file mode 100644 index 4c0b78816..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/editor/term_unsupported.go +++ /dev/null @@ -1,26 +0,0 @@ -// +build windows - -/* -Copyright 2015 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. -*/ - -package editor - -import ( - "os" -) - -// childSignals are the allowed signals that can be sent to children in Windows to terminate -var childSignals = []os.Signal{os.Interrupt} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory.go index ca6413b75..78b2503b4 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory.go @@ -26,6 +26,7 @@ import ( "os" "os/user" "path" + "path/filepath" "strconv" "strings" "time" @@ -40,8 +41,11 @@ import ( "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/autoscaling" + "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/apis/metrics" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/client/restclient" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" "k8s.io/kubernetes/pkg/kubectl" @@ -64,7 +68,6 @@ const ( type Factory struct { clients *ClientCache flags *pflag.FlagSet - cmd string // Returns interfaces for dealing with arbitrary runtime.Objects. Object func() (meta.RESTMapper, runtime.ObjectTyper) @@ -77,7 +80,7 @@ type Factory struct { // Returns a client for accessing Kubernetes resources or an error. Client func() (*client.Client, error) // Returns a client.Config for accessing the Kubernetes server. - ClientConfig func() (*client.Config, error) + ClientConfig func() (*restclient.Config, error) // Returns a RESTClient for working with the specified RESTMapping or an error. This is intended // for working with arbitrary resources and is not guaranteed to point to a Kubernetes APIServer. ClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error) @@ -104,7 +107,7 @@ type Factory struct { // LabelsForObject returns the labels associated with the provided object LabelsForObject func(object runtime.Object) (map[string]string, error) // LogsForObject returns a request for the logs associated with the provided object - LogsForObject func(object, options runtime.Object) (*client.Request, error) + LogsForObject func(object, options runtime.Object) (*restclient.Request, error) // PauseObject marks the provided object as paused ie. it will not be reconciled by its controller. PauseObject func(object runtime.Object) (bool, error) // ResumeObject resumes a paused object ie. it will be reconciled by its controller. @@ -136,9 +139,11 @@ const ( RunPodV1GeneratorName = "run-pod/v1" ServiceV1GeneratorName = "service/v1" ServiceV2GeneratorName = "service/v2" + ServiceAccountV1GeneratorName = "serviceaccount/v1" HorizontalPodAutoscalerV1Beta1GeneratorName = "horizontalpodautoscaler/v1beta1" DeploymentV1Beta1GeneratorName = "deployment/v1beta1" JobV1Beta1GeneratorName = "job/v1beta1" + JobV1GeneratorName = "job/v1" NamespaceV1GeneratorName = "namespace/v1" SecretV1GeneratorName = "secret/v1" SecretForDockerRegistryV1GeneratorName = "secret-for-docker-registry/v1" @@ -157,6 +162,7 @@ func DefaultGenerators(cmdName string) map[string]kubectl.Generator { RunPodV1GeneratorName: kubectl.BasicPod{}, DeploymentV1Beta1GeneratorName: kubectl.DeploymentV1Beta1{}, JobV1Beta1GeneratorName: kubectl.JobV1Beta1{}, + JobV1GeneratorName: kubectl.JobV1{}, } generators["autoscale"] = map[string]kubectl.Generator{ HorizontalPodAutoscalerV1Beta1GeneratorName: kubectl.HorizontalPodAutoscalerV1Beta1{}, @@ -192,7 +198,6 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { return &Factory{ clients: clients, flags: flags, - cmd: recordCommand(os.Args), Object: func() (meta.RESTMapper, runtime.ObjectTyper) { cfg, err := clientConfig.ClientConfig() @@ -202,12 +207,29 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { cmdApiVersion = *cfg.GroupVersion } - return kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersions: []unversioned.GroupVersion{cmdApiVersion}}, api.Scheme + outputRESTMapper := kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersions: []unversioned.GroupVersion{cmdApiVersion}} + + // eventually this should allow me choose a group priority based on the order of the discovery doc, for now hardcode a given order + priorityRESTMapper := meta.PriorityRESTMapper{ + Delegate: outputRESTMapper, + ResourcePriority: []unversioned.GroupVersionResource{ + {Group: api.GroupName, Version: meta.AnyVersion, Resource: meta.AnyResource}, + {Group: extensions.GroupName, Version: meta.AnyVersion, Resource: meta.AnyResource}, + {Group: metrics.GroupName, Version: meta.AnyVersion, Resource: meta.AnyResource}, + }, + KindPriority: []unversioned.GroupVersionKind{ + {Group: api.GroupName, Version: meta.AnyVersion, Kind: meta.AnyKind}, + {Group: extensions.GroupName, Version: meta.AnyVersion, Kind: meta.AnyKind}, + {Group: metrics.GroupName, Version: meta.AnyVersion, Kind: meta.AnyKind}, + }, + } + + return priorityRESTMapper, api.Scheme }, Client: func() (*client.Client, error) { return clients.ClientForVersion(nil) }, - ClientConfig: func() (*client.Config, error) { + ClientConfig: func() (*restclient.Config, error) { return clients.ClientConfigForVersion(nil) }, ClientForMapping: func(mapping *meta.RESTMapping) (resource.RESTClient, error) { @@ -221,6 +243,8 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { return client.RESTClient, nil case autoscaling.GroupName: return client.AutoscalingClient.RESTClient, nil + case batch.GroupName: + return client.BatchClient.RESTClient, nil case extensions.GroupName: return client.ExtensionsClient.RESTClient, nil } @@ -345,7 +369,7 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { LabelsForObject: func(object runtime.Object) (map[string]string, error) { return meta.NewAccessor().Labels(object) }, - LogsForObject: func(object, options runtime.Object) (*client.Request, error) { + LogsForObject: func(object, options runtime.Object) (*restclient.Request, error) { c, err := clients.ClientForVersion(nil) if err != nil { return nil, err @@ -358,6 +382,42 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { return nil, errors.New("provided options object is not a PodLogOptions") } return c.Pods(t.Namespace).GetLogs(t.Name, opts), nil + + case *api.ReplicationController: + opts, ok := options.(*api.PodLogOptions) + if !ok { + return nil, errors.New("provided options object is not a PodLogOptions") + } + selector := labels.SelectorFromSet(t.Spec.Selector) + pod, numPods, err := GetFirstPod(c, t.Namespace, selector) + if err != nil { + return nil, err + } + if numPods > 1 { + fmt.Fprintf(os.Stderr, "Found %v pods, using pod/%v\n", numPods, pod.Name) + } + + return c.Pods(pod.Namespace).GetLogs(pod.Name, opts), nil + + case *extensions.ReplicaSet: + opts, ok := options.(*api.PodLogOptions) + if !ok { + return nil, errors.New("provided options object is not a PodLogOptions") + } + selector, err := unversioned.LabelSelectorAsSelector(t.Spec.Selector) + if err != nil { + return nil, fmt.Errorf("invalid label selector: %v", err) + } + pod, numPods, err := GetFirstPod(c, t.Namespace, selector) + if err != nil { + return nil, err + } + if numPods > 1 { + fmt.Fprintf(os.Stderr, "Found %v pods, using pod/%v\n", numPods, pod.Name) + } + + return c.Pods(pod.Namespace).GetLogs(pod.Name, opts), nil + default: gvk, err := api.Scheme.ObjectKind(object) if err != nil { @@ -490,7 +550,7 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { }, CanBeAutoscaled: func(kind unversioned.GroupKind) error { switch kind { - case api.Kind("ReplicationController"), extensions.Kind("Deployment"): + case api.Kind("ReplicationController"), extensions.Kind("Deployment"), extensions.Kind("ReplicaSet"): // nothing to do here default: return fmt.Errorf("cannot autoscale a %v", kind) @@ -505,19 +565,22 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { switch t := object.(type) { case *api.ReplicationController: selector := labels.SelectorFromSet(t.Spec.Selector) - return GetFirstPod(client, t.Namespace, selector) + pod, _, err := GetFirstPod(client, t.Namespace, selector) + return pod, err case *extensions.Deployment: selector, err := unversioned.LabelSelectorAsSelector(t.Spec.Selector) if err != nil { return nil, fmt.Errorf("invalid label selector: %v", err) } - return GetFirstPod(client, t.Namespace, selector) + pod, _, err := GetFirstPod(client, t.Namespace, selector) + return pod, err case *extensions.Job: selector, err := unversioned.LabelSelectorAsSelector(t.Spec.Selector) if err != nil { return nil, fmt.Errorf("invalid label selector: %v", err) } - return GetFirstPod(client, t.Namespace, selector) + pod, _, err := GetFirstPod(client, t.Namespace, selector) + return pod, err case *api.Pod: return t, nil default: @@ -534,39 +597,37 @@ func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory { } } -// GetFirstPod returns the first pod of an object from its namespace and selector -func GetFirstPod(client *client.Client, namespace string, selector labels.Selector) (*api.Pod, error) { +// GetFirstPod returns the first pod of an object from its namespace and selector and the number of matching pods +func GetFirstPod(client *client.Client, namespace string, selector labels.Selector) (*api.Pod, int, error) { var pods *api.PodList for pods == nil || len(pods.Items) == 0 { var err error options := api.ListOptions{LabelSelector: selector} if pods, err = client.Pods(namespace).List(options); err != nil { - return nil, err + return nil, 0, err } if len(pods.Items) == 0 { time.Sleep(2 * time.Second) } } pod := &pods.Items[0] - return pod, nil -} - -func recordCommand(args []string) string { - if len(args) > 0 { - args[0] = "kubectl" - } - return strings.Join(args, " ") + return pod, len(pods.Items), nil } +// Command will stringify and return all environment arguments ie. a command run by a client +// using the factory. +// TODO: We need to filter out stuff like secrets. func (f *Factory) Command() string { - return f.cmd + if len(os.Args) == 0 { + return "" + } + base := filepath.Base(os.Args[0]) + args := append([]string{base}, os.Args[1:]...) + return strings.Join(args, " ") } // BindFlags adds any flags that are common to all kubectl sub commands. func (f *Factory) BindFlags(flags *pflag.FlagSet) { - // any flags defined by external projects (not part of pflags) - flags.AddGoFlagSet(flag.CommandLine) - // Merge factory's flags flags.AddFlagSet(f.flags) @@ -581,6 +642,12 @@ func (f *Factory) BindFlags(flags *pflag.FlagSet) { flags.SetNormalizeFunc(util.WordSepNormalizeFunc) } +// BindCommonFlags adds any flags defined by external projects (not part of pflags) +func (f *Factory) BindExternalFlags(flags *pflag.FlagSet) { + // any flags defined by external projects (not part of pflags) + flags.AddGoFlagSet(flag.CommandLine) +} + func getPorts(spec api.PodSpec) []string { result := []string{} for _, container := range spec.Containers { @@ -609,7 +676,7 @@ type clientSwaggerSchema struct { const schemaFileName = "schema.json" type schemaClient interface { - Get() *client.Request + Get() *restclient.Request } func recursiveSplit(dir string) []string { @@ -664,6 +731,7 @@ func writeSchemaFile(schemaData []byte, cacheDir, cacheFile, prefix, groupVersio func getSchemaAndValidate(c schemaClient, data []byte, prefix, groupVersion, cacheDir string) (err error) { var schemaData []byte + var firstSeen bool fullDir, err := substituteUserHome(cacheDir) if err != nil { return err @@ -676,24 +744,50 @@ func getSchemaAndValidate(c schemaClient, data []byte, prefix, groupVersion, cac } } if schemaData == nil { - schemaData, err = c.Get(). - AbsPath("/swaggerapi", prefix, groupVersion). - Do(). - Raw() + firstSeen = true + schemaData, err = downloadSchemaAndStore(c, cacheDir, fullDir, cacheFile, prefix, groupVersion) if err != nil { return err } - if len(cacheDir) != 0 { - if err := writeSchemaFile(schemaData, fullDir, cacheFile, prefix, groupVersion); err != nil { - return err - } - } } schema, err := validation.NewSwaggerSchemaFromBytes(schemaData) if err != nil { return err } - return schema.ValidateBytes(data) + err = schema.ValidateBytes(data) + if _, ok := err.(validation.TypeNotFoundError); ok && !firstSeen { + // As a temporay hack, kubectl would re-get the schema if validation + // fails for type not found reason. + // TODO: runtime-config settings needs to make into the file's name + schemaData, err = downloadSchemaAndStore(c, cacheDir, fullDir, cacheFile, prefix, groupVersion) + if err != nil { + return err + } + schema, err := validation.NewSwaggerSchemaFromBytes(schemaData) + if err != nil { + return err + } + return schema.ValidateBytes(data) + } + + return err +} + +// Download swagger schema from apiserver and store it to file. +func downloadSchemaAndStore(c schemaClient, cacheDir, fullDir, cacheFile, prefix, groupVersion string) (schemaData []byte, err error) { + schemaData, err = c.Get(). + AbsPath("/swaggerapi", prefix, groupVersion). + Do(). + Raw() + if err != nil { + return + } + if len(cacheDir) != 0 { + if err = writeSchemaFile(schemaData, fullDir, cacheFile, prefix, groupVersion); err != nil { + return + } + } + return } func (c *clientSwaggerSchema) ValidateBytes(data []byte) error { @@ -710,6 +804,12 @@ func (c *clientSwaggerSchema) ValidateBytes(data []byte) error { } return getSchemaAndValidate(c.c.AutoscalingClient.RESTClient, data, "apis/", gvk.GroupVersion().String(), c.cacheDir) } + if gvk.Group == batch.GroupName { + if c.c.BatchClient == nil { + return errors.New("unable to validate: no batch client") + } + return getSchemaAndValidate(c.c.BatchClient.RESTClient, data, "apis/", gvk.GroupVersion().String(), c.cacheDir) + } if gvk.Group == extensions.GroupName { if c.c.ExtensionsClient == nil { return errors.New("unable to validate: no experimental client") diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory_test.go deleted file mode 100644 index be9484fae..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/factory_test.go +++ /dev/null @@ -1,338 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package util - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - "os" - "os/user" - "path" - "sort" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" - clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/kubectl" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" -) - -func TestNewFactoryDefaultFlagBindings(t *testing.T) { - factory := NewFactory(nil) - - if !factory.flags.HasFlags() { - t.Errorf("Expected flags, but didn't get any") - } -} - -func TestNewFactoryNoFlagBindings(t *testing.T) { - clientConfig := clientcmd.NewDefaultClientConfig(*clientcmdapi.NewConfig(), &clientcmd.ConfigOverrides{}) - factory := NewFactory(clientConfig) - - if factory.flags.HasFlags() { - t.Errorf("Expected zero flags, but got %v", factory.flags) - } -} - -func TestPodSelectorForObject(t *testing.T) { - f := NewFactory(nil) - - svc := &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test"}, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - }, - }, - } - - expected := "foo=bar" - got, err := f.PodSelectorForObject(svc) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if expected != got { - t.Fatalf("Selector mismatch! Expected %s, got %s", expected, got) - } -} - -func TestPortsForObject(t *testing.T) { - f := NewFactory(nil) - - pod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Ports: []api.ContainerPort{ - { - ContainerPort: 101, - }, - }, - }, - }, - }, - } - - expected := []string{"101"} - got, err := f.PortsForObject(pod) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(expected) != len(got) { - t.Fatalf("Ports size mismatch! Expected %d, got %d", len(expected), len(got)) - } - - sort.Strings(expected) - sort.Strings(got) - - for i, port := range got { - if port != expected[i] { - t.Fatalf("Port mismatch! Expected %s, got %s", expected[i], port) - } - } -} - -func TestLabelsForObject(t *testing.T) { - f := NewFactory(nil) - - tests := []struct { - name string - object runtime.Object - expected string - err error - }{ - { - name: "successful re-use of labels", - object: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", Labels: map[string]string{"svc": "test"}}, - TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"}, - }, - expected: "svc=test", - err: nil, - }, - { - name: "empty labels", - object: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", Labels: map[string]string{}}, - TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"}, - }, - expected: "", - err: nil, - }, - { - name: "nil labels", - object: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "zen", Namespace: "test", Labels: nil}, - TypeMeta: unversioned.TypeMeta{Kind: "Service", APIVersion: "v1"}, - }, - expected: "", - err: nil, - }, - } - - for _, test := range tests { - gotLabels, err := f.LabelsForObject(test.object) - if err != test.err { - t.Fatalf("%s: Error mismatch: Expected %v, got %v", test.name, test.err, err) - } - got := kubectl.MakeLabels(gotLabels) - if test.expected != got { - t.Fatalf("%s: Labels mismatch! Expected %s, got %s", test.name, test.expected, got) - } - - } -} - -func TestCanBeExposed(t *testing.T) { - factory := NewFactory(nil) - tests := []struct { - kind unversioned.GroupKind - expectErr bool - }{ - { - kind: api.Kind("ReplicationController"), - expectErr: false, - }, - { - kind: api.Kind("Node"), - expectErr: true, - }, - } - - for _, test := range tests { - err := factory.CanBeExposed(test.kind) - if test.expectErr && err == nil { - t.Error("unexpected non-error") - } - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - } -} - -func TestFlagUnderscoreRenaming(t *testing.T) { - factory := NewFactory(nil) - - factory.flags.SetNormalizeFunc(util.WordSepNormalizeFunc) - factory.flags.Bool("valid_flag", false, "bool value") - - // In case of failure of this test check this PR: spf13/pflag#23 - if factory.flags.Lookup("valid_flag").Name != "valid-flag" { - t.Fatalf("Expected flag name to be valid-flag, got %s", factory.flags.Lookup("valid_flag").Name) - } -} - -func loadSchemaForTest() (validation.Schema, error) { - pathToSwaggerSpec := "../../../../api/swagger-spec/" + testapi.Default.GroupVersion().Version + ".json" - data, err := ioutil.ReadFile(pathToSwaggerSpec) - if err != nil { - return nil, err - } - return validation.NewSwaggerSchemaFromBytes(data) -} - -func TestValidateCachesSchema(t *testing.T) { - schema, err := loadSchemaForTest() - if err != nil { - t.Errorf("Error loading schema: %v", err) - t.FailNow() - } - output, err := json.Marshal(schema) - if err != nil { - t.Errorf("Error serializing schema: %v", err) - t.FailNow() - } - requests := map[string]int{} - - c := &fake.RESTClient{ - Codec: testapi.Default.Codec(), - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case strings.HasPrefix(p, "/swaggerapi") && m == "GET": - requests[p] = requests[p] + 1 - return &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewBuffer(output))}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - dir := os.TempDir() + "/schemaCache" - os.RemoveAll(dir) - - obj := &api.Pod{} - data, err := runtime.Encode(testapi.Default.Codec(), obj) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.FailNow() - } - - // Initial request, should use HTTP and write - if getSchemaAndValidate(c, data, "foo", "bar", dir); err != nil { - t.Errorf("unexpected error validating: %v", err) - } - if _, err := os.Stat(path.Join(dir, "foo", "bar", schemaFileName)); err != nil { - t.Errorf("unexpected missing cache file: %v", err) - } - if requests["/swaggerapi/foo/bar"] != 1 { - t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/bar"]) - } - - // Same version and group, should skip HTTP - if getSchemaAndValidate(c, data, "foo", "bar", dir); err != nil { - t.Errorf("unexpected error validating: %v", err) - } - if requests["/swaggerapi/foo/bar"] != 1 { - t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/bar"]) - } - - // Different API group, should go to HTTP and write - if getSchemaAndValidate(c, data, "foo", "baz", dir); err != nil { - t.Errorf("unexpected error validating: %v", err) - } - if _, err := os.Stat(path.Join(dir, "foo", "baz", schemaFileName)); err != nil { - t.Errorf("unexpected missing cache file: %v", err) - } - if requests["/swaggerapi/foo/baz"] != 1 { - t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/baz"]) - } - - // Different version, should go to HTTP and write - if getSchemaAndValidate(c, data, "foo2", "bar", dir); err != nil { - t.Errorf("unexpected error validating: %v", err) - } - if _, err := os.Stat(path.Join(dir, "foo2", "bar", schemaFileName)); err != nil { - t.Errorf("unexpected missing cache file: %v", err) - } - if requests["/swaggerapi/foo2/bar"] != 1 { - t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo2/bar"]) - } - - // No cache dir, should go straight to HTTP and not write - if getSchemaAndValidate(c, data, "foo", "blah", ""); err != nil { - t.Errorf("unexpected error validating: %v", err) - } - if requests["/swaggerapi/foo/blah"] != 1 { - t.Errorf("expected 1 schema request, saw: %d", requests["/swaggerapi/foo/blah"]) - } - if _, err := os.Stat(path.Join(dir, "foo", "blah", schemaFileName)); err == nil || !os.IsNotExist(err) { - t.Errorf("unexpected cache file error: %v", err) - } -} - -func TestSubstitueUser(t *testing.T) { - usr, err := user.Current() - if err != nil { - t.Logf("SKIPPING TEST: unexpected error: %v", err) - return - } - tests := []struct { - input string - expected string - expectErr bool - }{ - {input: "~/foo", expected: path.Join(os.Getenv("HOME"), "foo")}, - {input: "~" + usr.Username + "/bar", expected: usr.HomeDir + "/bar"}, - {input: "/foo/bar", expected: "/foo/bar"}, - {input: "~doesntexit/bar", expectErr: true}, - } - for _, test := range tests { - output, err := substituteUserHome(test.input) - if test.expectErr { - if err == nil { - t.Error("unexpected non-error") - } - continue - } - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if output != test.expected { - t.Errorf("expected: %s, saw: %s", test.expected, output) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/helpers_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/helpers_test.go deleted file mode 100644 index 10422e676..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/helpers_test.go +++ /dev/null @@ -1,364 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package util - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "syscall" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/validation/field" -) - -func TestMerge(t *testing.T) { - grace := int64(30) - tests := []struct { - obj runtime.Object - fragment string - expected runtime.Object - expectErr bool - kind string - }{ - { - kind: "Pod", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - }, - fragment: fmt.Sprintf(`{ "apiVersion": "%s" }`, testapi.Default.GroupVersion().String()), - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - }, - /* TODO: uncomment this test once Merge is updated to use - strategic-merge-patch. See #8449. - { - kind: "Pod", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - api.Container{ - Name: "c1", - Image: "red-image", - }, - api.Container{ - Name: "c2", - Image: "blue-image", - }, - }, - }, - }, - fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "containers": [ { "name": "c1", "image": "green-image" } ] } }`, testapi.Default.GroupVersion().String()), - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - api.Container{ - Name: "c1", - Image: "green-image", - }, - api.Container{ - Name: "c2", - Image: "blue-image", - }, - }, - }, - }, - }, */ - { - kind: "Pod", - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - }, - fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "volumes": [ {"name": "v1"}, {"name": "v2"} ] } }`, testapi.Default.GroupVersion().String()), - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Volumes: []api.Volume{ - { - Name: "v1", - VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}, - }, - { - Name: "v2", - VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}, - }, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSClusterFirst, - TerminationGracePeriodSeconds: &grace, - SecurityContext: &api.PodSecurityContext{}, - }, - }, - }, - { - kind: "Pod", - obj: &api.Pod{}, - fragment: "invalid json", - expected: &api.Pod{}, - expectErr: true, - }, - { - kind: "Service", - obj: &api.Service{}, - fragment: `{ "apiVersion": "badVersion" }`, - expectErr: true, - }, - { - kind: "Service", - obj: &api.Service{ - Spec: api.ServiceSpec{}, - }, - fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "ports": [ { "port": 0 } ] } }`, testapi.Default.GroupVersion().String()), - expected: &api.Service{ - Spec: api.ServiceSpec{ - SessionAffinity: "None", - Type: api.ServiceTypeClusterIP, - Ports: []api.ServicePort{ - { - Protocol: api.ProtocolTCP, - Port: 0, - }, - }, - }, - }, - }, - { - kind: "Service", - obj: &api.Service{ - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "version": "v1", - }, - }, - }, - fragment: fmt.Sprintf(`{ "apiVersion": "%s", "spec": { "selector": { "version": "v2" } } }`, testapi.Default.GroupVersion().String()), - expected: &api.Service{ - Spec: api.ServiceSpec{ - SessionAffinity: "None", - Type: api.ServiceTypeClusterIP, - Selector: map[string]string{ - "version": "v2", - }, - }, - }, - }, - } - - for i, test := range tests { - out, err := Merge(testapi.Default.Codec(), test.obj, test.fragment, test.kind) - if !test.expectErr { - if err != nil { - t.Errorf("testcase[%d], unexpected error: %v", i, err) - } else if !reflect.DeepEqual(out, test.expected) { - t.Errorf("\n\ntestcase[%d]\nexpected:\n%+v\nsaw:\n%+v", i, test.expected, out) - } - } - if test.expectErr && err == nil { - t.Errorf("testcase[%d], unexpected non-error", i) - } - } -} - -type fileHandler struct { - data []byte -} - -func (f *fileHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) { - if req.URL.Path == "/error" { - res.WriteHeader(http.StatusNotFound) - return - } - res.WriteHeader(http.StatusOK) - res.Write(f.data) -} - -func TestReadConfigData(t *testing.T) { - httpData := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - // TODO: Close() this server when fix #19254 - server := httptest.NewServer(&fileHandler{data: httpData}) - - fileData := []byte{11, 12, 13, 14, 15, 16, 17, 18, 19} - f, err := ioutil.TempFile("", "config") - if err != nil { - t.Errorf("unexpected error setting up config file") - t.Fail() - } - defer syscall.Unlink(f.Name()) - ioutil.WriteFile(f.Name(), fileData, 0644) - // TODO: test TLS here, requires making it possible to inject the HTTP client. - - tests := []struct { - config string - data []byte - expectErr bool - }{ - { - config: server.URL, - data: httpData, - }, - { - config: server.URL + "/error", - expectErr: true, - }, - { - config: "http://some.non.existent.foobar", - expectErr: true, - }, - { - config: f.Name(), - data: fileData, - }, - { - config: "some-non-existent-file", - expectErr: true, - }, - { - config: "", - expectErr: true, - }, - } - for _, test := range tests { - dataOut, err := ReadConfigData(test.config) - if err != nil && !test.expectErr { - t.Errorf("unexpected err: %v for %s", err, test.config) - } - if err == nil && test.expectErr { - t.Errorf("unexpected non-error for %s", test.config) - } - if !test.expectErr && !reflect.DeepEqual(test.data, dataOut) { - t.Errorf("unexpected data: %v, expected %v", dataOut, test.data) - } - } -} - -func TestCheckInvalidErr(t *testing.T) { - tests := []struct { - err error - expected string - }{ - { - errors.NewInvalid(api.Kind("Invalid1"), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field"), "single", "details")}), - `Error from server: Invalid1 "invalidation" is invalid: field: Invalid value: "single": details`, - }, - { - errors.NewInvalid(api.Kind("Invalid2"), "invalidation", field.ErrorList{field.Invalid(field.NewPath("field1"), "multi1", "details"), field.Invalid(field.NewPath("field2"), "multi2", "details")}), - `Error from server: Invalid2 "invalidation" is invalid: [field1: Invalid value: "multi1": details, field2: Invalid value: "multi2": details]`, - }, - { - errors.NewInvalid(api.Kind("Invalid3"), "invalidation", field.ErrorList{}), - `Error from server: Invalid3 "invalidation" is invalid: `, - }, - } - - var errReturned string - errHandle := func(err string) { - errReturned = err - } - - for _, test := range tests { - checkErr(test.err, errHandle) - - if errReturned != test.expected { - t.Fatalf("Got: %s, expected: %s", errReturned, test.expected) - } - } -} - -func TestCheckNoResourceMatchError(t *testing.T) { - tests := []struct { - err error - expected string - }{ - { - &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Resource: "foo"}}, - `the server doesn't have a resource type "foo"`, - }, - { - &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Version: "theversion", Resource: "foo"}}, - `the server doesn't have a resource type "foo" in version "theversion"`, - }, - { - &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Group: "thegroup", Version: "theversion", Resource: "foo"}}, - `the server doesn't have a resource type "foo" in group "thegroup" and version "theversion"`, - }, - { - &meta.NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Group: "thegroup", Resource: "foo"}}, - `the server doesn't have a resource type "foo" in group "thegroup"`, - }, - } - - var errReturned string - errHandle := func(err string) { - errReturned = err - } - - for _, test := range tests { - checkErr(test.err, errHandle) - - if errReturned != test.expected { - t.Fatalf("Got: %s, expected: %s", errReturned, test.expected) - } - } -} - -func TestDumpReaderToFile(t *testing.T) { - testString := "TEST STRING" - tempFile, err := ioutil.TempFile("", "hlpers_test_dump_") - if err != nil { - t.Errorf("unexpected error setting up a temporary file %v", err) - } - defer syscall.Unlink(tempFile.Name()) - defer tempFile.Close() - err = DumpReaderToFile(strings.NewReader(testString), tempFile.Name()) - if err != nil { - t.Errorf("error in DumpReaderToFile: %v", err) - } - data, err := ioutil.ReadFile(tempFile.Name()) - if err != nil { - t.Errorf("error when reading %s: %v", tempFile.Name(), err) - } - stringData := string(data) - if stringData != testString { - t.Fatalf("Wrong file content %s != %s", testString, stringData) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/jsonmerge/jsonmerge.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/jsonmerge/jsonmerge.go deleted file mode 100644 index 84a76da95..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/jsonmerge/jsonmerge.go +++ /dev/null @@ -1,193 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package jsonmerge - -import ( - "encoding/json" - "fmt" - - "github.com/evanphx/json-patch" - "github.com/golang/glog" - - "k8s.io/kubernetes/pkg/util/strategicpatch" - "k8s.io/kubernetes/pkg/util/yaml" -) - -// Delta represents a change between two JSON documents. -type Delta struct { - original []byte - edit []byte - - preconditions []PreconditionFunc -} - -// PreconditionFunc is a test to verify that an incompatible change -// has occurred before an Apply can be successful. -type PreconditionFunc func(interface{}) (hold bool, message string) - -// AddPreconditions adds precondition checks to a change which must -// be satisfied before an Apply is considered successful. If a -// precondition returns false, the Apply is failed with -// ErrPreconditionFailed. -func (d *Delta) AddPreconditions(fns ...PreconditionFunc) { - d.preconditions = append(d.preconditions, fns...) -} - -// RequireKeyUnchanged creates a precondition function that fails -// if the provided key is present in the diff (indicating its value -// has changed). -func RequireKeyUnchanged(key string) PreconditionFunc { - return func(diff interface{}) (bool, string) { - m, ok := diff.(map[string]interface{}) - if !ok { - return true, "" - } - // the presence of key in a diff means that its value has been changed, therefore - // we should fail the precondition. - _, ok = m[key] - if ok { - return false, key + " should not be changed\n" - } else { - return true, "" - } - } -} - -// RequireKeyUnchanged creates a precondition function that fails -// if the metadata.key is present in the diff (indicating its value -// has changed). -func RequireMetadataKeyUnchanged(key string) PreconditionFunc { - return func(diff interface{}) (bool, string) { - m, ok := diff.(map[string]interface{}) - if !ok { - return true, "" - } - m1, ok := m["metadata"] - if !ok { - return true, "" - } - m2, ok := m1.(map[string]interface{}) - if !ok { - return true, "" - } - _, ok = m2[key] - if ok { - return false, "metadata." + key + " should not be changed\n" - } else { - return true, "" - } - } -} - -// TestPreconditions test if preconditions hold given the edit -func TestPreconditionsHold(edit []byte, preconditions []PreconditionFunc) (bool, string) { - diff := make(map[string]interface{}) - if err := json.Unmarshal(edit, &diff); err != nil { - return false, err.Error() - } - for _, fn := range preconditions { - if hold, msg := fn(diff); !hold { - return false, msg - } - } - return true, "" -} - -// NewDelta accepts two JSON or YAML documents and calculates the difference -// between them. It returns a Delta object which can be used to resolve -// conflicts against a third version with a common parent, or an error -// if either document is in error. -func NewDelta(from, to []byte) (*Delta, error) { - d := &Delta{} - before, err := yaml.ToJSON(from) - if err != nil { - return nil, err - } - after, err := yaml.ToJSON(to) - if err != nil { - return nil, err - } - diff, err := jsonpatch.CreateMergePatch(before, after) - if err != nil { - return nil, err - } - glog.V(6).Infof("Patch created from:\n%s\n%s\n%s", string(before), string(after), string(diff)) - d.original = before - d.edit = diff - return d, nil -} - -// Apply attempts to apply the changes described by Delta onto latest, -// returning an error if the changes cannot be applied cleanly. -// IsConflicting will be true if the changes overlap, otherwise a -// generic error will be returned. -func (d *Delta) Apply(latest []byte) ([]byte, error) { - base, err := yaml.ToJSON(latest) - if err != nil { - return nil, err - } - changes, err := jsonpatch.CreateMergePatch(d.original, base) - if err != nil { - return nil, err - } - diff1 := make(map[string]interface{}) - if err := json.Unmarshal(d.edit, &diff1); err != nil { - return nil, err - } - diff2 := make(map[string]interface{}) - if err := json.Unmarshal(changes, &diff2); err != nil { - return nil, err - } - for _, fn := range d.preconditions { - hold1, _ := fn(diff1) - hold2, _ := fn(diff2) - if !hold1 || !hold2 { - return nil, ErrPreconditionFailed - } - } - - glog.V(6).Infof("Testing for conflict between:\n%s\n%s", string(d.edit), string(changes)) - hasConflicts, err := strategicpatch.HasConflicts(diff1, diff2) - if err != nil { - return nil, err - } - if hasConflicts { - return nil, ErrConflict - } - - return jsonpatch.MergePatch(base, d.edit) -} - -// IsConflicting returns true if the provided error indicates a -// conflict exists between the original changes and the applied -// changes. -func IsConflicting(err error) bool { - return err == ErrConflict -} - -// IsPreconditionFailed returns true if the provided error indicates -// a Delta precondition did not succeed. -func IsPreconditionFailed(err error) bool { - return err == ErrPreconditionFailed -} - -var ErrPreconditionFailed = fmt.Errorf("a precondition failed") -var ErrConflict = fmt.Errorf("changes are in conflict") - -func (d *Delta) Edit() []byte { - return d.edit -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/printing.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/printing.go index 88af6fa22..c95337253 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/printing.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/util/printing.go @@ -30,8 +30,8 @@ import ( // AddPrinterFlags adds printing related flags to a command (e.g. output format, no headers, template path) func AddPrinterFlags(cmd *cobra.Command) { - cmd.Flags().StringP("output", "o", "", "Output format. One of: json|yaml|wide|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://releases.k8s.io/HEAD/docs/user-guide/jsonpath.md].") - cmd.Flags().String("output-version", "", "Output the formatted object with the given version (default api-version).") + cmd.Flags().StringP("output", "o", "", "Output format. One of: json|yaml|wide|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://releases.k8s.io/release-1.2/docs/user-guide/jsonpath.md].") + cmd.Flags().String("output-version", "", "Output the formatted object with the given group version (for ex: 'extensions/v1beta1').") cmd.Flags().Bool("no-headers", false, "When using the default output, don't print headers.") cmd.Flags().Bool("show-labels", false, "When printing, show all labels as the last column (default hide labels column)") // template shorthand -t is deprecated to support -t for --tty diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/version.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/version.go deleted file mode 100644 index beaeda7bb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/cmd/version.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package cmd - -import ( - "io" - - "github.com/spf13/cobra" - - "k8s.io/kubernetes/pkg/kubectl" - cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" -) - -func NewCmdVersion(f *cmdutil.Factory, out io.Writer) *cobra.Command { - cmd := &cobra.Command{ - Use: "version", - Short: "Print the client and server version information.", - Run: func(cmd *cobra.Command, args []string) { - err := RunVersion(f, out, cmd) - cmdutil.CheckErr(err) - }, - } - cmd.Flags().BoolP("client", "c", false, "Client version only (no server required).") - cmd.Flags().MarkShorthandDeprecated("client", "please use --client instead.") - return cmd -} - -func RunVersion(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command) error { - kubectl.GetClientVersion(out) - if cmdutil.GetFlagBool(cmd, "client") { - return nil - } - - client, err := f.Client() - if err != nil { - return err - } - - kubectl.GetServerVersion(out, client) - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/configmap_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/configmap_test.go deleted file mode 100644 index 2fc936c9e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/configmap_test.go +++ /dev/null @@ -1,108 +0,0 @@ -/* -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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -func TestConfigMapGenerate(t *testing.T) { - tests := []struct { - params map[string]interface{} - expected *api.ConfigMap - expectErr bool - }{ - { - params: map[string]interface{}{ - "name": "foo", - }, - expected: &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Data: map[string]string{}, - }, - expectErr: false, - }, - { - params: map[string]interface{}{ - "name": "foo", - "type": "my-type", - }, - expected: &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Data: map[string]string{}, - }, - expectErr: false, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-literal": []string{"key1=value1", "key2=value2"}, - }, - expected: &api.ConfigMap{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Data: map[string]string{ - "key1": "value1", - "key2": "value2", - }, - }, - expectErr: false, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-literal": []string{"key1value1"}, - }, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-file": []string{"key1=/file=2"}, - }, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-file": []string{"key1==value"}, - }, - expectErr: true, - }, - } - generator := ConfigMapGeneratorV1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*api.ConfigMap), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*api.ConfigMap)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/custom_column_printer_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/custom_column_printer_test.go deleted file mode 100644 index 531881a73..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/custom_column_printer_test.go +++ /dev/null @@ -1,276 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "bytes" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestMassageJSONPath(t *testing.T) { - tests := []struct { - input string - expectedOutput string - expectErr bool - }{ - {input: "foo.bar", expectedOutput: "{.foo.bar}"}, - {input: "{foo.bar}", expectedOutput: "{.foo.bar}"}, - {input: ".foo.bar", expectedOutput: "{.foo.bar}"}, - {input: "{.foo.bar}", expectedOutput: "{.foo.bar}"}, - {input: "", expectedOutput: ""}, - {input: "{foo.bar", expectErr: true}, - {input: "foo.bar}", expectErr: true}, - {input: "{foo.bar}}", expectErr: true}, - {input: "{{foo.bar}", expectErr: true}, - } - for _, test := range tests { - output, err := massageJSONPath(test.input) - if err != nil && !test.expectErr { - t.Errorf("unexpected error: %v", err) - continue - } - if test.expectErr { - if err == nil { - t.Error("unexpected non-error") - } - continue - } - if output != test.expectedOutput { - t.Errorf("input: %s, expected: %s, saw: %s", test.input, test.expectedOutput, output) - } - } -} - -func TestNewColumnPrinterFromSpec(t *testing.T) { - tests := []struct { - spec string - expectedColumns []Column - expectErr bool - name string - }{ - { - spec: "", - expectErr: true, - name: "empty", - }, - { - spec: "invalid", - expectErr: true, - name: "invalid1", - }, - { - spec: "invalid=foobar", - expectErr: true, - name: "invalid2", - }, - { - spec: "invalid,foobar:blah", - expectErr: true, - name: "invalid3", - }, - { - spec: "NAME:metadata.name,API_VERSION:apiVersion", - name: "ok", - expectedColumns: []Column{ - { - Header: "NAME", - FieldSpec: "{.metadata.name}", - }, - { - Header: "API_VERSION", - FieldSpec: "{.apiVersion}", - }, - }, - }, - } - for _, test := range tests { - printer, err := NewCustomColumnsPrinterFromSpec(test.spec, api.Codecs.UniversalDecoder()) - if test.expectErr { - if err == nil { - t.Errorf("[%s] unexpected non-error", test.name) - } - continue - } - if !test.expectErr && err != nil { - t.Errorf("[%s] unexpected error: %v", test.name, err) - continue - } - - if !reflect.DeepEqual(test.expectedColumns, printer.Columns) { - t.Errorf("[%s]\nexpected:\n%v\nsaw:\n%v\n", test.name, test.expectedColumns, printer.Columns) - } - - } -} - -const exampleTemplateOne = `NAME API_VERSION -{metadata.name} {apiVersion}` - -const exampleTemplateTwo = `NAME API_VERSION - {metadata.name} {apiVersion}` - -func TestNewColumnPrinterFromTemplate(t *testing.T) { - tests := []struct { - spec string - expectedColumns []Column - expectErr bool - name string - }{ - { - spec: "", - expectErr: true, - name: "empty", - }, - { - spec: "invalid", - expectErr: true, - name: "invalid1", - }, - { - spec: "invalid=foobar", - expectErr: true, - name: "invalid2", - }, - { - spec: "invalid,foobar:blah", - expectErr: true, - name: "invalid3", - }, - { - spec: exampleTemplateOne, - name: "ok", - expectedColumns: []Column{ - { - Header: "NAME", - FieldSpec: "{.metadata.name}", - }, - { - Header: "API_VERSION", - FieldSpec: "{.apiVersion}", - }, - }, - }, - { - spec: exampleTemplateTwo, - name: "ok-2", - expectedColumns: []Column{ - { - Header: "NAME", - FieldSpec: "{.metadata.name}", - }, - { - Header: "API_VERSION", - FieldSpec: "{.apiVersion}", - }, - }, - }, - } - for _, test := range tests { - reader := bytes.NewBufferString(test.spec) - printer, err := NewCustomColumnsPrinterFromTemplate(reader, api.Codecs.UniversalDecoder()) - if test.expectErr { - if err == nil { - t.Errorf("[%s] unexpected non-error", test.name) - } - continue - } - if !test.expectErr && err != nil { - t.Errorf("[%s] unexpected error: %v", test.name, err) - continue - } - - if !reflect.DeepEqual(test.expectedColumns, printer.Columns) { - t.Errorf("[%s]\nexpected:\n%v\nsaw:\n%v\n", test.name, test.expectedColumns, printer.Columns) - } - - } -} - -func TestColumnPrint(t *testing.T) { - tests := []struct { - columns []Column - obj runtime.Object - expectedOutput string - }{ - { - columns: []Column{ - { - Header: "NAME", - FieldSpec: "{.metadata.name}", - }, - }, - obj: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo"}}, - expectedOutput: `NAME -foo -`, - }, - { - columns: []Column{ - { - Header: "NAME", - FieldSpec: "{.metadata.name}", - }, - }, - obj: &v1.PodList{ - Items: []v1.Pod{ - {ObjectMeta: v1.ObjectMeta{Name: "foo"}}, - {ObjectMeta: v1.ObjectMeta{Name: "bar"}}, - }, - }, - expectedOutput: `NAME -foo -bar -`, - }, - { - columns: []Column{ - { - Header: "NAME", - FieldSpec: "{.metadata.name}", - }, - { - Header: "API_VERSION", - FieldSpec: "{.apiVersion}", - }, - }, - obj: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "foo"}, TypeMeta: unversioned.TypeMeta{APIVersion: "baz"}}, - expectedOutput: `NAME API_VERSION -foo baz -`, - }, - } - - for _, test := range tests { - printer := &CustomColumnsPrinter{ - Columns: test.columns, - Decoder: api.Codecs.UniversalDecoder(), - } - buffer := &bytes.Buffer{} - if err := printer.PrintObj(test.obj, buffer); err != nil { - t.Errorf("unexpected error: %v", err) - } - if buffer.String() != test.expectedOutput { - t.Errorf("\nexpected:\n'%s'\nsaw\n'%s'\n", test.expectedOutput, buffer.String()) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/describe.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/describe.go index 6d2dc66ee..0a09b3a06 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/describe.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/describe.go @@ -33,6 +33,8 @@ import ( "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/apis/autoscaling" + "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" client "k8s.io/kubernetes/pkg/client/unversioned" @@ -89,12 +91,14 @@ func describerMap(c *client.Client) map[unversioned.GroupKind]Describer { api.Kind("Endpoints"): &EndpointsDescriber{c}, api.Kind("ConfigMap"): &ConfigMapDescriber{c}, - extensions.Kind("ReplicaSet"): &ReplicaSetDescriber{c}, - extensions.Kind("HorizontalPodAutoscaler"): &HorizontalPodAutoscalerDescriber{c}, - extensions.Kind("DaemonSet"): &DaemonSetDescriber{c}, - extensions.Kind("Deployment"): &DeploymentDescriber{clientset.FromUnversionedClient(c)}, - extensions.Kind("Job"): &JobDescriber{c}, - extensions.Kind("Ingress"): &IngressDescriber{c}, + extensions.Kind("ReplicaSet"): &ReplicaSetDescriber{c}, + extensions.Kind("HorizontalPodAutoscaler"): &HorizontalPodAutoscalerDescriber{c}, + autoscaling.Kind("HorizontalPodAutoscaler"): &HorizontalPodAutoscalerDescriber{c}, + extensions.Kind("DaemonSet"): &DaemonSetDescriber{c}, + extensions.Kind("Deployment"): &DeploymentDescriber{clientset.FromUnversionedClient(c)}, + extensions.Kind("Job"): &JobDescriber{c}, + batch.Kind("Job"): &JobDescriber{c}, + extensions.Kind("Ingress"): &IngressDescriber{c}, } return m @@ -258,36 +262,41 @@ func DescribeResourceQuotas(quotas *api.ResourceQuotaList, w io.Writer) { fmt.Fprint(w, "No resource quota.\n") return } - resources := []api.ResourceName{} - hard := map[api.ResourceName]resource.Quantity{} - used := map[api.ResourceName]resource.Quantity{} + sort.Sort(SortableResourceQuotas(quotas.Items)) + + fmt.Fprint(w, "Resource Quotas") for _, q := range quotas.Items { + fmt.Fprintf(w, "\n Name:\t%s\n", q.Name) + if len(q.Spec.Scopes) > 0 { + scopes := []string{} + for _, scope := range q.Spec.Scopes { + scopes = append(scopes, string(scope)) + } + sort.Strings(scopes) + fmt.Fprintf(w, " Scopes:\t%s\n", strings.Join(scopes, ", ")) + for _, scope := range scopes { + helpText := helpTextForResourceQuotaScope(api.ResourceQuotaScope(scope)) + if len(helpText) > 0 { + fmt.Fprintf(w, " * %s\n", helpText) + } + } + } + + fmt.Fprintf(w, " Resource\tUsed\tHard\n") + fmt.Fprint(w, " --------\t---\t---\n") + + resources := []api.ResourceName{} for resource := range q.Status.Hard { resources = append(resources, resource) + } + sort.Sort(SortableResourceNames(resources)) + + for _, resource := range resources { hardQuantity := q.Status.Hard[resource] usedQuantity := q.Status.Used[resource] - - // if for some reason there are multiple quota documents, we take least permissive - prevQuantity, ok := hard[resource] - if ok { - if hardQuantity.Value() < prevQuantity.Value() { - hard[resource] = hardQuantity - } - } else { - hard[resource] = hardQuantity - } - used[resource] = usedQuantity + fmt.Fprintf(w, " %s\t%s\t%s\n", string(resource), usedQuantity.String(), hardQuantity.String()) } } - - sort.Sort(SortableResourceNames(resources)) - fmt.Fprint(w, "Resource Quotas\n Resource\tUsed\tHard\n") - fmt.Fprint(w, " ---\t---\t---\n") - for _, resource := range resources { - hardQuantity := hard[resource] - usedQuantity := used[resource] - fmt.Fprintf(w, " %s\t%s\t%s\n", string(resource), usedQuantity.String(), hardQuantity.String()) - } } // LimitRangeDescriber generates information about a limit range @@ -393,10 +402,38 @@ func (d *ResourceQuotaDescriber) Describe(namespace, name string) (string, error return describeQuota(resourceQuota) } +func helpTextForResourceQuotaScope(scope api.ResourceQuotaScope) string { + switch scope { + case api.ResourceQuotaScopeTerminating: + return "Matches all pods that have an active deadline." + case api.ResourceQuotaScopeNotTerminating: + return "Matches all pods that do not have an active deadline." + case api.ResourceQuotaScopeBestEffort: + return "Matches all pods that have best effort quality of service." + case api.ResourceQuotaScopeNotBestEffort: + return "Matches all pods that do not have best effort quality of service." + default: + return "" + } +} func describeQuota(resourceQuota *api.ResourceQuota) (string, error) { return tabbedString(func(out io.Writer) error { fmt.Fprintf(out, "Name:\t%s\n", resourceQuota.Name) fmt.Fprintf(out, "Namespace:\t%s\n", resourceQuota.Namespace) + if len(resourceQuota.Spec.Scopes) > 0 { + scopes := []string{} + for _, scope := range resourceQuota.Spec.Scopes { + scopes = append(scopes, string(scope)) + } + sort.Strings(scopes) + fmt.Fprintf(out, "Scopes:\t%s\n", strings.Join(scopes, ", ")) + for _, scope := range scopes { + helpText := helpTextForResourceQuotaScope(api.ResourceQuotaScope(scope)) + if len(helpText) > 0 { + fmt.Fprintf(out, " * %s\n", helpText) + } + } + } fmt.Fprintf(out, "Resource\tUsed\tHard\n") fmt.Fprintf(out, "--------\t----\t----\n") @@ -525,6 +562,8 @@ func describeVolumes(volumes []api.Volume, out io.Writer) { printGitRepoVolumeSource(volume.VolumeSource.GitRepo, out) case volume.VolumeSource.Secret != nil: printSecretVolumeSource(volume.VolumeSource.Secret, out) + case volume.VolumeSource.ConfigMap != nil: + printConfigMapVolumeSource(volume.VolumeSource.ConfigMap, out) case volume.VolumeSource.NFS != nil: printNFSVolumeSource(volume.VolumeSource.NFS, out) case volume.VolumeSource.ISCSI != nil: @@ -535,8 +574,10 @@ func describeVolumes(volumes []api.Volume, out io.Writer) { printPersistentVolumeClaimVolumeSource(volume.VolumeSource.PersistentVolumeClaim, out) case volume.VolumeSource.RBD != nil: printRBDVolumeSource(volume.VolumeSource.RBD, out) + case volume.VolumeSource.DownwardAPI != nil: + printDownwardAPIVolumeSource(volume.VolumeSource.DownwardAPI, out) default: - fmt.Fprintf(out, " \n") + fmt.Fprintf(out, " \n") } } } @@ -577,10 +618,15 @@ func printGitRepoVolumeSource(git *api.GitRepoVolumeSource, out io.Writer) { } func printSecretVolumeSource(secret *api.SecretVolumeSource, out io.Writer) { - fmt.Fprintf(out, " Type:\tSecret (a secret that should populate this volume)\n"+ + fmt.Fprintf(out, " Type:\tSecret (a volume populated by a Secret)\n"+ " SecretName:\t%v\n", secret.SecretName) } +func printConfigMapVolumeSource(configMap *api.ConfigMapVolumeSource, out io.Writer) { + fmt.Fprintf(out, " Type:\tConfigMap (a volume populated by a ConfigMap)\n"+ + " Name:\t%v\n", configMap.Name) +} + func printNFSVolumeSource(nfs *api.NFSVolumeSource, out io.Writer) { fmt.Fprintf(out, " Type:\tNFS (an NFS mount that lasts the lifetime of a pod)\n"+ " Server:\t%v\n"+ @@ -628,6 +674,13 @@ func printRBDVolumeSource(rbd *api.RBDVolumeSource, out io.Writer) { rbd.CephMonitors, rbd.RBDImage, rbd.FSType, rbd.RBDPool, rbd.RadosUser, rbd.Keyring, rbd.SecretRef, rbd.ReadOnly) } +func printDownwardAPIVolumeSource(d *api.DownwardAPIVolumeSource, out io.Writer) { + fmt.Fprintf(out, " Type:\tDownwardAPI (a volume populated by information about the pod)\n Items:\n") + for _, mapping := range d.Items { + fmt.Fprintf(out, " %v -> %v\n", mapping.FieldRef.FieldPath, mapping.Path) + } +} + type PersistentVolumeDescriber struct { client.Interface } @@ -720,13 +773,22 @@ func DescribeContainers(containers []api.Container, containerStatuses []api.Cont } for _, container := range containers { - status := statuses[container.Name] - state := status.State + status, ok := statuses[container.Name] fmt.Fprintf(out, " %v:\n", container.Name) - fmt.Fprintf(out, " Container ID:\t%s\n", status.ContainerID) + if ok { + fmt.Fprintf(out, " Container ID:\t%s\n", status.ContainerID) + } fmt.Fprintf(out, " Image:\t%s\n", container.Image) - fmt.Fprintf(out, " Image ID:\t%s\n", status.ImageID) + if ok { + fmt.Fprintf(out, " Image ID:\t%s\n", status.ImageID) + } + portString := describeContainerPorts(container.Ports) + if strings.Contains(portString, ",") { + fmt.Fprintf(out, " Ports:\t%s\n", portString) + } else { + fmt.Fprintf(out, " Port:\t%s\n", portString) + } if len(container.Command) > 0 { fmt.Fprintf(out, " Command:\n") @@ -763,12 +825,14 @@ func DescribeContainers(containers []api.Container, containerStatuses []api.Cont fmt.Fprintf(out, " %s:\t%s\n", name, quantity.String()) } - describeStatus("State", state, out) - if status.LastTerminationState.Terminated != nil { - describeStatus("Last State", status.LastTerminationState, out) + if ok { + describeStatus("State", status.State, out) + if status.LastTerminationState.Terminated != nil { + describeStatus("Last State", status.LastTerminationState, out) + } + fmt.Fprintf(out, " Ready:\t%v\n", printBool(status.Ready)) + fmt.Fprintf(out, " Restart Count:\t%d\n", status.RestartCount) } - fmt.Fprintf(out, " Ready:\t%v\n", printBool(status.Ready)) - fmt.Fprintf(out, " Restart Count:\t%d\n", status.RestartCount) if container.LivenessProbe != nil { probe := DescribeProbe(container.LivenessProbe) @@ -793,6 +857,14 @@ func DescribeContainers(containers []api.Container, containerStatuses []api.Cont } } +func describeContainerPorts(cPorts []api.ContainerPort) string { + ports := []string{} + for _, cPort := range cPorts { + ports = append(ports, fmt.Sprintf("%d/%s", cPort.ContainerPort, cPort.Protocol)) + } + return strings.Join(ports, ", ") +} + // DescribeProbe is exported for consumers in other API groups that have probes func DescribeProbe(probe *api.Probe) string { attrs := fmt.Sprintf("delay=%ds timeout=%ds period=%ds #success=%d #failure=%d", probe.InitialDelaySeconds, probe.TimeoutSeconds, probe.PeriodSeconds, probe.SuccessThreshold, probe.FailureThreshold) @@ -903,7 +975,7 @@ func describeReplicationController(controller *api.ReplicationController, events if controller.Spec.Template != nil { fmt.Fprintf(out, "Image(s):\t%s\n", makeImageList(&controller.Spec.Template.Spec)) } else { - fmt.Fprintf(out, "Image(s):\t%s\n", "") + fmt.Fprintf(out, "Image(s):\t%s\n", "") } fmt.Fprintf(out, "Selector:\t%s\n", labels.FormatLabels(controller.Spec.Selector)) fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(controller.Labels)) @@ -922,7 +994,7 @@ func describeReplicationController(controller *api.ReplicationController, events func DescribePodTemplate(template *api.PodTemplateSpec) (string, error) { return tabbedString(func(out io.Writer) error { if template == nil { - fmt.Fprintf(out, "") + fmt.Fprintf(out, "") return nil } fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(template.Labels)) @@ -966,18 +1038,12 @@ func describeReplicaSet(rs *extensions.ReplicaSet, events *api.EventList, runnin return tabbedString(func(out io.Writer) error { fmt.Fprintf(out, "Name:\t%s\n", rs.Name) fmt.Fprintf(out, "Namespace:\t%s\n", rs.Namespace) - if rs.Spec.Template != nil { - fmt.Fprintf(out, "Image(s):\t%s\n", makeImageList(&rs.Spec.Template.Spec)) - } else { - fmt.Fprintf(out, "Image(s):\t%s\n", "") - } + fmt.Fprintf(out, "Image(s):\t%s\n", makeImageList(&rs.Spec.Template.Spec)) fmt.Fprintf(out, "Selector:\t%s\n", unversioned.FormatLabelSelector(rs.Spec.Selector)) fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(rs.Labels)) fmt.Fprintf(out, "Replicas:\t%d current / %d desired\n", rs.Status.Replicas, rs.Spec.Replicas) fmt.Fprintf(out, "Pods Status:\t%d Running / %d Waiting / %d Succeeded / %d Failed\n", running, waiting, succeeded, failed) - if rs.Spec.Template != nil { - describeVolumes(rs.Spec.Template.Spec.Volumes, out) - } + describeVolumes(rs.Spec.Template.Spec.Volumes, out) if events != nil { DescribeEvents(events, out) } @@ -1012,7 +1078,7 @@ func describeJob(job *extensions.Job, events *api.EventList) (string, error) { if job.Spec.Completions != nil { fmt.Fprintf(out, "Completions:\t%d\n", *job.Spec.Completions) } else { - fmt.Fprintf(out, "Completions:\tNot Set\n") + fmt.Fprintf(out, "Completions:\t\n") } if job.Status.StartTime != nil { fmt.Fprintf(out, "Start Time:\t%s\n", job.Status.StartTime.Time.Format(time.RFC1123Z)) @@ -1271,7 +1337,7 @@ func describeService(service *api.Service, endpoints *api.Endpoints, events *api name := sp.Name if name == "" { - name = "" + name = "" } fmt.Fprintf(out, "Port:\t%s\t%d/%s\n", name, sp.Port, sp.Protocol) if sp.NodePort != 0 { @@ -1342,7 +1408,7 @@ func describeEndpoints(ep *api.Endpoints, events *api.EventList) (string, error) for _, port := range subset.Ports { name := port.Name if len(name) == 0 { - name = "" + name = "" } fmt.Fprintf(out, " %s\t%d\t%s\n", name, port.Port, port.Protocol) } @@ -1372,7 +1438,7 @@ func (d *ServiceAccountDescriber) Describe(namespace, name string) (string, erro tokens := []api.Secret{} - tokenSelector := fields.SelectorFromSet(map[string]string{client.SecretType: string(api.SecretTypeServiceAccountToken)}) + tokenSelector := fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(api.SecretTypeServiceAccountToken)}) options := api.ListOptions{FieldSelector: tokenSelector} secrets, err := d.Secrets(namespace).List(options) if err == nil { @@ -1552,6 +1618,7 @@ func (d *HorizontalPodAutoscalerDescriber) Describe(namespace, name string) (str fmt.Fprintf(out, "Name:\t%s\n", hpa.Name) fmt.Fprintf(out, "Namespace:\t%s\n", hpa.Namespace) fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(hpa.Labels)) + fmt.Fprintf(out, "Annotations:\t%s\n", labels.FormatLabels(hpa.Annotations)) fmt.Fprintf(out, "CreationTimestamp:\t%s\n", hpa.CreationTimestamp.Time.Format(time.RFC1123Z)) fmt.Fprintf(out, "Reference:\t%s/%s/%s\n", hpa.Spec.ScaleRef.Kind, @@ -1563,7 +1630,7 @@ func (d *HorizontalPodAutoscalerDescriber) Describe(namespace, name string) (str if hpa.Status.CurrentCPUUtilizationPercentage != nil { fmt.Fprintf(out, "%d%%\n", *hpa.Status.CurrentCPUUtilizationPercentage) } else { - fmt.Fprintf(out, "\n") + fmt.Fprintf(out, "\n") } } minReplicas := "" @@ -1583,6 +1650,11 @@ func (d *HorizontalPodAutoscalerDescriber) Describe(namespace, name string) (str fmt.Fprintf(out, "failed to check Replication Controller\n") } } + + events, _ := d.client.Events(namespace).Search(hpa) + if events != nil { + DescribeEvents(events, out) + } return nil }) } @@ -1710,11 +1782,11 @@ func (dd *DeploymentDescriber) Describe(namespace, name string) (string, error) ru := d.Spec.Strategy.RollingUpdate fmt.Fprintf(out, "RollingUpdateStrategy:\t%s max unavailable, %s max surge\n", ru.MaxUnavailable.String(), ru.MaxSurge.String()) } - oldRSs, _, err := deploymentutil.GetOldReplicaSets(*d, dd) + oldRSs, _, err := deploymentutil.GetOldReplicaSets(d, dd) if err == nil { fmt.Fprintf(out, "OldReplicaSets:\t%s\n", printReplicaSetsByLabels(oldRSs)) } - newRS, err := deploymentutil.GetNewReplicaSet(*d, dd) + newRS, err := deploymentutil.GetNewReplicaSet(d, dd) if err == nil { var newRSs []*extensions.ReplicaSet if newRS != nil { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/describe_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/describe_test.go deleted file mode 100644 index a7d1c24e1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/describe_test.go +++ /dev/null @@ -1,523 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "bytes" - "fmt" - "reflect" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient" -) - -type describeClient struct { - T *testing.T - Namespace string - Err error - client.Interface -} - -func TestDescribePod(t *testing.T) { - fake := testclient.NewSimpleFake(&api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Namespace: "foo", - }, - }) - c := &describeClient{T: t, Namespace: "foo", Interface: fake} - d := PodDescriber{c} - out, err := d.Describe("foo", "bar") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !strings.Contains(out, "bar") || !strings.Contains(out, "Status:") { - t.Errorf("unexpected out: %s", out) - } -} - -func TestDescribeService(t *testing.T) { - fake := testclient.NewSimpleFake(&api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Namespace: "foo", - }, - }) - c := &describeClient{T: t, Namespace: "foo", Interface: fake} - d := ServiceDescriber{c} - out, err := d.Describe("foo", "bar") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !strings.Contains(out, "Labels:") || !strings.Contains(out, "bar") { - t.Errorf("unexpected out: %s", out) - } -} - -func TestPodDescribeResultsSorted(t *testing.T) { - // Arrange - fake := testclient.NewSimpleFake(&api.EventList{ - Items: []api.Event{ - { - Source: api.EventSource{Component: "kubelet"}, - Message: "Item 1", - FirstTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - { - Source: api.EventSource{Component: "scheduler"}, - Message: "Item 2", - FirstTimestamp: unversioned.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - { - Source: api.EventSource{Component: "kubelet"}, - Message: "Item 3", - FirstTimestamp: unversioned.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - }, - }) - c := &describeClient{T: t, Namespace: "foo", Interface: fake} - d := PodDescriber{c} - - // Act - out, err := d.Describe("foo", "bar") - - // Assert - if err != nil { - t.Errorf("unexpected error: %v", err) - } - VerifyDatesInOrder(out, "\n" /* rowDelimiter */, "\t" /* columnDelimiter */, t) -} - -func TestDescribeContainers(t *testing.T) { - testCases := []struct { - container api.Container - status api.ContainerStatus - expectedElements []string - }{ - // Running state. - { - container: api.Container{Name: "test", Image: "image"}, - status: api.ContainerStatus{ - Name: "test", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{ - StartedAt: unversioned.NewTime(time.Now()), - }, - }, - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Running", "Ready", "True", "Restart Count", "7", "Image", "image", "Started"}, - }, - // Waiting state. - { - container: api.Container{Name: "test", Image: "image"}, - status: api.ContainerStatus{ - Name: "test", - State: api.ContainerState{ - Waiting: &api.ContainerStateWaiting{ - Reason: "potato", - }, - }, - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "Reason", "potato"}, - }, - // Terminated state. - { - container: api.Container{Name: "test", Image: "image"}, - status: api.ContainerStatus{ - Name: "test", - State: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{ - StartedAt: unversioned.NewTime(time.Now()), - FinishedAt: unversioned.NewTime(time.Now()), - Reason: "potato", - ExitCode: 2, - }, - }, - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Terminated", "Ready", "True", "Restart Count", "7", "Image", "image", "Reason", "potato", "Started", "Finished", "Exit Code", "2"}, - }, - // Last Terminated - { - container: api.Container{Name: "test", Image: "image"}, - status: api.ContainerStatus{ - Name: "test", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{ - StartedAt: unversioned.NewTime(time.Now()), - }, - }, - LastTerminationState: api.ContainerState{ - Terminated: &api.ContainerStateTerminated{ - StartedAt: unversioned.NewTime(time.Now().Add(time.Second * 3)), - FinishedAt: unversioned.NewTime(time.Now()), - Reason: "crashing", - ExitCode: 3, - }, - }, - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Terminated", "Ready", "True", "Restart Count", "7", "Image", "image", "Started", "Finished", "Exit Code", "2", "crashing", "3"}, - }, - // No state defaults to waiting. - { - container: api.Container{Name: "test", Image: "image"}, - status: api.ContainerStatus{ - Name: "test", - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image"}, - }, - // Env - { - container: api.Container{Name: "test", Image: "image", Env: []api.EnvVar{{Name: "envname", Value: "xyz"}}}, - status: api.ContainerStatus{ - Name: "test", - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "envname", "xyz"}, - }, - // Command - { - container: api.Container{Name: "test", Image: "image", Command: []string{"sleep", "1000"}}, - status: api.ContainerStatus{ - Name: "test", - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "sleep", "1000"}, - }, - // Args - { - container: api.Container{Name: "test", Image: "image", Args: []string{"time", "1000"}}, - status: api.ContainerStatus{ - Name: "test", - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"test", "State", "Waiting", "Ready", "True", "Restart Count", "7", "Image", "image", "time", "1000"}, - }, - // Using limits. - { - container: api.Container{ - Name: "test", - Image: "image", - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("1000"), - api.ResourceName(api.ResourceMemory): resource.MustParse("4G"), - api.ResourceName(api.ResourceStorage): resource.MustParse("20G"), - }, - }, - }, - status: api.ContainerStatus{ - Name: "test", - Ready: true, - RestartCount: 7, - }, - expectedElements: []string{"cpu", "1k", "memory", "4G", "storage", "20G"}, - }, - } - - for i, testCase := range testCases { - out := new(bytes.Buffer) - pod := api.Pod{ - Spec: api.PodSpec{ - Containers: []api.Container{testCase.container}, - }, - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{testCase.status}, - }, - } - DescribeContainers(pod.Spec.Containers, pod.Status.ContainerStatuses, EnvValueRetriever(&pod), out) - output := out.String() - for _, expected := range testCase.expectedElements { - if !strings.Contains(output, expected) { - t.Errorf("Test case %d: expected to find %q in output: %q", i, expected, output) - } - } - } -} - -func TestDescribers(t *testing.T) { - first := &api.Event{} - second := &api.Pod{} - var third *api.Pod - testErr := fmt.Errorf("test") - d := Describers{} - d.Add( - func(e *api.Event, p *api.Pod) (string, error) { - if e != first { - t.Errorf("first argument not equal: %#v", e) - } - if p != second { - t.Errorf("second argument not equal: %#v", p) - } - return "test", testErr - }, - ) - if out, err := d.DescribeObject(first, second); out != "test" || err != testErr { - t.Errorf("unexpected result: %s %v", out, err) - } - - if out, err := d.DescribeObject(first, second, third); out != "" || err == nil { - t.Errorf("unexpected result: %s %v", out, err) - } else { - if noDescriber, ok := err.(ErrNoDescriber); ok { - if !reflect.DeepEqual(noDescriber.Types, []string{"*api.Event", "*api.Pod", "*api.Pod"}) { - t.Errorf("unexpected describer: %v", err) - } - } else { - t.Errorf("unexpected error type: %v", err) - } - } - - d.Add( - func(e *api.Event) (string, error) { - if e != first { - t.Errorf("first argument not equal: %#v", e) - } - return "simpler", testErr - }, - ) - if out, err := d.DescribeObject(first); out != "simpler" || err != testErr { - t.Errorf("unexpected result: %s %v", out, err) - } -} - -func TestDefaultDescribers(t *testing.T) { - out, err := DefaultObjectDescriber.DescribeObject(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !strings.Contains(out, "foo") { - t.Errorf("unexpected output: %s", out) - } - - out, err = DefaultObjectDescriber.DescribeObject(&api.Service{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !strings.Contains(out, "foo") { - t.Errorf("unexpected output: %s", out) - } - - out, err = DefaultObjectDescriber.DescribeObject(&api.ReplicationController{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !strings.Contains(out, "foo") { - t.Errorf("unexpected output: %s", out) - } - - out, err = DefaultObjectDescriber.DescribeObject(&api.Node{ObjectMeta: api.ObjectMeta{Name: "foo"}}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !strings.Contains(out, "foo") { - t.Errorf("unexpected output: %s", out) - } -} - -func TestGetPodsTotalRequests(t *testing.T) { - testCases := []struct { - pods *api.PodList - expectedReqs, expectedLimits map[api.ResourceName]resource.Quantity - }{ - { - pods: &api.PodList{ - Items: []api.Pod{ - { - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("1"), - api.ResourceName(api.ResourceMemory): resource.MustParse("300Mi"), - api.ResourceName(api.ResourceStorage): resource.MustParse("1G"), - }, - }, - }, - { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("90m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("120Mi"), - api.ResourceName(api.ResourceStorage): resource.MustParse("200M"), - }, - }, - }, - }, - }, - }, - { - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("60m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("43Mi"), - api.ResourceName(api.ResourceStorage): resource.MustParse("500M"), - }, - }, - }, - { - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("34m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("83Mi"), - api.ResourceName(api.ResourceStorage): resource.MustParse("700M"), - }, - }, - }, - }, - }, - }, - }, - }, - expectedReqs: map[api.ResourceName]resource.Quantity{ - api.ResourceName(api.ResourceCPU): resource.MustParse("1.184"), - api.ResourceName(api.ResourceMemory): resource.MustParse("546Mi"), - api.ResourceName(api.ResourceStorage): resource.MustParse("2.4G"), - }, - }, - } - - for _, testCase := range testCases { - reqs, _, err := getPodsTotalRequestsAndLimits(testCase.pods) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - if !reflect.DeepEqual(reqs, testCase.expectedReqs) { - t.Errorf("Expected %v, got %v", testCase.expectedReqs, reqs) - } - } -} - -func TestPersistentVolumeDescriber(t *testing.T) { - tests := map[string]*api.PersistentVolume{ - - "hostpath": { - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - HostPath: &api.HostPathVolumeSource{}, - }, - }, - }, - "gce": { - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{}, - }, - }, - }, - "ebs": { - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{}, - }, - }, - }, - "nfs": { - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - NFS: &api.NFSVolumeSource{}, - }, - }, - }, - "iscsi": { - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - ISCSI: &api.ISCSIVolumeSource{}, - }, - }, - }, - "gluster": { - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - Glusterfs: &api.GlusterfsVolumeSource{}, - }, - }, - }, - "rbd": { - Spec: api.PersistentVolumeSpec{ - PersistentVolumeSource: api.PersistentVolumeSource{ - RBD: &api.RBDVolumeSource{}, - }, - }, - }, - } - - for name, pv := range tests { - fake := testclient.NewSimpleFake(pv) - c := PersistentVolumeDescriber{fake} - str, err := c.Describe("foo", "bar") - if err != nil { - t.Errorf("Unexpected error for test %s: %v", name, err) - } - if str == "" { - t.Errorf("Unexpected empty string for test %s. Expected PV Describer output", name) - } - } -} - -func TestDescribeDeployment(t *testing.T) { - fake := fake.NewSimpleClientset(&extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Namespace: "foo", - }, - Spec: extensions.DeploymentSpec{ - Template: api.PodTemplateSpec{}, - }, - }) - d := DeploymentDescriber{fake} - out, err := d.Describe("foo", "bar") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !strings.Contains(out, "bar") || !strings.Contains(out, "foo") { - t.Errorf("unexpected out: %s", out) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/generate_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/generate_test.go deleted file mode 100644 index 62823f9dc..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/generate_test.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - "github.com/spf13/cobra" -) - -type TestStruct struct { - val int -} - -func TestIsZero(t *testing.T) { - tests := []struct { - val interface{} - expectZero bool - }{ - {"", true}, - {nil, true}, - {0, true}, - {TestStruct{}, true}, - {"foo", false}, - {1, false}, - {TestStruct{val: 2}, false}, - } - - for _, test := range tests { - output := IsZero(test.val) - if output != test.expectZero { - t.Errorf("expected: %v, saw %v", test.expectZero, output) - } - } -} - -func TestValidateParams(t *testing.T) { - tests := []struct { - paramSpec []GeneratorParam - params map[string]interface{} - valid bool - }{ - { - paramSpec: []GeneratorParam{}, - params: map[string]interface{}{}, - valid: true, - }, - { - paramSpec: []GeneratorParam{ - {Name: "foo"}, - }, - params: map[string]interface{}{}, - valid: true, - }, - { - paramSpec: []GeneratorParam{ - {Name: "foo", Required: true}, - }, - params: map[string]interface{}{ - "foo": "bar", - }, - valid: true, - }, - { - paramSpec: []GeneratorParam{ - {Name: "foo", Required: true}, - }, - params: map[string]interface{}{ - "baz": "blah", - "foo": "bar", - }, - valid: true, - }, - { - paramSpec: []GeneratorParam{ - {Name: "foo", Required: true}, - {Name: "baz", Required: true}, - }, - params: map[string]interface{}{ - "baz": "blah", - "foo": "bar", - }, - valid: true, - }, - { - paramSpec: []GeneratorParam{ - {Name: "foo", Required: true}, - {Name: "baz", Required: true}, - }, - params: map[string]interface{}{ - "foo": "bar", - }, - valid: false, - }, - } - for _, test := range tests { - err := ValidateParams(test.paramSpec, test.params) - if test.valid && err != nil { - t.Errorf("unexpected error: %v", err) - } - if !test.valid && err == nil { - t.Errorf("unexpected non-error") - } - } -} - -func TestMakeParams(t *testing.T) { - cmd := &cobra.Command{} - cmd.Flags().String("foo", "bar", "") - cmd.Flags().String("baz", "", "") - cmd.Flags().Set("baz", "blah") - - paramSpec := []GeneratorParam{ - {Name: "foo", Required: true}, - {Name: "baz", Required: true}, - } - expected := map[string]interface{}{ - "foo": "bar", - "baz": "blah", - } - params := MakeParams(cmd, paramSpec) - if !reflect.DeepEqual(params, expected) { - t.Errorf("\nexpected:\n%v\nsaw:\n%v", expected, params) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/history.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/history.go index 01995f376..37cb9e0b2 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/history.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/history.go @@ -67,11 +67,11 @@ func (h *DeploymentHistoryViewer) History(namespace, name string) (HistoryInfo, if err != nil { return historyInfo, fmt.Errorf("failed to retrieve deployment %s: %v", name, err) } - _, allOldRSs, err := deploymentutil.GetOldReplicaSets(*deployment, h.c) + _, allOldRSs, err := deploymentutil.GetOldReplicaSets(deployment, h.c) if err != nil { return historyInfo, fmt.Errorf("failed to retrieve old replica sets from deployment %s: %v", name, err) } - newRS, err := deploymentutil.GetNewReplicaSet(*deployment, h.c) + newRS, err := deploymentutil.GetNewReplicaSet(deployment, h.c) if err != nil { return historyInfo, fmt.Errorf("failed to retrieve new replica set from deployment %s: %v", name, err) } @@ -81,7 +81,7 @@ func (h *DeploymentHistoryViewer) History(namespace, name string) (HistoryInfo, if err != nil { continue } - historyInfo.RevisionToTemplate[v] = rs.Spec.Template + historyInfo.RevisionToTemplate[v] = &rs.Spec.Template changeCause := getChangeCause(rs) if historyInfo.RevisionToTemplate[v].Annotations == nil { historyInfo.RevisionToTemplate[v].Annotations = make(map[string]string) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/interfaces.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/interfaces.go index 890947b5c..8f1e6f197 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/interfaces.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/interfaces.go @@ -18,7 +18,7 @@ package kubectl import ( "k8s.io/kubernetes/pkg/api" - client "k8s.io/kubernetes/pkg/client/unversioned" + client "k8s.io/kubernetes/pkg/client/restclient" ) // RESTClient is a client helper for dealing with RESTful resources diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl.go index 60b280174..844a53781 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl.go @@ -26,7 +26,6 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" ) const kubectlAnnotationPrefix = "kubectl.kubernetes.io/" @@ -75,51 +74,72 @@ func (m OutputVersionMapper) RESTMapping(gk unversioned.GroupKind, versions ...s } // ShortcutExpander is a RESTMapper that can be used for Kubernetes -// resources. +// resources. It expands the resource first, then invokes the wrapped RESTMapper type ShortcutExpander struct { - meta.RESTMapper + RESTMapper meta.RESTMapper } var _ meta.RESTMapper = &ShortcutExpander{} -// KindFor implements meta.RESTMapper. It expands the resource first, then invokes the wrapped -// mapper. func (e ShortcutExpander) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) { - resource = expandResourceShortcut(resource) - return e.RESTMapper.KindFor(resource) + return e.RESTMapper.KindFor(expandResourceShortcut(resource)) +} + +func (e ShortcutExpander) KindsFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionKind, error) { + return e.RESTMapper.KindsFor(expandResourceShortcut(resource)) +} + +func (e ShortcutExpander) ResourcesFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) { + return e.RESTMapper.ResourcesFor(expandResourceShortcut(resource)) +} + +func (e ShortcutExpander) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) { + return e.RESTMapper.ResourceFor(expandResourceShortcut(resource)) } -// ResourceSingularizer expands the named resource and then singularizes it. func (e ShortcutExpander) ResourceSingularizer(resource string) (string, error) { return e.RESTMapper.ResourceSingularizer(expandResourceShortcut(unversioned.GroupVersionResource{Resource: resource}).Resource) } +func (e ShortcutExpander) RESTMapping(gk unversioned.GroupKind, versions ...string) (*meta.RESTMapping, error) { + return e.RESTMapper.RESTMapping(gk, versions...) +} + +func (e ShortcutExpander) AliasesForResource(resource string) ([]string, bool) { + return e.RESTMapper.AliasesForResource(expandResourceShortcut(unversioned.GroupVersionResource{Resource: resource}).Resource) +} + +// shortForms is the list of short names to their expanded names +var shortForms = map[string]string{ + // Please keep this alphabetized + // If you add an entry here, please also take a look at pkg/kubectl/cmd/cmd.go + // and add an entry to valid_resources when appropriate. + "cs": "componentstatuses", + "ds": "daemonsets", + "ep": "endpoints", + "ev": "events", + "hpa": "horizontalpodautoscalers", + "ing": "ingresses", + "limits": "limitranges", + "no": "nodes", + "ns": "namespaces", + "po": "pods", + "psp": "podSecurityPolicies", + "pvc": "persistentvolumeclaims", + "pv": "persistentvolumes", + "quota": "resourcequotas", + "rc": "replicationcontrollers", + "rs": "replicasets", + "svc": "services", +} + // expandResourceShortcut will return the expanded version of resource // (something that a pkg/api/meta.RESTMapper can understand), if it is // indeed a shortcut. Otherwise, will return resource unmodified. func expandResourceShortcut(resource unversioned.GroupVersionResource) unversioned.GroupVersionResource { - shortForms := map[string]unversioned.GroupVersionResource{ - // Please keep this alphabetized - "cs": api.SchemeGroupVersion.WithResource("componentstatuses"), - "ds": extensions.SchemeGroupVersion.WithResource("daemonsets"), - "ep": api.SchemeGroupVersion.WithResource("endpoints"), - "ev": api.SchemeGroupVersion.WithResource("events"), - "hpa": extensions.SchemeGroupVersion.WithResource("horizontalpodautoscalers"), - "ing": extensions.SchemeGroupVersion.WithResource("ingresses"), - "limits": api.SchemeGroupVersion.WithResource("limitranges"), - "no": api.SchemeGroupVersion.WithResource("nodes"), - "ns": api.SchemeGroupVersion.WithResource("namespaces"), - "po": api.SchemeGroupVersion.WithResource("pods"), - "psp": api.SchemeGroupVersion.WithResource("podSecurityPolicies"), - "pvc": api.SchemeGroupVersion.WithResource("persistentvolumeclaims"), - "pv": api.SchemeGroupVersion.WithResource("persistentvolumes"), - "quota": api.SchemeGroupVersion.WithResource("resourcequotas"), - "rc": api.SchemeGroupVersion.WithResource("replicationcontrollers"), - "rs": extensions.SchemeGroupVersion.WithResource("replicasets"), - "svc": api.SchemeGroupVersion.WithResource("services"), - } if expanded, ok := shortForms[resource.Resource]; ok { - return expanded + // don't change the group or version that's already been specified + resource.Resource = expanded } return resource } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl.test b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl.test deleted file mode 100644 index 152a3526f..000000000 Binary files a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl.test and /dev/null differ diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl_test.go deleted file mode 100644 index 6381b4920..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/kubectl_test.go +++ /dev/null @@ -1,194 +0,0 @@ -/* -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. -*/ - -package kubectl - -import ( - "testing" -) - -func TestParseFileSource(t *testing.T) { - cases := []struct { - name string - input string - key string - filepath string - err bool - }{ - { - name: "success 1", - input: "boo=zoo", - key: "boo", - filepath: "zoo", - err: false, - }, - { - name: "success 2", - input: "boo=/path/to/zoo", - key: "boo", - filepath: "/path/to/zoo", - err: false, - }, - { - name: "success 3", - input: "boo-2=/1/2/3/4/5/zab.txt", - key: "boo-2", - filepath: "/1/2/3/4/5/zab.txt", - err: false, - }, - { - name: "success 4", - input: "boo-=this/seems/weird.txt", - key: "boo-", - filepath: "this/seems/weird.txt", - err: false, - }, - { - name: "success 5", - input: "-key=some/path", - key: "-key", - filepath: "some/path", - err: false, - }, - { - name: "invalid 1", - input: "key==some/path", - err: true, - }, - { - name: "invalid 2", - input: "=key=some/path", - err: true, - }, - { - name: "invalid 3", - input: "==key=/some/other/path", - err: true, - }, - { - name: "invalid 4", - input: "=key", - err: true, - }, - { - name: "invalid 5", - input: "key=", - err: true, - }, - } - - for _, tc := range cases { - key, filepath, err := parseFileSource(tc.input) - if err != nil { - if tc.err { - continue - } - - t.Errorf("%v: unexpected error: %v", tc.name, err) - continue - } - - if tc.err { - t.Errorf("%v: unexpected success", tc.name) - continue - } - - if e, a := tc.key, key; e != a { - t.Errorf("%v: expected key %v; got %v", tc.name, e, a) - continue - } - - if e, a := tc.filepath, filepath; e != a { - t.Errorf("%v: expected filepath %v; got %v", tc.name, e, a) - } - } -} - -func TestParseLiteralSource(t *testing.T) { - cases := []struct { - name string - input string - key string - value string - err bool - }{ - { - name: "success 1", - input: "key=value", - key: "key", - value: "value", - err: false, - }, - { - name: "success 2", - input: "key=value/with/slashes", - key: "key", - value: "value/with/slashes", - err: false, - }, - { - name: "err 1", - input: "key==value", - err: true, - }, - { - name: "err 2", - input: "key=value=", - err: true, - }, - { - name: "err 3", - input: "key2=value==", - err: true, - }, - { - name: "err 4", - input: "==key", - err: true, - }, - { - name: "err 5", - input: "=key=", - err: true, - }, - } - - for _, tc := range cases { - key, value, err := parseLiteralSource(tc.input) - if err != nil { - if tc.err { - continue - } - - t.Errorf("%v: unexpected error: %v", tc.name, err) - continue - } - - if tc.err { - t.Errorf("%v: unexpected success", tc.name) - continue - } - - if e, a := tc.key, key; e != a { - t.Errorf("%v: expected key %v; got %v", tc.name, e, a) - continue - } - - if e, a := tc.value, value; e != a { - t.Errorf("%v: expected value %v; got %v", tc.name, e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/namespace_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/namespace_test.go deleted file mode 100644 index b0445bd29..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/namespace_test.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -func TestNamespaceGenerate(t *testing.T) { - tests := []struct { - params map[string]interface{} - expected *api.Namespace - expectErr bool - }{ - { - params: map[string]interface{}{ - "name": "foo", - }, - expected: &api.Namespace{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - }, - expectErr: false, - }, - { - params: map[string]interface{}{}, - expectErr: true, - }, - } - generator := NamespaceGeneratorV1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*api.Namespace), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*api.Namespace)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/proxy_server.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/proxy_server.go index bfbb9b6a0..082b542fc 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/proxy_server.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/proxy_server.go @@ -28,7 +28,7 @@ import ( "time" "github.com/golang/glog" - client "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/util" ) @@ -146,7 +146,7 @@ type ProxyServer struct { // NewProxyServer creates and installs a new ProxyServer. // It automatically registers the created ProxyServer to http.DefaultServeMux. // 'filter', if non-nil, protects requests to the api only. -func NewProxyServer(filebase string, apiProxyPrefix string, staticPrefix string, filter *FilterServer, cfg *client.Config) (*ProxyServer, error) { +func NewProxyServer(filebase string, apiProxyPrefix string, staticPrefix string, filter *FilterServer, cfg *restclient.Config) (*ProxyServer, error) { host := cfg.Host if !strings.HasSuffix(host, "/") { host = host + "/" @@ -156,7 +156,7 @@ func NewProxyServer(filebase string, apiProxyPrefix string, staticPrefix string, return nil, err } proxy := newProxy(target) - if proxy.Transport, err = client.TransportFor(cfg); err != nil { + if proxy.Transport, err = restclient.TransportFor(cfg); err != nil { return nil, err } proxyServer := http.Handler(proxy) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/proxy_server_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/proxy_server_test.go deleted file mode 100644 index 494b926cc..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/proxy_server_test.go +++ /dev/null @@ -1,337 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "path/filepath" - "strings" - "testing" - - client "k8s.io/kubernetes/pkg/client/unversioned" -) - -func TestAccept(t *testing.T) { - tests := []struct { - acceptPaths string - rejectPaths string - acceptHosts string - path string - host string - method string - expectAccept bool - }{ - - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods", - host: "127.0.0.1", - method: "GET", - expectAccept: true, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods", - host: "localhost", - method: "GET", - expectAccept: true, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods/foo/exec", - host: "127.0.0.1", - method: "GET", - expectAccept: false, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods/foo/attach", - host: "127.0.0.1", - method: "GET", - expectAccept: false, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods", - host: "evil.com", - method: "GET", - expectAccept: false, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods", - host: "localhost.evil.com", - method: "GET", - expectAccept: false, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods", - host: "127a0b0c1", - method: "GET", - expectAccept: false, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/ui", - host: "localhost", - method: "GET", - expectAccept: true, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods", - host: "localhost", - method: "POST", - expectAccept: false, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods/somepod", - host: "localhost", - method: "PUT", - expectAccept: false, - }, - { - acceptPaths: DefaultPathAcceptRE, - rejectPaths: DefaultPathRejectRE, - acceptHosts: DefaultHostAcceptRE, - path: "/api/v1/pods/somepod", - host: "localhost", - method: "PATCH", - expectAccept: false, - }, - } - for _, test := range tests { - filter := &FilterServer{ - AcceptPaths: MakeRegexpArrayOrDie(test.acceptPaths), - RejectPaths: MakeRegexpArrayOrDie(test.rejectPaths), - AcceptHosts: MakeRegexpArrayOrDie(test.acceptHosts), - RejectMethods: MakeRegexpArrayOrDie(DefaultMethodRejectRE), - } - accept := filter.accept(test.method, test.path, test.host) - if accept != test.expectAccept { - t.Errorf("expected: %v, got %v for %#v", test.expectAccept, accept, test) - } - } -} - -func TestRegexpMatch(t *testing.T) { - tests := []struct { - str string - regexps string - expectMatch bool - }{ - { - str: "foo", - regexps: "bar,.*", - expectMatch: true, - }, - { - str: "foo", - regexps: "bar,fo.*", - expectMatch: true, - }, - { - str: "bar", - regexps: "bar,fo.*", - expectMatch: true, - }, - { - str: "baz", - regexps: "bar,fo.*", - expectMatch: false, - }, - } - for _, test := range tests { - match := matchesRegexp(test.str, MakeRegexpArrayOrDie(test.regexps)) - if test.expectMatch != match { - t.Errorf("expected: %v, found: %v, for %s and %v", test.expectMatch, match, test.str, test.regexps) - } - } -} - -func TestFileServing(t *testing.T) { - const ( - fname = "test.txt" - data = "This is test data" - ) - dir, err := ioutil.TempDir("", "data") - if err != nil { - t.Fatalf("error creating tmp dir: %v", err) - } - if err := ioutil.WriteFile(filepath.Join(dir, fname), []byte(data), 0755); err != nil { - t.Fatalf("error writing tmp file: %v", err) - } - - const prefix = "/foo/" - handler := newFileHandler(prefix, dir) - server := httptest.NewServer(handler) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - url := server.URL + prefix + fname - res, err := http.Get(url) - if err != nil { - t.Fatalf("http.Get(%q) error: %v", url, err) - } - defer res.Body.Close() - - if res.StatusCode != http.StatusOK { - t.Errorf("res.StatusCode = %d; want %d", res.StatusCode, http.StatusOK) - } - b, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatalf("error reading resp body: %v", err) - } - if string(b) != data { - t.Errorf("have %q; want %q", string(b), data) - } -} - -func TestAPIRequests(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - fmt.Fprintf(w, "%s %s %s", r.Method, r.RequestURI, string(b)) - })) - // TODO: Uncomment when fix #19254 - // defer ts.Close() - - // httptest.NewServer should always generate a valid URL. - target, _ := url.Parse(ts.URL) - proxy := newProxy(target) - - tests := []struct{ method, body string }{ - {"GET", ""}, - {"DELETE", ""}, - {"POST", "test payload"}, - {"PUT", "test payload"}, - } - - const path = "/api/test?fields=ID%3Dfoo&labels=key%3Dvalue" - for i, tt := range tests { - r, err := http.NewRequest(tt.method, path, strings.NewReader(tt.body)) - if err != nil { - t.Errorf("error creating request: %v", err) - continue - } - w := httptest.NewRecorder() - proxy.ServeHTTP(w, r) - if w.Code != http.StatusOK { - t.Errorf("%d: proxy.ServeHTTP w.Code = %d; want %d", i, w.Code, http.StatusOK) - } - want := strings.Join([]string{tt.method, path, tt.body}, " ") - if w.Body.String() != want { - t.Errorf("%d: response body = %q; want %q", i, w.Body.String(), want) - } - } -} - -func TestPathHandling(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, r.URL.Path) - })) - // TODO: Uncomment when fix #19254 - // defer ts.Close() - - table := []struct { - prefix string - reqPath string - expectPath string - }{ - {"/api/", "/metrics", "404 page not found\n"}, - {"/api/", "/api/metrics", "/api/metrics"}, - {"/api/", "/api/v1/pods/", "/api/v1/pods/"}, - {"/", "/metrics", "/metrics"}, - {"/", "/api/v1/pods/", "/api/v1/pods/"}, - {"/custom/", "/metrics", "404 page not found\n"}, - {"/custom/", "/api/metrics", "404 page not found\n"}, - {"/custom/", "/api/v1/pods/", "404 page not found\n"}, - {"/custom/", "/custom/api/metrics", "/api/metrics"}, - {"/custom/", "/custom/api/v1/pods/", "/api/v1/pods/"}, - } - - cc := &client.Config{ - Host: ts.URL, - } - - for _, item := range table { - func() { - p, err := NewProxyServer("", item.prefix, "/not/used/for/this/test", nil, cc) - if err != nil { - t.Fatalf("%#v: %v", item, err) - } - pts := httptest.NewServer(p.handler) - // TODO: Uncomment when fix #19254 - // defer pts.Close() - - r, err := http.Get(pts.URL + item.reqPath) - if err != nil { - t.Fatalf("%#v: %v", item, err) - } - body, err := ioutil.ReadAll(r.Body) - r.Body.Close() - if err != nil { - t.Fatalf("%#v: %v", item, err) - } - if e, a := item.expectPath, string(body); e != a { - t.Errorf("%#v: Wanted %q, got %q", item, e, a) - } - }() - } -} - -func TestExtractHost(t *testing.T) { - fixtures := map[string]string{ - "localhost:8085": "localhost", - "marmalade": "marmalade", - } - for header, expected := range fixtures { - host := extractHost(header) - if host != expected { - t.Fatalf("%s != %s", host, expected) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/builder.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/builder.go index 61b0f1131..7b7bc1504 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/builder.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/builder.go @@ -126,9 +126,8 @@ func (b *Builder) FilenameParam(enforceNamespace bool, paths ...string) *Builder func (b *Builder) URL(urls ...*url.URL) *Builder { for _, u := range urls { b.paths = append(b.paths, &URLVisitor{ - Mapper: b.mapper, - URL: u, - Schema: b.schema, + URL: u, + StreamVisitor: NewStreamVisitor(nil, b.mapper, u.String(), b.schema), }) } return b @@ -434,20 +433,36 @@ func (b *Builder) SingleResourceType() *Builder { return b } +// mappingFor returns the RESTMapping for the Kind referenced by the resource. +// prefers a fully specified GroupVersionResource match. If we don't have one match on GroupResource +func (b *Builder) mappingFor(resourceArg string) (*meta.RESTMapping, error) { + fullySpecifiedGVR, groupResource := unversioned.ParseResourceArg(resourceArg) + gvk := unversioned.GroupVersionKind{} + if fullySpecifiedGVR != nil { + gvk, _ = b.mapper.KindFor(*fullySpecifiedGVR) + } + if gvk.IsEmpty() { + var err error + gvk, err = b.mapper.KindFor(groupResource.WithVersion("")) + if err != nil { + return nil, err + } + } + + return b.mapper.RESTMapping(gvk.GroupKind(), gvk.Version) +} + func (b *Builder) resourceMappings() ([]*meta.RESTMapping, error) { if len(b.resources) > 1 && b.singleResourceType { return nil, fmt.Errorf("you may only specify a single resource type") } mappings := []*meta.RESTMapping{} for _, r := range b.resources { - gvk, err := b.mapper.KindFor(unversioned.GroupVersionResource{Resource: r}) - if err != nil { - return nil, err - } - mapping, err := b.mapper.RESTMapping(gvk.GroupKind(), gvk.Version) + mapping, err := b.mappingFor(r) if err != nil { return nil, err } + mappings = append(mappings, mapping) } return mappings, nil @@ -460,14 +475,11 @@ func (b *Builder) resourceTupleMappings() (map[string]*meta.RESTMapping, error) if _, ok := mappings[r.Resource]; ok { continue } - gvk, err := b.mapper.KindFor(unversioned.GroupVersionResource{Resource: r.Resource}) - if err != nil { - return nil, err - } - mapping, err := b.mapper.RESTMapping(gvk.GroupKind(), gvk.Version) + mapping, err := b.mappingFor(r.Resource) if err != nil { return nil, err } + mappings[mapping.Resource] = mapping mappings[r.Resource] = mapping canonical[mapping.Resource] = struct{}{} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/builder_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/builder_test.go deleted file mode 100644 index 1fad662b6..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/builder_test.go +++ /dev/null @@ -1,1072 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package resource - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "testing" - - "github.com/ghodss/yaml" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/runtime" - utilerrors "k8s.io/kubernetes/pkg/util/errors" - "k8s.io/kubernetes/pkg/watch" - watchjson "k8s.io/kubernetes/pkg/watch/json" -) - -func stringBody(body string) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(body))) -} - -func watchBody(events ...watch.Event) string { - buf := &bytes.Buffer{} - enc := watchjson.NewEncoder(buf, testapi.Default.Codec()) - for _, e := range events { - enc.Encode(&e) - } - return buf.String() -} - -func fakeClient() ClientMapper { - return ClientMapperFunc(func(*meta.RESTMapping) (RESTClient, error) { - return &fake.RESTClient{}, nil - }) -} - -func fakeClientWith(testName string, t *testing.T, data map[string]string) ClientMapper { - return ClientMapperFunc(func(*meta.RESTMapping) (RESTClient, error) { - return &fake.RESTClient{ - Codec: testapi.Default.Codec(), - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - p := req.URL.Path - q := req.URL.RawQuery - if len(q) != 0 { - p = p + "?" + q - } - body, ok := data[p] - if !ok { - t.Fatalf("%s: unexpected request: %s (%s)\n%#v", testName, p, req.URL, req) - } - return &http.Response{ - StatusCode: http.StatusOK, - Body: stringBody(body), - }, nil - }), - }, nil - }) -} - -func testData() (*api.PodList, *api.ServiceList) { - pods := &api.PodList{ - ListMeta: unversioned.ListMeta{ - ResourceVersion: "15", - }, - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - { - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "test", ResourceVersion: "11"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - }, - } - svc := &api.ServiceList{ - ListMeta: unversioned.ListMeta{ - ResourceVersion: "16", - }, - Items: []api.Service{ - { - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "12"}, - Spec: api.ServiceSpec{ - Type: "ClusterIP", - SessionAffinity: "None", - }, - }, - }, - } - return pods, svc -} - -func streamTestData() (io.Reader, *api.PodList, *api.ServiceList) { - pods, svc := testData() - r, w := io.Pipe() - go func() { - defer w.Close() - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), pods))) - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), svc))) - }() - return r, pods, svc -} - -func JSONToYAMLOrDie(in []byte) []byte { - data, err := yaml.JSONToYAML(in) - if err != nil { - panic(err) - } - return data -} - -func streamYAMLTestData() (io.Reader, *api.PodList, *api.ServiceList) { - pods, svc := testData() - r, w := io.Pipe() - go func() { - defer w.Close() - w.Write(JSONToYAMLOrDie([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), pods)))) - w.Write([]byte("\n---\n")) - w.Write(JSONToYAMLOrDie([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), svc)))) - }() - return r, pods, svc -} - -func streamTestObject(obj runtime.Object) io.Reader { - r, w := io.Pipe() - go func() { - defer w.Close() - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), obj))) - }() - return r -} - -type testVisitor struct { - InjectErr error - Infos []*Info -} - -func (v *testVisitor) Handle(info *Info, err error) error { - if err != nil { - return err - } - v.Infos = append(v.Infos, info) - return v.InjectErr -} - -func (v *testVisitor) Objects() []runtime.Object { - objects := []runtime.Object{} - for i := range v.Infos { - objects = append(objects, v.Infos[i].Object) - } - return objects -} - -func TestPathBuilderAndVersionedObjectNotDefaulted(t *testing.T) { - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - FilenameParam(false, "../../../docs/user-guide/update-demo/kitten-rc.yaml") - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || !singular || len(test.Infos) != 1 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - - info := test.Infos[0] - if info.Name != "update-demo-kitten" || info.Namespace != "" || info.Object == nil { - t.Errorf("unexpected info: %#v", info) - } - version, ok := info.VersionedObject.(*v1.ReplicationController) - // versioned object does not have defaulting applied - if info.VersionedObject == nil || !ok || version.Spec.Replicas != nil { - t.Errorf("unexpected versioned object: %#v", info.VersionedObject) - } -} - -func TestNodeBuilder(t *testing.T) { - node := &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "node1", Namespace: "should-not-have", ResourceVersion: "10"}, - Spec: api.NodeSpec{}, - Status: api.NodeStatus{ - Capacity: api.ResourceList{ - api.ResourceCPU: resource.MustParse("1000m"), - api.ResourceMemory: resource.MustParse("1Mi"), - }, - }, - } - r, w := io.Pipe() - go func() { - defer w.Close() - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), node))) - }() - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").Stream(r, "STDIN") - - test := &testVisitor{} - - err := b.Do().Visit(test.Handle) - if err != nil || len(test.Infos) != 1 { - t.Fatalf("unexpected response: %v %#v", err, test.Infos) - } - info := test.Infos[0] - if info.Name != "node1" || info.Namespace != "" || info.Object == nil { - t.Errorf("unexpected info: %#v", info) - } -} - -func TestPathBuilderWithMultiple(t *testing.T) { - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - FilenameParam(false, "../../../examples/guestbook/redis-master-controller.yaml"). - FilenameParam(false, "../../../examples/pod"). - NamespaceParam("test").DefaultNamespace() - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || singular || len(test.Infos) != 2 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - - info := test.Infos[0] - if _, ok := info.Object.(*api.ReplicationController); !ok || info.Name != "redis-master" || info.Namespace != "test" { - t.Errorf("unexpected info: %#v", info) - } - info = test.Infos[1] - if _, ok := info.Object.(*api.Pod); !ok || info.Name != "nginx" || info.Namespace != "test" { - t.Errorf("unexpected info: %#v", info) - } -} - -func TestDirectoryBuilder(t *testing.T) { - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - FilenameParam(false, "../../../examples/guestbook"). - NamespaceParam("test").DefaultNamespace() - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || singular || len(test.Infos) < 4 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - - found := false - for _, info := range test.Infos { - if info.Name == "redis-master" && info.Namespace == "test" && info.Object != nil { - found = true - } - } - if !found { - t.Errorf("unexpected responses: %#v", test.Infos) - } -} - -func TestNamespaceOverride(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: "foo", Name: "test"}}))) - })) - // TODO: Uncomment when fix #19254 - // defer s.Close() - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - FilenameParam(false, s.URL). - NamespaceParam("test") - - test := &testVisitor{} - - err := b.Do().Visit(test.Handle) - if err != nil || len(test.Infos) != 1 && test.Infos[0].Namespace != "foo" { - t.Fatalf("unexpected response: %v %#v", err, test.Infos) - } - - b = NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - FilenameParam(true, s.URL). - NamespaceParam("test") - - test = &testVisitor{} - - err = b.Do().Visit(test.Handle) - if err == nil { - t.Fatalf("expected namespace error. got: %#v", test.Infos) - } -} - -func TestURLBuilder(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: "foo", Name: "test"}}))) - })) - // TODO: Uncomment when fix #19254 - // defer s.Close() - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - FilenameParam(false, s.URL). - NamespaceParam("test") - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || !singular || len(test.Infos) != 1 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - info := test.Infos[0] - if info.Name != "test" || info.Namespace != "foo" || info.Object == nil { - t.Errorf("unexpected info: %#v", info) - } -} - -func TestURLBuilderRequireNamespace(t *testing.T) { - s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), &api.Pod{ObjectMeta: api.ObjectMeta{Namespace: "foo", Name: "test"}}))) - })) - // TODO: Uncomment when fix #19254 - // defer s.Close() - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - FilenameParam(false, s.URL). - NamespaceParam("test").RequireNamespace() - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err == nil || !singular || len(test.Infos) != 0 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } -} - -func TestResourceByName(t *testing.T) { - pods, _ := testData() - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods/foo": runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[0]), - }), testapi.Default.Codec()). - NamespaceParam("test") - - test := &testVisitor{} - singular := false - - if b.Do().Err() == nil { - t.Errorf("unexpected non-error") - } - - b.ResourceTypeOrNameArgs(true, "pods", "foo") - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || !singular || len(test.Infos) != 1 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - if !reflect.DeepEqual(&pods.Items[0], test.Objects()[0]) { - t.Errorf("unexpected object: %#v", test.Objects()[0]) - } - - mapping, err := b.Do().ResourceMapping() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "pods" { - t.Errorf("unexpected resource mapping: %#v", mapping) - } -} - -func TestMultipleResourceByTheSameName(t *testing.T) { - pods, svcs := testData() - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods/foo": runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[0]), - "/namespaces/test/pods/baz": runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[1]), - "/namespaces/test/services/foo": runtime.EncodeOrDie(testapi.Default.Codec(), &svcs.Items[0]), - "/namespaces/test/services/baz": runtime.EncodeOrDie(testapi.Default.Codec(), &svcs.Items[0]), - }), testapi.Default.Codec()). - NamespaceParam("test") - - test := &testVisitor{} - singular := false - - if b.Do().Err() == nil { - t.Errorf("unexpected non-error") - } - - b.ResourceTypeOrNameArgs(true, "pods,services", "foo", "baz") - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || singular || len(test.Infos) != 4 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &svcs.Items[0], &svcs.Items[0]}, test.Objects()) { - t.Errorf("unexpected visited objects: %#v", test.Objects()) - } - - if _, err := b.Do().ResourceMapping(); err == nil { - t.Errorf("unexpected non-error") - } -} - -func TestResourceNames(t *testing.T) { - pods, svc := testData() - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods/foo": runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[0]), - "/namespaces/test/services/baz": runtime.EncodeOrDie(testapi.Default.Codec(), &svc.Items[0]), - }), testapi.Default.Codec()). - NamespaceParam("test") - - test := &testVisitor{} - - if b.Do().Err() == nil { - t.Errorf("unexpected non-error") - } - - b.ResourceNames("pods", "foo", "services/baz") - - err := b.Do().Visit(test.Handle) - if err != nil || len(test.Infos) != 2 { - t.Fatalf("unexpected response: %v %#v", err, test.Infos) - } - if !reflect.DeepEqual(&pods.Items[0], test.Objects()[0]) { - t.Errorf("unexpected object: \n%#v, expected: \n%#v", test.Objects()[0], &pods.Items[0]) - } - if !reflect.DeepEqual(&svc.Items[0], test.Objects()[1]) { - t.Errorf("unexpected object: \n%#v, expected: \n%#v", test.Objects()[1], &svc.Items[0]) - } -} - -func TestResourceByNameWithoutRequireObject(t *testing.T) { - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{}), testapi.Default.Codec()). - NamespaceParam("test") - - test := &testVisitor{} - singular := false - - if b.Do().Err() == nil { - t.Errorf("unexpected non-error") - } - - b.ResourceTypeOrNameArgs(true, "pods", "foo").RequireObject(false) - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || !singular || len(test.Infos) != 1 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - if test.Infos[0].Name != "foo" { - t.Errorf("unexpected name: %#v", test.Infos[0].Name) - } - if test.Infos[0].Object != nil { - t.Errorf("unexpected object: %#v", test.Infos[0].Object) - } - - mapping, err := b.Do().ResourceMapping() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.GroupVersionKind.Kind != "Pod" || mapping.Resource != "pods" { - t.Errorf("unexpected resource mapping: %#v", mapping) - } -} - -func TestResourceByNameAndEmptySelector(t *testing.T) { - pods, _ := testData() - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods/foo": runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[0]), - }), testapi.Default.Codec()). - NamespaceParam("test"). - SelectorParam(""). - ResourceTypeOrNameArgs(true, "pods", "foo") - - singular := false - infos, err := b.Do().IntoSingular(&singular).Infos() - if err != nil || !singular || len(infos) != 1 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, infos) - } - if !reflect.DeepEqual(&pods.Items[0], infos[0].Object) { - t.Errorf("unexpected object: %#v", infos[0]) - } - - mapping, err := b.Do().ResourceMapping() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "pods" { - t.Errorf("unexpected resource mapping: %#v", mapping) - } -} - -func TestSelector(t *testing.T) { - pods, svc := testData() - labelKey := unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods?" + labelKey + "=a%3Db": runtime.EncodeOrDie(testapi.Default.Codec(), pods), - "/namespaces/test/services?" + labelKey + "=a%3Db": runtime.EncodeOrDie(testapi.Default.Codec(), svc), - }), testapi.Default.Codec()). - SelectorParam("a=b"). - NamespaceParam("test"). - Flatten() - - test := &testVisitor{} - singular := false - - if b.Do().Err() == nil { - t.Errorf("unexpected non-error") - } - - b.ResourceTypeOrNameArgs(true, "pods,service") - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || singular || len(test.Infos) != 3 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &svc.Items[0]}, test.Objects()) { - t.Errorf("unexpected visited objects: %#v", test.Objects()) - } - - if _, err := b.Do().ResourceMapping(); err == nil { - t.Errorf("unexpected non-error") - } -} - -func TestSelectorRequiresKnownTypes(t *testing.T) { - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - SelectorParam("a=b"). - NamespaceParam("test"). - ResourceTypes("unknown") - - if b.Do().Err() == nil { - t.Errorf("unexpected non-error") - } -} - -func TestSingleResourceType(t *testing.T) { - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - SelectorParam("a=b"). - SingleResourceType(). - ResourceTypeOrNameArgs(true, "pods,services") - - if b.Do().Err() == nil { - t.Errorf("unexpected non-error") - } -} - -func TestResourceTuple(t *testing.T) { - expectNoErr := func(err error) bool { return err == nil } - expectErr := func(err error) bool { return err != nil } - testCases := map[string]struct { - args []string - errFn func(error) bool - }{ - "valid": { - args: []string{"pods/foo"}, - errFn: expectNoErr, - }, - "valid multiple with name indirection": { - args: []string{"pods/foo", "pod/bar"}, - errFn: expectNoErr, - }, - "valid multiple with namespaced and non-namespaced types": { - args: []string{"nodes/foo", "pod/bar"}, - errFn: expectNoErr, - }, - "mixed arg types": { - args: []string{"pods/foo", "bar"}, - errFn: expectErr, - }, - /*"missing resource": { - args: []string{"pods/foo2"}, - errFn: expectNoErr, // not an error because resources are lazily visited - },*/ - "comma in resource": { - args: []string{",pods/foo"}, - errFn: expectErr, - }, - "multiple types in resource": { - args: []string{"pods,services/foo"}, - errFn: expectErr, - }, - "unknown resource type": { - args: []string{"unknown/foo"}, - errFn: expectErr, - }, - "leading slash": { - args: []string{"/bar"}, - errFn: expectErr, - }, - "trailing slash": { - args: []string{"bar/"}, - errFn: expectErr, - }, - } - for k, testCase := range testCases { - for _, requireObject := range []bool{true, false} { - expectedRequests := map[string]string{} - if requireObject { - pods, _ := testData() - expectedRequests = map[string]string{ - "/namespaces/test/pods/foo": runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[0]), - "/namespaces/test/pods/bar": runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[0]), - "/nodes/foo": runtime.EncodeOrDie(testapi.Default.Codec(), &api.Node{ObjectMeta: api.ObjectMeta{Name: "foo"}}), - } - } - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith(k, t, expectedRequests), testapi.Default.Codec()). - NamespaceParam("test").DefaultNamespace(). - ResourceTypeOrNameArgs(true, testCase.args...).RequireObject(requireObject) - - r := b.Do() - - if !testCase.errFn(r.Err()) { - t.Errorf("%s: unexpected error: %v", k, r.Err()) - } - if r.Err() != nil { - continue - } - switch { - case (r.singular && len(testCase.args) != 1), - (!r.singular && len(testCase.args) == 1): - t.Errorf("%s: result had unexpected singular value", k) - } - info, err := r.Infos() - if err != nil { - // test error - continue - } - if len(info) != len(testCase.args) { - t.Errorf("%s: unexpected number of infos returned: %#v", k, info) - } - } - } -} - -func TestStream(t *testing.T) { - r, pods, rc := streamTestData() - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").Stream(r, "STDIN").Flatten() - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || singular || len(test.Infos) != 3 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &rc.Items[0]}, test.Objects()) { - t.Errorf("unexpected visited objects: %#v", test.Objects()) - } -} - -func TestYAMLStream(t *testing.T) { - r, pods, rc := streamYAMLTestData() - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").Stream(r, "STDIN").Flatten() - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || singular || len(test.Infos) != 3 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &rc.Items[0]}, test.Objects()) { - t.Errorf("unexpected visited objects: %#v", test.Objects()) - } -} - -func TestMultipleObject(t *testing.T) { - r, pods, svc := streamTestData() - obj, err := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").Stream(r, "STDIN").Flatten(). - Do().Object() - - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - expected := &api.List{ - Items: []runtime.Object{ - &pods.Items[0], - &pods.Items[1], - &svc.Items[0], - }, - } - if !api.Semantic.DeepDerivative(expected, obj) { - t.Errorf("unexpected visited objects: %#v", obj) - } -} - -func TestContinueOnErrorVisitor(t *testing.T) { - r, _, _ := streamTestData() - req := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - ContinueOnError(). - NamespaceParam("test").Stream(r, "STDIN").Flatten(). - Do() - count := 0 - testErr := fmt.Errorf("test error") - err := req.Visit(func(_ *Info, _ error) error { - count++ - if count > 1 { - return testErr - } - return nil - }) - if err == nil { - t.Fatalf("unexpected error: %v", err) - } - if count != 3 { - t.Fatalf("did not visit all infos: %d", count) - } - agg, ok := err.(utilerrors.Aggregate) - if !ok { - t.Fatalf("unexpected error: %v", err) - } - if len(agg.Errors()) != 2 || agg.Errors()[0] != testErr || agg.Errors()[1] != testErr { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestSingularObject(t *testing.T) { - obj, err := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").DefaultNamespace(). - FilenameParam(false, "../../../examples/guestbook/redis-master-controller.yaml"). - Flatten(). - Do().Object() - - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - rc, ok := obj.(*api.ReplicationController) - if !ok { - t.Fatalf("unexpected object: %#v", obj) - } - if rc.Name != "redis-master" || rc.Namespace != "test" { - t.Errorf("unexpected controller: %#v", rc) - } -} - -func TestSingularObjectNoExtension(t *testing.T) { - obj, err := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").DefaultNamespace(). - FilenameParam(false, "../../../examples/pod"). - Flatten(). - Do().Object() - - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - pod, ok := obj.(*api.Pod) - if !ok { - t.Fatalf("unexpected object: %#v", obj) - } - if pod.Name != "nginx" || pod.Namespace != "test" { - t.Errorf("unexpected pod: %#v", pod) - } -} - -func TestSingularRootScopedObject(t *testing.T) { - node := &api.Node{ObjectMeta: api.ObjectMeta{Name: "test"}, Spec: api.NodeSpec{ExternalID: "test"}} - r := streamTestObject(node) - infos, err := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").DefaultNamespace(). - Stream(r, "STDIN"). - Flatten(). - Do().Infos() - - if err != nil || len(infos) != 1 { - t.Fatalf("unexpected error: %v", err) - } - - if infos[0].Namespace != "" { - t.Errorf("namespace should be empty: %#v", infos[0]) - } - n, ok := infos[0].Object.(*api.Node) - if !ok { - t.Fatalf("unexpected object: %#v", infos[0].Object) - } - if n.Name != "test" || n.Namespace != "" { - t.Errorf("unexpected object: %#v", n) - } -} - -func TestListObject(t *testing.T) { - pods, _ := testData() - labelKey := unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods?" + labelKey + "=a%3Db": runtime.EncodeOrDie(testapi.Default.Codec(), pods), - }), testapi.Default.Codec()). - SelectorParam("a=b"). - NamespaceParam("test"). - ResourceTypeOrNameArgs(true, "pods"). - Flatten() - - obj, err := b.Do().Object() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - list, ok := obj.(*api.List) - if !ok { - t.Fatalf("unexpected object: %#v", obj) - } - if list.ResourceVersion != pods.ResourceVersion || len(list.Items) != 2 { - t.Errorf("unexpected list: %#v", list) - } - - mapping, err := b.Do().ResourceMapping() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "pods" { - t.Errorf("unexpected resource mapping: %#v", mapping) - } -} - -func TestListObjectWithDifferentVersions(t *testing.T) { - pods, svc := testData() - labelKey := unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String()) - obj, err := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods?" + labelKey + "=a%3Db": runtime.EncodeOrDie(testapi.Default.Codec(), pods), - "/namespaces/test/services?" + labelKey + "=a%3Db": runtime.EncodeOrDie(testapi.Default.Codec(), svc), - }), testapi.Default.Codec()). - SelectorParam("a=b"). - NamespaceParam("test"). - ResourceTypeOrNameArgs(true, "pods,services"). - Flatten(). - Do().Object() - - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - list, ok := obj.(*api.List) - if !ok { - t.Fatalf("unexpected object: %#v", obj) - } - // resource version differs between type lists, so it's not possible to get a single version. - if list.ResourceVersion != "" || len(list.Items) != 3 { - t.Errorf("unexpected list: %#v", list) - } -} - -func TestWatch(t *testing.T) { - _, svc := testData() - w, err := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/watch/namespaces/test/services/redis-master?resourceVersion=12": watchBody(watch.Event{ - Type: watch.Added, - Object: &svc.Items[0], - }), - }), testapi.Default.Codec()). - NamespaceParam("test").DefaultNamespace(). - FilenameParam(false, "../../../examples/guestbook/redis-master-service.yaml").Flatten(). - Do().Watch("12") - - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - defer w.Stop() - ch := w.ResultChan() - select { - case obj := <-ch: - if obj.Type != watch.Added { - t.Fatalf("unexpected watch event %#v", obj) - } - service, ok := obj.Object.(*api.Service) - if !ok { - t.Fatalf("unexpected object: %#v", obj) - } - if service.Name != "baz" || service.ResourceVersion != "12" { - t.Errorf("unexpected service: %#v", service) - } - } -} - -func TestWatchMultipleError(t *testing.T) { - _, err := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - NamespaceParam("test").DefaultNamespace(). - FilenameParam(false, "../../../examples/guestbook/redis-master-controller.yaml").Flatten(). - FilenameParam(false, "../../../examples/guestbook/redis-master-controller.yaml").Flatten(). - Do().Watch("") - - if err == nil { - t.Fatalf("unexpected non-error") - } -} - -func TestLatest(t *testing.T) { - r, _, _ := streamTestData() - newPod := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "13"}, - } - newPod2 := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "bar", Namespace: "test", ResourceVersion: "14"}, - } - newSvc := &api.Service{ - ObjectMeta: api.ObjectMeta{Name: "baz", Namespace: "test", ResourceVersion: "15"}, - } - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClientWith("", t, map[string]string{ - "/namespaces/test/pods/foo": runtime.EncodeOrDie(testapi.Default.Codec(), newPod), - "/namespaces/test/pods/bar": runtime.EncodeOrDie(testapi.Default.Codec(), newPod2), - "/namespaces/test/services/baz": runtime.EncodeOrDie(testapi.Default.Codec(), newSvc), - }), testapi.Default.Codec()). - NamespaceParam("other").Stream(r, "STDIN").Flatten().Latest() - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err != nil || singular || len(test.Infos) != 3 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - if !api.Semantic.DeepDerivative([]runtime.Object{newPod, newPod2, newSvc}, test.Objects()) { - t.Errorf("unexpected visited objects: %#v", test.Objects()) - } -} - -func TestReceiveMultipleErrors(t *testing.T) { - pods, svc := testData() - - r, w := io.Pipe() - go func() { - defer w.Close() - w.Write([]byte(`{}`)) - w.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), &pods.Items[0]))) - }() - - r2, w2 := io.Pipe() - go func() { - defer w2.Close() - w2.Write([]byte(`{}`)) - w2.Write([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), &svc.Items[0]))) - }() - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()). - Stream(r, "1").Stream(r2, "2"). - ContinueOnError() - - test := &testVisitor{} - singular := false - - err := b.Do().IntoSingular(&singular).Visit(test.Handle) - if err == nil || singular || len(test.Infos) != 2 { - t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) - } - - errs, ok := err.(utilerrors.Aggregate) - if !ok { - t.Fatalf("unexpected error: %v", reflect.TypeOf(err)) - } - if len(errs.Errors()) != 2 { - t.Errorf("unexpected errors %v", errs) - } -} - -func TestReplaceAliases(t *testing.T) { - tests := []struct { - name string - arg string - expected string - }{ - { - name: "no-replacement", - arg: "service", - expected: "service", - }, - { - name: "all-replacement", - arg: "all", - expected: "rc,svc,pods,pvc", - }, - { - name: "alias-in-comma-separated-arg", - arg: "all,secrets", - expected: "rc,svc,pods,pvc,secrets", - }, - } - - b := NewBuilder(testapi.Default.RESTMapper(), api.Scheme, fakeClient(), testapi.Default.Codec()) - - for _, test := range tests { - replaced := b.replaceAliases(test.arg) - if replaced != test.expected { - t.Errorf("%s: unexpected argument: expected %s, got %s", test.name, test.expected, replaced) - } - } -} - -func TestHasNames(t *testing.T) { - tests := []struct { - args []string - expectedHasName bool - expectedError error - }{ - { - args: []string{""}, - expectedHasName: false, - expectedError: nil, - }, - { - args: []string{"rc"}, - expectedHasName: false, - expectedError: nil, - }, - { - args: []string{"rc,pod,svc"}, - expectedHasName: false, - expectedError: nil, - }, - { - args: []string{"rc/foo"}, - expectedHasName: true, - expectedError: nil, - }, - { - args: []string{"rc", "foo"}, - expectedHasName: true, - expectedError: nil, - }, - { - args: []string{"rc,pod,svc", "foo"}, - expectedHasName: true, - expectedError: nil, - }, - { - args: []string{"rc/foo", "rc/bar", "rc/zee"}, - expectedHasName: true, - expectedError: nil, - }, - { - args: []string{"rc/foo", "bar"}, - expectedHasName: false, - expectedError: fmt.Errorf("when passing arguments in resource/name form, all arguments must include the resource"), - }, - } - for _, test := range tests { - hasNames, err := HasNames(test.args) - if !reflect.DeepEqual(test.expectedError, err) { - t.Errorf("expected HasName to error %v, got %s", test.expectedError, err) - } - if hasNames != test.expectedHasName { - t.Errorf("expected HasName to return %v for %s", test.expectedHasName, test.args) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/helper_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/helper_test.go deleted file mode 100644 index bfb05f7f7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/helper_test.go +++ /dev/null @@ -1,498 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package resource - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "net/http" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/runtime" -) - -func objBody(obj runtime.Object) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(testapi.Default.Codec(), obj)))) -} - -// splitPath returns the segments for a URL path. -func splitPath(path string) []string { - path = strings.Trim(path, "/") - if path == "" { - return []string{} - } - return strings.Split(path, "/") -} - -func TestHelperDelete(t *testing.T) { - tests := []struct { - Err bool - Req func(*http.Request) bool - Resp *http.Response - HttpErr error - }{ - { - HttpErr: errors.New("failure"), - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusNotFound, - Body: objBody(&unversioned.Status{Status: unversioned.StatusFailure}), - }, - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusOK, - Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess}), - }, - Req: func(req *http.Request) bool { - if req.Method != "DELETE" { - t.Errorf("unexpected method: %#v", req) - return false - } - parts := splitPath(req.URL.Path) - if len(parts) < 3 { - t.Errorf("expected URL path to have 3 parts: %s", req.URL.Path) - return false - } - if parts[1] != "bar" { - t.Errorf("url doesn't contain namespace: %#v", req) - return false - } - if parts[2] != "foo" { - t.Errorf("url doesn't contain name: %#v", req) - return false - } - return true - }, - }, - } - for _, test := range tests { - client := &fake.RESTClient{ - Codec: testapi.Default.Codec(), - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: true, - } - err := modifier.Delete("bar", "foo") - if (err != nil) != test.Err { - t.Errorf("unexpected error: %t %v", test.Err, err) - } - if err != nil { - continue - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("unexpected request: %#v", client.Req) - } - } -} - -func TestHelperCreate(t *testing.T) { - expectPost := func(req *http.Request) bool { - if req.Method != "POST" { - t.Errorf("unexpected method: %#v", req) - return false - } - parts := splitPath(req.URL.Path) - if parts[1] != "bar" { - t.Errorf("url doesn't contain namespace: %#v", req) - return false - } - return true - } - - tests := []struct { - Resp *http.Response - HttpErr error - Modify bool - Object runtime.Object - - ExpectObject runtime.Object - Err bool - Req func(*http.Request) bool - }{ - { - HttpErr: errors.New("failure"), - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusNotFound, - Body: objBody(&unversioned.Status{Status: unversioned.StatusFailure}), - }, - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusOK, - Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess}), - }, - Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, - ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, - Req: expectPost, - }, - { - Modify: false, - Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, - ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, - Resp: &http.Response{StatusCode: http.StatusOK, Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess})}, - Req: expectPost, - }, - { - Modify: true, - Object: &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - ExpectObject: &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - Resp: &http.Response{StatusCode: http.StatusOK, Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess})}, - Req: expectPost, - }, - } - for i, test := range tests { - client := &fake.RESTClient{ - Codec: testapi.Default.Codec(), - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - Versioner: testapi.Default.MetadataAccessor(), - NamespaceScoped: true, - } - _, err := modifier.Create("bar", test.Modify, test.Object) - if (err != nil) != test.Err { - t.Errorf("%d: unexpected error: %t %v", i, test.Err, err) - } - if err != nil { - continue - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("%d: unexpected request: %#v", i, client.Req) - } - body, err := ioutil.ReadAll(client.Req.Body) - if err != nil { - t.Fatalf("%d: unexpected error: %#v", i, err) - } - t.Logf("got body: %s", string(body)) - expect := []byte{} - if test.ExpectObject != nil { - expect = []byte(runtime.EncodeOrDie(testapi.Default.Codec(), test.ExpectObject)) - } - if !reflect.DeepEqual(expect, body) { - t.Errorf("%d: unexpected body: %s (expected %s)", i, string(body), string(expect)) - } - - } -} - -func TestHelperGet(t *testing.T) { - tests := []struct { - Err bool - Req func(*http.Request) bool - Resp *http.Response - HttpErr error - }{ - { - HttpErr: errors.New("failure"), - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusNotFound, - Body: objBody(&unversioned.Status{Status: unversioned.StatusFailure}), - }, - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusOK, - Body: objBody(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}), - }, - Req: func(req *http.Request) bool { - if req.Method != "GET" { - t.Errorf("unexpected method: %#v", req) - return false - } - parts := splitPath(req.URL.Path) - if parts[1] != "bar" { - t.Errorf("url doesn't contain namespace: %#v", req) - return false - } - if parts[2] != "foo" { - t.Errorf("url doesn't contain name: %#v", req) - return false - } - return true - }, - }, - } - for _, test := range tests { - client := &fake.RESTClient{ - Codec: testapi.Default.Codec(), - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: true, - } - obj, err := modifier.Get("bar", "foo", false) - if (err != nil) != test.Err { - t.Errorf("unexpected error: %t %v", test.Err, err) - } - if err != nil { - continue - } - if obj.(*api.Pod).Name != "foo" { - t.Errorf("unexpected object: %#v", obj) - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("unexpected request: %#v", client.Req) - } - } -} - -func TestHelperList(t *testing.T) { - tests := []struct { - Err bool - Req func(*http.Request) bool - Resp *http.Response - HttpErr error - }{ - { - HttpErr: errors.New("failure"), - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusNotFound, - Body: objBody(&unversioned.Status{Status: unversioned.StatusFailure}), - }, - Err: true, - }, - { - Resp: &http.Response{ - StatusCode: http.StatusOK, - Body: objBody(&api.PodList{ - Items: []api.Pod{{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - }, - }, - }), - }, - Req: func(req *http.Request) bool { - if req.Method != "GET" { - t.Errorf("unexpected method: %#v", req) - return false - } - if req.URL.Path != "/namespaces/bar" { - t.Errorf("url doesn't contain name: %#v", req.URL) - return false - } - if req.URL.Query().Get(unversioned.LabelSelectorQueryParam(testapi.Default.GroupVersion().String())) != labels.SelectorFromSet(labels.Set{"foo": "baz"}).String() { - t.Errorf("url doesn't contain query parameters: %#v", req.URL) - return false - } - return true - }, - }, - } - for _, test := range tests { - client := &fake.RESTClient{ - Codec: testapi.Default.Codec(), - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - NamespaceScoped: true, - } - obj, err := modifier.List("bar", testapi.Default.GroupVersion().String(), labels.SelectorFromSet(labels.Set{"foo": "baz"}), false) - if (err != nil) != test.Err { - t.Errorf("unexpected error: %t %v", test.Err, err) - } - if err != nil { - continue - } - if obj.(*api.PodList).Items[0].Name != "foo" { - t.Errorf("unexpected object: %#v", obj) - } - if test.Req != nil && !test.Req(client.Req) { - t.Errorf("unexpected request: %#v", client.Req) - } - } -} - -func TestHelperReplace(t *testing.T) { - expectPut := func(path string, req *http.Request) bool { - if req.Method != "PUT" { - t.Errorf("unexpected method: %#v", req) - return false - } - if req.URL.Path != path { - t.Errorf("unexpected url: %v", req.URL) - return false - } - return true - } - - tests := []struct { - Resp *http.Response - HTTPClient *http.Client - HttpErr error - Overwrite bool - Object runtime.Object - Namespace string - NamespaceScoped bool - - ExpectPath string - ExpectObject runtime.Object - Err bool - Req func(string, *http.Request) bool - }{ - { - Namespace: "bar", - NamespaceScoped: true, - HttpErr: errors.New("failure"), - Err: true, - }, - { - Namespace: "bar", - NamespaceScoped: true, - Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, - Resp: &http.Response{ - StatusCode: http.StatusNotFound, - Body: objBody(&unversioned.Status{Status: unversioned.StatusFailure}), - }, - Err: true, - }, - { - Namespace: "bar", - NamespaceScoped: true, - Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, - ExpectPath: "/namespaces/bar/foo", - ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, - Resp: &http.Response{ - StatusCode: http.StatusOK, - Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess}), - }, - Req: expectPut, - }, - // namespace scoped resource - { - Namespace: "bar", - NamespaceScoped: true, - Object: &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - ExpectPath: "/namespaces/bar/foo", - ExpectObject: &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - Overwrite: true, - HTTPClient: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - if req.Method == "PUT" { - return &http.Response{StatusCode: http.StatusOK, Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess})}, nil - } - return &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}})}, nil - }), - Req: expectPut, - }, - // cluster scoped resource - { - Object: &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - }, - ExpectObject: &api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}, - }, - Overwrite: true, - ExpectPath: "/foo", - HTTPClient: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - if req.Method == "PUT" { - return &http.Response{StatusCode: http.StatusOK, Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess})}, nil - } - return &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Node{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}})}, nil - }), - Req: expectPut, - }, - { - Namespace: "bar", - NamespaceScoped: true, - Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, - ExpectPath: "/namespaces/bar/foo", - ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}}, - Resp: &http.Response{StatusCode: http.StatusOK, Body: objBody(&unversioned.Status{Status: unversioned.StatusSuccess})}, - Req: expectPut, - }, - } - for i, test := range tests { - client := &fake.RESTClient{ - Client: test.HTTPClient, - Codec: testapi.Default.Codec(), - Resp: test.Resp, - Err: test.HttpErr, - } - modifier := &Helper{ - RESTClient: client, - Versioner: testapi.Default.MetadataAccessor(), - NamespaceScoped: test.NamespaceScoped, - } - _, err := modifier.Replace(test.Namespace, "foo", test.Overwrite, test.Object) - if (err != nil) != test.Err { - t.Errorf("%d: unexpected error: %t %v", i, test.Err, err) - } - if err != nil { - continue - } - if test.Req != nil && !test.Req(test.ExpectPath, client.Req) { - t.Errorf("%d: unexpected request: %#v", i, client.Req) - } - body, err := ioutil.ReadAll(client.Req.Body) - if err != nil { - t.Fatalf("%d: unexpected error: %#v", i, err) - } - expect := []byte{} - if test.ExpectObject != nil { - expect = []byte(runtime.EncodeOrDie(testapi.Default.Codec(), test.ExpectObject)) - } - if !reflect.DeepEqual(expect, body) { - t.Errorf("%d: unexpected body: %s", i, string(body)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/interfaces.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/interfaces.go index 54d20dfbf..2639a61ec 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/interfaces.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/interfaces.go @@ -19,7 +19,7 @@ package resource import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" - client "k8s.io/kubernetes/pkg/client/unversioned" + client "k8s.io/kubernetes/pkg/client/restclient" ) // RESTClient is a client helper for dealing with RESTful resources diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/mapper.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/mapper.go index 0839ca4a8..25fd97d90 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/mapper.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/mapper.go @@ -21,6 +21,7 @@ import ( "reflect" "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" ) @@ -85,11 +86,17 @@ func (m *Mapper) InfoForData(data []byte, source string) (*Info, error) { // InfoForObject creates an Info object for the given Object. An error is returned // if the object cannot be introspected. Name and namespace will be set into Info // if the mapping's MetadataAccessor can retrieve them. -func (m *Mapper) InfoForObject(obj runtime.Object) (*Info, error) { - groupVersionKind, err := m.ObjectKind(obj) +func (m *Mapper) InfoForObject(obj runtime.Object, preferredGVKs []unversioned.GroupVersionKind) (*Info, error) { + groupVersionKinds, err := m.ObjectKinds(obj) if err != nil { return nil, fmt.Errorf("unable to get type info from the object %q: %v", reflect.TypeOf(obj), err) } + + groupVersionKind := groupVersionKinds[0] + if len(groupVersionKinds) > 1 && len(preferredGVKs) > 0 { + groupVersionKind = preferredObjectKind(groupVersionKinds, preferredGVKs) + } + mapping, err := m.RESTMapping(groupVersionKind.GroupKind(), groupVersionKind.Version) if err != nil { return nil, fmt.Errorf("unable to recognize %v: %v", groupVersionKind, err) @@ -111,3 +118,39 @@ func (m *Mapper) InfoForObject(obj runtime.Object) (*Info, error) { ResourceVersion: resourceVersion, }, nil } + +// preferredObjectKind picks the possibility that most closely matches the priority list in this order: +// GroupVersionKind matches (exact match) +// GroupKind matches +// Group matches +func preferredObjectKind(possibilities []unversioned.GroupVersionKind, preferences []unversioned.GroupVersionKind) unversioned.GroupVersionKind { + // Exact match + for _, priority := range preferences { + for _, possibility := range possibilities { + if possibility == priority { + return possibility + } + } + } + + // GroupKind match + for _, priority := range preferences { + for _, possibility := range possibilities { + if possibility.GroupKind() == priority.GroupKind() { + return possibility + } + } + } + + // Group match + for _, priority := range preferences { + for _, possibility := range possibilities { + if possibility.Group == priority.Group { + return possibility + } + } + } + + // Just pick the first + return possibilities[0] +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/visitor.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/visitor.go index a187919a4..76569389c 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/visitor.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource/visitor.go @@ -20,13 +20,13 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" "path/filepath" "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/runtime" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -219,9 +219,8 @@ func ValidateSchema(data []byte, schema validation.Schema) error { // URLVisitor downloads the contents of a URL, and if successful, returns // an info object representing the downloaded object. type URLVisitor struct { - *Mapper - URL *url.URL - Schema validation.Schema + URL *url.URL + *StreamVisitor } func (v *URLVisitor) Visit(fn VisitorFunc) error { @@ -233,18 +232,9 @@ func (v *URLVisitor) Visit(fn VisitorFunc) error { if res.StatusCode != 200 { return fmt.Errorf("unable to read URL %q, server reported %d %s", v.URL, res.StatusCode, res.Status) } - data, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("unable to read URL %q: %v\n", v.URL, err) - } - if err := ValidateSchema(data, v.Schema); err != nil { - return fmt.Errorf("error validating %q: %v", v.URL, err) - } - info, err := v.Mapper.InfoForData(data, v.URL.String()) - if err != nil { - return err - } - return fn(info, nil) + + v.StreamVisitor.Reader = res.Body + return v.StreamVisitor.Visit(fn) } // DecoratedVisitor will invoke the decorators in order prior to invoking the visitor function @@ -348,8 +338,15 @@ func (v FlattenListVisitor) Visit(fn VisitorFunc) error { }{v.Mapper, v.Mapper.Decoder}); len(errs) > 0 { return utilerrors.NewAggregate(errs) } + + // If we have a GroupVersionKind on the list, prioritize that when asking for info on the objects contained in the list + var preferredGVKs []unversioned.GroupVersionKind + if info.Mapping != nil && !info.Mapping.GroupVersionKind.IsEmpty() { + preferredGVKs = append(preferredGVKs, info.Mapping.GroupVersionKind) + } + for i := range items { - item, err := v.InfoForObject(items[i]) + item, err := v.InfoForObject(items[i], preferredGVKs) if err != nil { return err } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource_printer.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource_printer.go index d33bb92f0..7f9d4ab0e 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource_printer.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource_printer.go @@ -396,14 +396,14 @@ func (h *HumanReadablePrinter) HandledResources() []string { // pkg/kubectl/cmd/get.go to reflect the new resource type. var podColumns = []string{"NAME", "READY", "STATUS", "RESTARTS", "AGE"} var podTemplateColumns = []string{"TEMPLATE", "CONTAINER(S)", "IMAGE(S)", "PODLABELS"} -var replicationControllerColumns = []string{"CONTROLLER", "REPLICAS", "AGE"} -var replicaSetColumns = []string{"CONTROLLER", "REPLICAS", "AGE"} -var jobColumns = []string{"JOB", "SUCCESSFUL"} +var replicationControllerColumns = []string{"NAME", "DESIRED", "CURRENT", "AGE"} +var replicaSetColumns = []string{"NAME", "DESIRED", "CURRENT", "AGE"} +var jobColumns = []string{"NAME", "DESIRED", "SUCCESSFUL", "AGE"} var serviceColumns = []string{"NAME", "CLUSTER-IP", "EXTERNAL-IP", "PORT(S)", "AGE"} -var ingressColumns = []string{"NAME", "RULE", "BACKEND", "ADDRESS"} +var ingressColumns = []string{"NAME", "RULE", "BACKEND", "ADDRESS", "AGE"} var endpointColumns = []string{"NAME", "ENDPOINTS", "AGE"} var nodeColumns = []string{"NAME", "STATUS", "AGE"} -var daemonSetColumns = []string{"NAME", "NODE-SELECTOR"} +var daemonSetColumns = []string{"NAME", "DESIRED", "CURRENT", "NODE-SELECTOR", "AGE"} var eventColumns = []string{"FIRSTSEEN", "LASTSEEN", "COUNT", "NAME", "KIND", "SUBOBJECT", "TYPE", "REASON", "SOURCE", "MESSAGE"} var limitRangeColumns = []string{"NAME", "AGE"} var resourceQuotaColumns = []string{"NAME", "AGE"} @@ -638,22 +638,19 @@ func printPodTemplate(pod *api.PodTemplate, w io.Writer, options PrintOptions) e namespace := pod.Namespace containers := pod.Template.Spec.Containers - var firstContainer api.Container - if len(containers) > 0 { - firstContainer, containers = containers[0], containers[1:] - } if options.WithNamespace { if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil { return err } } - if _, err := fmt.Fprintf(w, "%s\t%s\t%s\t%s", - name, - firstContainer.Name, - firstContainer.Image, - labels.FormatLabels(pod.Template.Labels), - ); err != nil { + if _, err := fmt.Fprintf(w, "%s", name); err != nil { + return err + } + if err := layoutContainers(containers, w); err != nil { + return err + } + if _, err := fmt.Fprintf(w, "\t%s", labels.FormatLabels(pod.Template.Labels)); err != nil { return err } if _, err := fmt.Fprint(w, appendLabels(pod.Labels, options.ColumnLabels)); err != nil { @@ -663,20 +660,6 @@ func printPodTemplate(pod *api.PodTemplate, w io.Writer, options PrintOptions) e return err } - // Lay out all the other containers on separate lines. - extraLinePrefix := "\t" - if options.WithNamespace { - extraLinePrefix = "\t\t" - } - for _, container := range containers { - _, err := fmt.Fprintf(w, "%s%s\t%s\t%s", extraLinePrefix, container.Name, container.Image, "") - if err != nil { - return err - } - if _, err := fmt.Fprint(w, appendLabelTabs(options.ColumnLabels)); err != nil { - return err - } - } return nil } @@ -689,33 +672,34 @@ func printPodTemplateList(podList *api.PodTemplateList, w io.Writer, options Pri return nil } +// TODO(AdoHe): try to put wide output in a single method func printReplicationController(controller *api.ReplicationController, w io.Writer, options PrintOptions) error { name := controller.Name namespace := controller.Namespace containers := controller.Spec.Template.Spec.Containers - var firstContainer api.Container - if len(containers) > 0 { - firstContainer, containers = containers[0], containers[1:] - } if options.WithNamespace { if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil { return err } } - if _, err := fmt.Fprintf(w, "%s\t%d\t%s", + + desiredReplicas := controller.Spec.Replicas + currentReplicas := controller.Status.Replicas + if _, err := fmt.Fprintf(w, "%s\t%d\t%d\t%s", name, - controller.Spec.Replicas, + desiredReplicas, + currentReplicas, translateTimestamp(controller.CreationTimestamp), ); err != nil { return err } + if options.Wide { - if _, err := fmt.Fprintf(w, "\t%s\t%s\t%s", - firstContainer.Name, - firstContainer.Image, - labels.FormatLabels(controller.Spec.Selector), - ); err != nil { + if err := layoutContainers(containers, w); err != nil { + return err + } + if _, err := fmt.Fprintf(w, "\t%s", labels.FormatLabels(controller.Spec.Selector)); err != nil { return err } } @@ -726,20 +710,6 @@ func printReplicationController(controller *api.ReplicationController, w io.Writ return err } - // Lay out all the other containers on separate lines. - extraLinePrefix := "\t" - if options.WithNamespace { - extraLinePrefix = "\t\t" - } - for _, container := range containers { - _, err := fmt.Fprintf(w, "%s%s\t%s\t%s\t%s", extraLinePrefix, container.Name, container.Image, "", "") - if err != nil { - return err - } - if _, err := fmt.Fprint(w, appendLabelTabs(options.ColumnLabels)); err != nil { - return err - } - } return nil } @@ -756,29 +726,28 @@ func printReplicaSet(rs *extensions.ReplicaSet, w io.Writer, options PrintOption name := rs.Name namespace := rs.Namespace containers := rs.Spec.Template.Spec.Containers - var firstContainer api.Container - if len(containers) > 0 { - firstContainer, containers = containers[0], containers[1:] - } if options.WithNamespace { if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil { return err } } - if _, err := fmt.Fprintf(w, "%s\t%d\t%s", + + desiredReplicas := rs.Spec.Replicas + currentReplicas := rs.Status.Replicas + if _, err := fmt.Fprintf(w, "%s\t%d\t%d\t%s", name, - rs.Spec.Replicas, + desiredReplicas, + currentReplicas, translateTimestamp(rs.CreationTimestamp), ); err != nil { return err } if options.Wide { - if _, err := fmt.Fprintf(w, "\t%s\t%s\t%s", - firstContainer.Name, - firstContainer.Image, - unversioned.FormatLabelSelector(rs.Spec.Selector), - ); err != nil { + if err := layoutContainers(containers, w); err != nil { + return err + } + if _, err := fmt.Fprintf(w, "\t%s", unversioned.FormatLabelSelector(rs.Spec.Selector)); err != nil { return err } } @@ -789,20 +758,6 @@ func printReplicaSet(rs *extensions.ReplicaSet, w io.Writer, options PrintOption return err } - // Lay out all the other containers on separate lines. - extraLinePrefix := "\t" - if options.WithNamespace { - extraLinePrefix = "\t\t" - } - for _, container := range containers { - _, err := fmt.Fprintf(w, "%s%s\t%s\t%s\t%s", extraLinePrefix, container.Name, container.Image, "", "") - if err != nil { - return err - } - if _, err := fmt.Fprint(w, appendLabelTabs(options.ColumnLabels)); err != nil { - return err - } - } return nil } @@ -819,31 +774,44 @@ func printJob(job *extensions.Job, w io.Writer, options PrintOptions) error { name := job.Name namespace := job.Namespace containers := job.Spec.Template.Spec.Containers - var firstContainer api.Container - if len(containers) > 0 { - firstContainer, containers = containers[0], containers[1:] - } + if options.WithNamespace { if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil { return err } } - selector, _ := unversioned.LabelSelectorAsSelector(job.Spec.Selector) - _, err := fmt.Fprintf(w, "%s\t%d", - name, - job.Status.Succeeded) + selector, err := unversioned.LabelSelectorAsSelector(job.Spec.Selector) if err != nil { + // this shouldn't happen if LabelSelector passed validation return err } - if options.Wide { - if _, err := fmt.Fprintf(w, "\t%s\t%s\t%s", - firstContainer.Name, - firstContainer.Image, - selector.String(), + if job.Spec.Completions != nil { + if _, err := fmt.Fprintf(w, "%s\t%d\t%d\t%s", + name, + *job.Spec.Completions, + job.Status.Succeeded, + translateTimestamp(job.CreationTimestamp), ); err != nil { return err } + } else { + if _, err := fmt.Fprintf(w, "%s\t%s\t%d\t%s", + name, + "", + job.Status.Succeeded, + translateTimestamp(job.CreationTimestamp), + ); err != nil { + return err + } + } + if options.Wide { + if err := layoutContainers(containers, w); err != nil { + return err + } + if _, err := fmt.Fprintf(w, "\t%s", selector.String()); err != nil { + return err + } } if _, err := fmt.Fprint(w, appendLabels(job.Labels, options.ColumnLabels)); err != nil { return err @@ -852,20 +820,6 @@ func printJob(job *extensions.Job, w io.Writer, options PrintOptions) error { return err } - // Lay out all the other containers on separate lines. - extraLinePrefix := "\t" - if options.WithNamespace { - extraLinePrefix = "\t\t" - } - for _, container := range containers { - _, err := fmt.Fprintf(w, "%s%s\t%s\t%s\t%s", extraLinePrefix, container.Name, container.Image, "", "") - if err != nil { - return err - } - if _, err := fmt.Fprint(w, appendLabelTabs(options.ColumnLabels)); err != nil { - return err - } - } return nil } @@ -983,11 +937,13 @@ func printIngress(ingress *extensions.Ingress, w io.Writer, options PrintOptions } } - if _, err := fmt.Fprintf(w, "%s\t%v\t%v\t%v", + if _, err := fmt.Fprintf(w, "%s\t%v\t%v\t%v\t%s", name, "-", backendStringer(ingress.Spec.Backend), - loadBalancerStatusStringer(ingress.Status.LoadBalancer)); err != nil { + loadBalancerStatusStringer(ingress.Status.LoadBalancer), + translateTimestamp(ingress.CreationTimestamp), + ); err != nil { return err } if _, err := fmt.Fprint(w, appendLabels(ingress.Labels, options.ColumnLabels)); err != nil { @@ -998,7 +954,8 @@ func printIngress(ingress *extensions.Ingress, w io.Writer, options PrintOptions return err } - // Lay out all the rules on separate lines. + // Lay out all the rules on separate lines if use wide output. + // TODO(AdoHe): improve ingress output extraLinePrefix := "" if options.WithNamespace { extraLinePrefix = "\t" @@ -1024,6 +981,7 @@ func printIngress(ingress *extensions.Ingress, w io.Writer, options PrintOptions } } } + return nil } @@ -1041,33 +999,34 @@ func printDaemonSet(ds *extensions.DaemonSet, w io.Writer, options PrintOptions) namespace := ds.Namespace containers := ds.Spec.Template.Spec.Containers - var firstContainer api.Container - if len(containers) > 0 { - firstContainer, containers = containers[0], containers[1:] - } if options.WithNamespace { if _, err := fmt.Fprintf(w, "%s\t", namespace); err != nil { return err } } + + desiredScheduled := ds.Status.DesiredNumberScheduled + currentScheduled := ds.Status.CurrentNumberScheduled selector, err := unversioned.LabelSelectorAsSelector(ds.Spec.Selector) if err != nil { // this shouldn't happen if LabelSelector passed validation return err } - if _, err := fmt.Fprintf(w, "%s\t%s", + if _, err := fmt.Fprintf(w, "%s\t%d\t%d\t%s\t%s", name, + desiredScheduled, + currentScheduled, labels.FormatLabels(ds.Spec.Template.Spec.NodeSelector), + translateTimestamp(ds.CreationTimestamp), ); err != nil { return err } if options.Wide { - if _, err := fmt.Fprintf(w, "\t%s\t%s\t%s", - firstContainer.Name, - firstContainer.Image, - selector, - ); err != nil { + if err := layoutContainers(containers, w); err != nil { + return err + } + if _, err := fmt.Fprintf(w, "\t%s", selector.String()); err != nil { return err } } @@ -1078,20 +1037,6 @@ func printDaemonSet(ds *extensions.DaemonSet, w io.Writer, options PrintOptions) return err } - // Lay out all the other containers on separate lines. - extraLinePrefix := "\t" - if options.WithNamespace { - extraLinePrefix = "\t\t" - } - for _, container := range containers { - _, err := fmt.Fprintf(w, "%s%s\t%s\t%s\t%s", extraLinePrefix, container.Name, container.Image, "", "") - if err != nil { - return err - } - if _, err := fmt.Fprint(w, appendLabelTabs(options.ColumnLabels)); err != nil { - return err - } - } return nil } @@ -1640,8 +1585,8 @@ func printConfigMapList(list *api.ConfigMapList, w io.Writer, options PrintOptio func printPodSecurityPolicy(item *extensions.PodSecurityPolicy, w io.Writer, options PrintOptions) error { _, err := fmt.Fprintf(w, "%s\t%t\t%v\t%t\t%s\t%s\n", item.Name, item.Spec.Privileged, - item.Spec.Capabilities, item.Spec.Volumes, item.Spec.SELinuxContext.Type, - item.Spec.RunAsUser.Type) + item.Spec.Capabilities, item.Spec.Volumes, item.Spec.SELinux.Rule, + item.Spec.RunAsUser.Rule) return err } @@ -1700,6 +1645,26 @@ func appendLabelTabs(columnLabels []string) string { return buffer.String() } +// Lay out all the containers on one line if use wide output. +func layoutContainers(containers []api.Container, w io.Writer) error { + var namesBuffer bytes.Buffer + var imagesBuffer bytes.Buffer + + for i, container := range containers { + namesBuffer.WriteString(container.Name) + imagesBuffer.WriteString(container.Image) + if i != len(containers)-1 { + namesBuffer.WriteString(",") + imagesBuffer.WriteString(",") + } + } + _, err := fmt.Fprintf(w, "\t%s\t%s", namesBuffer.String(), imagesBuffer.String()) + if err != nil { + return err + } + return nil +} + func formatLabelHeaders(columnLabels []string) []string { formHead := make([]string, len(columnLabels)) for i, l := range columnLabels { diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource_printer_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource_printer_test.go deleted file mode 100644 index 52e286db1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/resource_printer_test.go +++ /dev/null @@ -1,1366 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "reflect" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/apis/extensions" - kubectltesting "k8s.io/kubernetes/pkg/kubectl/testing" - "k8s.io/kubernetes/pkg/runtime" - yamlserializer "k8s.io/kubernetes/pkg/runtime/serializer/yaml" - "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/intstr" - "k8s.io/kubernetes/pkg/util/sets" - - "github.com/ghodss/yaml" -) - -func init() { - api.Scheme.AddKnownTypes(testapi.Default.InternalGroupVersion(), &kubectltesting.TestStruct{}) - api.Scheme.AddKnownTypes(*testapi.Default.GroupVersion(), &kubectltesting.TestStruct{}) -} - -var testData = kubectltesting.TestStruct{ - Key: "testValue", - Map: map[string]int{"TestSubkey": 1}, - StringList: []string{"a", "b", "c"}, - IntList: []int{1, 2, 3}, -} - -func TestVersionedPrinter(t *testing.T) { - original := &kubectltesting.TestStruct{Key: "value"} - p := NewVersionedPrinter( - ResourcePrinterFunc(func(obj runtime.Object, w io.Writer) error { - if obj == original { - t.Fatalf("object should not be identical: %#v", obj) - } - if obj.(*kubectltesting.TestStruct).Key != "value" { - t.Fatalf("object was not converted: %#v", obj) - } - return nil - }), - api.Scheme, - *testapi.Default.GroupVersion(), - ) - if err := p.PrintObj(original, nil); err != nil { - t.Errorf("unexpected error: %v", err) - } -} - -func TestPrintDefault(t *testing.T) { - printer, found, err := GetPrinter("", "") - if err != nil { - t.Fatalf("unexpected error: %#v", err) - } - if found { - t.Errorf("no printer should have been found: %#v / %v", printer, err) - } -} - -type TestPrintType struct { - Data string -} - -func (obj *TestPrintType) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -type TestUnknownType struct{} - -func (obj *TestUnknownType) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -func TestPrinter(t *testing.T) { - //test inputs - simpleTest := &TestPrintType{"foo"} - podTest := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}} - podListTest := &api.PodList{ - Items: []api.Pod{ - {ObjectMeta: api.ObjectMeta{Name: "foo"}}, - {ObjectMeta: api.ObjectMeta{Name: "bar"}}, - }, - } - emptyListTest := &api.PodList{} - testapi, err := api.Scheme.ConvertToVersion(podTest, testapi.Default.GroupVersion().String()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - printerTests := []struct { - Name string - Format string - FormatArgument string - Input runtime.Object - Expect string - }{ - {"test json", "json", "", simpleTest, "{\n \"Data\": \"foo\"\n}\n"}, - {"test yaml", "yaml", "", simpleTest, "Data: foo\n"}, - {"test template", "template", "{{if .id}}{{.id}}{{end}}{{if .metadata.name}}{{.metadata.name}}{{end}}", - podTest, "foo"}, - {"test jsonpath", "jsonpath", "{.metadata.name}", podTest, "foo"}, - {"test jsonpath list", "jsonpath", "{.items[*].metadata.name}", podListTest, "foo bar"}, - {"test jsonpath empty list", "jsonpath", "{.items[*].metadata.name}", emptyListTest, ""}, - {"test name", "name", "", podTest, "pod/foo\n"}, - {"emits versioned objects", "template", "{{.kind}}", testapi, "Pod"}, - } - for _, test := range printerTests { - buf := bytes.NewBuffer([]byte{}) - printer, found, err := GetPrinter(test.Format, test.FormatArgument) - if err != nil || !found { - t.Errorf("in %s, unexpected error: %#v", test.Name, err) - } - if err := printer.PrintObj(test.Input, buf); err != nil { - t.Errorf("in %s, unexpected error: %#v", test.Name, err) - } - if buf.String() != test.Expect { - t.Errorf("in %s, expect %q, got %q", test.Name, test.Expect, buf.String()) - } - } - -} - -func TestBadPrinter(t *testing.T) { - badPrinterTests := []struct { - Name string - Format string - FormatArgument string - Error error - }{ - {"empty template", "template", "", fmt.Errorf("template format specified but no template given")}, - {"bad template", "template", "{{ .Name", fmt.Errorf("error parsing template {{ .Name, template: output:1: unclosed action\n")}, - {"bad templatefile", "templatefile", "", fmt.Errorf("templatefile format specified but no template file given")}, - {"bad jsonpath", "jsonpath", "{.Name", fmt.Errorf("error parsing jsonpath {.Name, unclosed action\n")}, - } - for _, test := range badPrinterTests { - _, _, err := GetPrinter(test.Format, test.FormatArgument) - if err == nil || err.Error() != test.Error.Error() { - t.Errorf("in %s, expect %s, got %s", test.Name, test.Error, err) - } - } -} - -func testPrinter(t *testing.T, printer ResourcePrinter, unmarshalFunc func(data []byte, v interface{}) error) { - buf := bytes.NewBuffer([]byte{}) - - err := printer.PrintObj(&testData, buf) - if err != nil { - t.Fatal(err) - } - var poutput kubectltesting.TestStruct - // Verify that given function runs without error. - err = unmarshalFunc(buf.Bytes(), &poutput) - if err != nil { - t.Fatal(err) - } - // Use real decode function to undo the versioning process. - poutput = kubectltesting.TestStruct{} - s := yamlserializer.NewDecodingSerializer(testapi.Default.Codec()) - if err := runtime.DecodeInto(s, buf.Bytes(), &poutput); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(testData, poutput) { - t.Errorf("Test data and unmarshaled data are not equal: %v", util.ObjectDiff(poutput, testData)) - } - - obj := &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "foo"}, - } - buf.Reset() - printer.PrintObj(obj, buf) - var objOut api.Pod - // Verify that given function runs without error. - err = unmarshalFunc(buf.Bytes(), &objOut) - if err != nil { - t.Fatalf("unexpected error: %#v", err) - } - // Use real decode function to undo the versioning process. - objOut = api.Pod{} - if err := runtime.DecodeInto(s, buf.Bytes(), &objOut); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(obj, &objOut) { - t.Errorf("Unexpected inequality:\n%v", util.ObjectDiff(obj, &objOut)) - } -} - -func TestYAMLPrinter(t *testing.T) { - testPrinter(t, &YAMLPrinter{}, yaml.Unmarshal) -} - -func TestJSONPrinter(t *testing.T) { - testPrinter(t, &JSONPrinter{}, json.Unmarshal) -} - -func PrintCustomType(obj *TestPrintType, w io.Writer, options PrintOptions) error { - _, err := fmt.Fprintf(w, "%s", obj.Data) - return err -} - -func ErrorPrintHandler(obj *TestPrintType, w io.Writer, options PrintOptions) error { - return fmt.Errorf("ErrorPrintHandler error") -} - -func TestCustomTypePrinting(t *testing.T) { - columns := []string{"Data"} - printer := NewHumanReadablePrinter(false, false, false, false, false, false, []string{}) - printer.Handler(columns, PrintCustomType) - - obj := TestPrintType{"test object"} - buffer := &bytes.Buffer{} - err := printer.PrintObj(&obj, buffer) - if err != nil { - t.Fatalf("An error occurred printing the custom type: %#v", err) - } - expectedOutput := "Data\ntest object" - if buffer.String() != expectedOutput { - t.Errorf("The data was not printed as expected. Expected:\n%s\nGot:\n%s", expectedOutput, buffer.String()) - } -} - -func TestPrintHandlerError(t *testing.T) { - columns := []string{"Data"} - printer := NewHumanReadablePrinter(false, false, false, false, false, false, []string{}) - printer.Handler(columns, ErrorPrintHandler) - obj := TestPrintType{"test object"} - buffer := &bytes.Buffer{} - err := printer.PrintObj(&obj, buffer) - if err == nil || err.Error() != "ErrorPrintHandler error" { - t.Errorf("Did not get the expected error: %#v", err) - } -} - -func TestUnknownTypePrinting(t *testing.T) { - printer := NewHumanReadablePrinter(false, false, false, false, false, false, []string{}) - buffer := &bytes.Buffer{} - err := printer.PrintObj(&TestUnknownType{}, buffer) - if err == nil { - t.Errorf("An error was expected from printing unknown type") - } -} - -func TestTemplatePanic(t *testing.T) { - tmpl := `{{and ((index .currentState.info "foo").state.running.startedAt) .currentState.info.net.state.running.startedAt}}` - printer, err := NewTemplatePrinter([]byte(tmpl)) - if err != nil { - t.Fatalf("tmpl fail: %v", err) - } - buffer := &bytes.Buffer{} - err = printer.PrintObj(&api.Pod{}, buffer) - if err == nil { - t.Fatalf("expected that template to crash") - } - if buffer.String() == "" { - t.Errorf("no debugging info was printed") - } -} - -func TestNamePrinter(t *testing.T) { - tests := map[string]struct { - obj runtime.Object - expect string - }{ - "singleObject": { - &api.Pod{ - TypeMeta: unversioned.TypeMeta{ - Kind: "Pod", - }, - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - }, - "pod/foo\n"}, - "List": { - &v1.List{ - TypeMeta: unversioned.TypeMeta{ - Kind: "List", - }, - Items: []runtime.RawExtension{ - { - RawJSON: []byte(`{"kind": "Pod", "apiVersion": "v1", "metadata": { "name": "foo"}}`), - }, - { - RawJSON: []byte(`{"kind": "Pod", "apiVersion": "v1", "metadata": { "name": "bar"}}`), - }, - }, - }, - "pod/foo\npod/bar\n"}, - } - printer, _, _ := GetPrinter("name", "") - for name, item := range tests { - buff := &bytes.Buffer{} - err := printer.PrintObj(item.obj, buff) - if err != nil { - t.Errorf("%v: unexpected err: %v", name, err) - continue - } - got := buff.String() - if item.expect != got { - t.Errorf("%v: expected %v, got %v", name, item.expect, got) - } - } -} - -func TestTemplateStrings(t *testing.T) { - // This unit tests the "exists" function as well as the template from update.sh - table := map[string]struct { - pod api.Pod - expect string - }{ - "nilInfo": {api.Pod{}, "false"}, - "emptyInfo": {api.Pod{Status: api.PodStatus{ContainerStatuses: []api.ContainerStatus{}}}, "false"}, - "fooExists": { - api.Pod{ - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ - { - Name: "foo", - }, - }, - }, - }, - "false", - }, - "barExists": { - api.Pod{ - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ - { - Name: "bar", - }, - }, - }, - }, - "false", - }, - "bothExist": { - api.Pod{ - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ - { - Name: "foo", - }, - { - Name: "bar", - }, - }, - }, - }, - "false", - }, - "barValid": { - api.Pod{ - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ - { - Name: "foo", - }, - { - Name: "bar", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{ - StartedAt: unversioned.Time{}, - }, - }, - }, - }, - }, - }, - "false", - }, - "bothValid": { - api.Pod{ - Status: api.PodStatus{ - ContainerStatuses: []api.ContainerStatus{ - { - Name: "foo", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{ - StartedAt: unversioned.Time{}, - }, - }, - }, - { - Name: "bar", - State: api.ContainerState{ - Running: &api.ContainerStateRunning{ - StartedAt: unversioned.Time{}, - }, - }, - }, - }, - }, - }, - "true", - }, - } - // The point of this test is to verify that the below template works. - tmpl := `{{if (exists . "status" "containerStatuses")}}{{range .status.containerStatuses}}{{if (and (eq .name "foo") (exists . "state" "running"))}}true{{end}}{{end}}{{end}}` - p, err := NewTemplatePrinter([]byte(tmpl)) - if err != nil { - t.Fatalf("tmpl fail: %v", err) - } - - printer := NewVersionedPrinter(p, api.Scheme, *testapi.Default.GroupVersion()) - - for name, item := range table { - buffer := &bytes.Buffer{} - err = printer.PrintObj(&item.pod, buffer) - if err != nil { - t.Errorf("%v: unexpected err: %v", name, err) - continue - } - actual := buffer.String() - if len(actual) == 0 { - actual = "false" - } - if e := item.expect; e != actual { - t.Errorf("%v: expected %v, got %v", name, e, actual) - } - } -} - -func TestPrinters(t *testing.T) { - om := func(name string) api.ObjectMeta { return api.ObjectMeta{Name: name} } - templatePrinter, err := NewTemplatePrinter([]byte("{{.name}}")) - if err != nil { - t.Fatal(err) - } - templatePrinter2, err := NewTemplatePrinter([]byte("{{len .items}}")) - if err != nil { - t.Fatal(err) - } - jsonpathPrinter, err := NewJSONPathPrinter("{.metadata.name}") - if err != nil { - t.Fatal(err) - } - printers := map[string]ResourcePrinter{ - "humanReadable": NewHumanReadablePrinter(true, false, false, false, false, false, []string{}), - "humanReadableHeaders": NewHumanReadablePrinter(false, false, false, false, false, false, []string{}), - "json": &JSONPrinter{}, - "yaml": &YAMLPrinter{}, - "template": templatePrinter, - "template2": templatePrinter2, - "jsonpath": jsonpathPrinter, - "name": &NamePrinter{ - Typer: runtime.ObjectTyperToTyper(api.Scheme), - Decoder: api.Codecs.UniversalDecoder(), - }, - } - objects := map[string]runtime.Object{ - "pod": &api.Pod{ObjectMeta: om("pod")}, - "emptyPodList": &api.PodList{}, - "nonEmptyPodList": &api.PodList{Items: []api.Pod{{}}}, - "endpoints": &api.Endpoints{ - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}, {IP: "localhost"}}, - Ports: []api.EndpointPort{{Port: 8080}}, - }}}, - } - // map of printer name to set of objects it should fail on. - expectedErrors := map[string]sets.String{ - "template2": sets.NewString("pod", "emptyPodList", "endpoints"), - "jsonpath": sets.NewString("emptyPodList", "nonEmptyPodList", "endpoints"), - } - - for pName, p := range printers { - for oName, obj := range objects { - b := &bytes.Buffer{} - if err := p.PrintObj(obj, b); err != nil { - if set, found := expectedErrors[pName]; found && set.Has(oName) { - // expected error - continue - } - t.Errorf("printer '%v', object '%v'; error: '%v'", pName, oName, err) - } - } - } -} - -func TestPrintEventsResultSorted(t *testing.T) { - // Arrange - printer := NewHumanReadablePrinter(false /* noHeaders */, false, false, false, false, false, []string{}) - - obj := api.EventList{ - Items: []api.Event{ - { - Source: api.EventSource{Component: "kubelet"}, - Message: "Item 1", - FirstTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - { - Source: api.EventSource{Component: "scheduler"}, - Message: "Item 2", - FirstTimestamp: unversioned.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - { - Source: api.EventSource{Component: "kubelet"}, - Message: "Item 3", - FirstTimestamp: unversioned.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - }, - } - buffer := &bytes.Buffer{} - - // Act - err := printer.PrintObj(&obj, buffer) - - // Assert - if err != nil { - t.Fatalf("An error occurred printing the EventList: %#v", err) - } - out := buffer.String() - VerifyDatesInOrder(out, "\n" /* rowDelimiter */, " " /* columnDelimiter */, t) -} - -func TestPrintNodeStatus(t *testing.T) { - printer := NewHumanReadablePrinter(false, false, false, false, false, false, []string{}) - table := []struct { - node api.Node - status string - }{ - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo1"}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionTrue}}}, - }, - status: "Ready", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo2"}, - Spec: api.NodeSpec{Unschedulable: true}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionTrue}}}, - }, - status: "Ready,SchedulingDisabled", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo3"}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{ - {Type: api.NodeReady, Status: api.ConditionTrue}, - {Type: api.NodeReady, Status: api.ConditionTrue}}}, - }, - status: "Ready", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo4"}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionFalse}}}, - }, - status: "NotReady", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo5"}, - Spec: api.NodeSpec{Unschedulable: true}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: api.NodeReady, Status: api.ConditionFalse}}}, - }, - status: "NotReady,SchedulingDisabled", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo6"}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: "InvalidValue", Status: api.ConditionTrue}}}, - }, - status: "Unknown", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo7"}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{}}}, - }, - status: "Unknown", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo8"}, - Spec: api.NodeSpec{Unschedulable: true}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{Type: "InvalidValue", Status: api.ConditionTrue}}}, - }, - status: "Unknown,SchedulingDisabled", - }, - { - node: api.Node{ - ObjectMeta: api.ObjectMeta{Name: "foo9"}, - Spec: api.NodeSpec{Unschedulable: true}, - Status: api.NodeStatus{Conditions: []api.NodeCondition{{}}}, - }, - status: "Unknown,SchedulingDisabled", - }, - } - - for _, test := range table { - buffer := &bytes.Buffer{} - err := printer.PrintObj(&test.node, buffer) - if err != nil { - t.Fatalf("An error occurred printing Node: %#v", err) - } - if !contains(strings.Fields(buffer.String()), test.status) { - t.Fatalf("Expect printing node %s with status %#v, got: %#v", test.node.Name, test.status, buffer.String()) - } - } -} - -func contains(fields []string, field string) bool { - for _, v := range fields { - if v == field { - return true - } - } - return false -} - -func TestPrintHunmanReadableIngressWithColumnLabels(t *testing.T) { - ingress := extensions.Ingress{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - CreationTimestamp: unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}, - Labels: map[string]string{ - "app_name": "kubectl_test_ingress", - }, - }, - Spec: extensions.IngressSpec{ - Backend: &extensions.IngressBackend{ - ServiceName: "svc", - ServicePort: intstr.FromInt(93), - }, - }, - Status: extensions.IngressStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - { - IP: "2.3.4.5", - Hostname: "localhost.localdomain", - }, - }, - }, - }, - } - buff := bytes.Buffer{} - printIngress(&ingress, &buff, PrintOptions{false, false, false, false, false, false, []string{"app_name"}}) - output := string(buff.Bytes()) - appName := ingress.ObjectMeta.Labels["app_name"] - if !strings.Contains(output, appName) { - t.Errorf("expected to container app_name label value %s, but doesn't %s", appName, output) - } -} - -func TestPrintHumanReadableService(t *testing.T) { - tests := []api.Service{ - { - Spec: api.ServiceSpec{ - ClusterIP: "1.2.3.4", - Type: "LoadBalancer", - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - }, - }, - }, - Status: api.ServiceStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - { - IP: "2.3.4.5", - }, - { - IP: "3.4.5.6", - }, - }, - }, - }, - }, - { - Spec: api.ServiceSpec{ - ClusterIP: "1.2.3.4", - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - }, - { - Port: 8090, - Protocol: "UDP", - }, - { - Port: 8000, - Protocol: "TCP", - }, - }, - }, - }, - { - Spec: api.ServiceSpec{ - ClusterIP: "1.2.3.4", - Type: "LoadBalancer", - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - }, - { - Port: 8090, - Protocol: "UDP", - }, - { - Port: 8000, - Protocol: "TCP", - }, - }, - }, - Status: api.ServiceStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - { - IP: "2.3.4.5", - }, - }, - }, - }, - }, - { - Spec: api.ServiceSpec{ - ClusterIP: "1.2.3.4", - Type: "LoadBalancer", - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - }, - { - Port: 8090, - Protocol: "UDP", - }, - { - Port: 8000, - Protocol: "TCP", - }, - }, - }, - Status: api.ServiceStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - { - IP: "2.3.4.5", - }, - { - IP: "3.4.5.6", - }, - { - IP: "5.6.7.8", - Hostname: "host5678", - }, - }, - }, - }, - }, - } - - for _, svc := range tests { - buff := bytes.Buffer{} - printService(&svc, &buff, PrintOptions{false, false, false, false, false, false, []string{}}) - output := string(buff.Bytes()) - ip := svc.Spec.ClusterIP - if !strings.Contains(output, ip) { - t.Errorf("expected to contain ClusterIP %s, but doesn't: %s", ip, output) - } - - for _, ingress := range svc.Status.LoadBalancer.Ingress { - ip = ingress.IP - if !strings.Contains(output, ip) { - t.Errorf("expected to contain ingress ip %s, but doesn't: %s", ip, output) - } - } - - for _, port := range svc.Spec.Ports { - portSpec := fmt.Sprintf("%d/%s", port.Port, port.Protocol) - if !strings.Contains(output, portSpec) { - t.Errorf("expected to contain port: %s, but doesn't: %s", portSpec, output) - } - } - // Each service should print on one line - if 1 != strings.Count(output, "\n") { - t.Errorf("expected a single newline, found %d", strings.Count(output, "\n")) - } - } -} - -func TestPrintHumanReadableWithNamespace(t *testing.T) { - namespaceName := "testnamespace" - name := "test" - table := []struct { - obj runtime.Object - isNamespaced bool - }{ - { - obj: &api.Pod{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - }, - isNamespaced: true, - }, - { - obj: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - Spec: api.ReplicationControllerSpec{ - Replicas: 2, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "name": "foo", - "type": "production", - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Image: "foo/bar", - TerminationMessagePath: api.TerminationMessagePathDefault, - ImagePullPolicy: api.PullIfNotPresent, - }, - }, - RestartPolicy: api.RestartPolicyAlways, - DNSPolicy: api.DNSDefault, - NodeSelector: map[string]string{ - "baz": "blah", - }, - }, - }, - }, - }, - isNamespaced: true, - }, - { - obj: &api.Service{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - Spec: api.ServiceSpec{ - ClusterIP: "1.2.3.4", - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - }, - }, - }, - Status: api.ServiceStatus{ - LoadBalancer: api.LoadBalancerStatus{ - Ingress: []api.LoadBalancerIngress{ - { - IP: "2.3.4.5", - }, - }, - }, - }, - }, - isNamespaced: true, - }, - { - obj: &api.Endpoints{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}, {IP: "localhost"}}, - Ports: []api.EndpointPort{{Port: 8080}}, - }, - }}, - isNamespaced: true, - }, - { - obj: &api.Namespace{ - ObjectMeta: api.ObjectMeta{Name: name}, - }, - isNamespaced: false, - }, - { - obj: &api.Secret{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - }, - isNamespaced: true, - }, - { - obj: &api.ServiceAccount{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - Secrets: []api.ObjectReference{}, - }, - isNamespaced: true, - }, - { - obj: &api.Node{ - ObjectMeta: api.ObjectMeta{Name: name}, - Status: api.NodeStatus{}, - }, - isNamespaced: false, - }, - { - obj: &api.PersistentVolume{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - Spec: api.PersistentVolumeSpec{}, - }, - isNamespaced: false, - }, - { - obj: &api.PersistentVolumeClaim{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - Spec: api.PersistentVolumeClaimSpec{}, - }, - isNamespaced: true, - }, - { - obj: &api.Event{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - Source: api.EventSource{Component: "kubelet"}, - Message: "Item 1", - FirstTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - isNamespaced: true, - }, - { - obj: &api.LimitRange{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - }, - isNamespaced: true, - }, - { - obj: &api.ResourceQuota{ - ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespaceName}, - }, - isNamespaced: true, - }, - { - obj: &api.ComponentStatus{ - Conditions: []api.ComponentCondition{ - {Type: api.ComponentHealthy, Status: api.ConditionTrue, Message: "ok", Error: ""}, - }, - }, - isNamespaced: false, - }, - } - - for _, test := range table { - if test.isNamespaced { - // Expect output to include namespace when requested. - printer := NewHumanReadablePrinter(false, true, false, false, false, false, []string{}) - buffer := &bytes.Buffer{} - err := printer.PrintObj(test.obj, buffer) - if err != nil { - t.Fatalf("An error occurred printing object: %#v", err) - } - matched := contains(strings.Fields(buffer.String()), fmt.Sprintf("%s", namespaceName)) - if !matched { - t.Errorf("Expect printing object to contain namespace: %#v", test.obj) - } - } else { - // Expect error when trying to get all namespaces for un-namespaced object. - printer := NewHumanReadablePrinter(false, true, false, false, false, false, []string{}) - buffer := &bytes.Buffer{} - err := printer.PrintObj(test.obj, buffer) - if err == nil { - t.Errorf("Expected error when printing un-namespaced type") - } - } - } -} - -func TestPrintPod(t *testing.T) { - tests := []struct { - pod api.Pod - expect string - }{ - { - // Test name, num of containers, restarts, container ready status - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test1"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - "test1\t1/2\tpodPhase\t6\t", - }, - { - // Test container error overwrites pod phase - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test2"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {State: api.ContainerState{Waiting: &api.ContainerStateWaiting{Reason: "ContainerWaitingReason"}}, RestartCount: 3}, - }, - }, - }, - "test2\t1/2\tContainerWaitingReason\t6\t", - }, - { - // Test the same as the above but with Terminated state and the first container overwrites the rest - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test3"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {State: api.ContainerState{Waiting: &api.ContainerStateWaiting{Reason: "ContainerWaitingReason"}}, RestartCount: 3}, - {State: api.ContainerState{Terminated: &api.ContainerStateTerminated{Reason: "ContainerTerminatedReason"}}, RestartCount: 3}, - }, - }, - }, - "test3\t0/2\tContainerWaitingReason\t6\t", - }, - { - // Test ready is not enough for reporting running - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test4"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {Ready: true, RestartCount: 3}, - }, - }, - }, - "test4\t1/2\tpodPhase\t6\t", - }, - { - // Test ready is not enough for reporting running - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test5"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Reason: "OutOfDisk", - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {Ready: true, RestartCount: 3}, - }, - }, - }, - "test5\t1/2\tOutOfDisk\t6\t", - }, - } - - buf := bytes.NewBuffer([]byte{}) - for _, test := range tests { - printPod(&test.pod, buf, PrintOptions{false, false, false, true, false, false, []string{}}) - // We ignore time - if !strings.HasPrefix(buf.String(), test.expect) { - t.Fatalf("Expected: %s, got: %s", test.expect, buf.String()) - } - buf.Reset() - } -} - -func TestPrintNonTerminatedPod(t *testing.T) { - tests := []struct { - pod api.Pod - expect string - }{ - { - // Test pod phase Running should be printed - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test1"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: api.PodRunning, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - "test1\t1/2\tRunning\t6\t", - }, - { - // Test pod phase Pending should be printed - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test2"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: api.PodPending, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - "test2\t1/2\tPending\t6\t", - }, - { - // Test pod phase Unknown should be printed - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test3"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: api.PodUnknown, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - "test3\t1/2\tUnknown\t6\t", - }, - { - // Test pod phase Succeeded shouldn't be printed - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test4"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: api.PodSucceeded, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - "", - }, - { - // Test pod phase Failed shouldn't be printed - api.Pod{ - ObjectMeta: api.ObjectMeta{Name: "test5"}, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: api.PodFailed, - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {Ready: true, RestartCount: 3}, - }, - }, - }, - "", - }, - } - - buf := bytes.NewBuffer([]byte{}) - for _, test := range tests { - printPod(&test.pod, buf, PrintOptions{false, false, false, false, false, false, []string{}}) - // We ignore time - if !strings.HasPrefix(buf.String(), test.expect) { - t.Fatalf("Expected: %s, got: %s", test.expect, buf.String()) - } - buf.Reset() - } -} - -func TestPrintPodWithLabels(t *testing.T) { - tests := []struct { - pod api.Pod - labelColumns []string - startsWith string - endsWith string - }{ - { - // Test name, num of containers, restarts, container ready status - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - Labels: map[string]string{"col1": "asd", "COL2": "zxc"}, - }, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - []string{"col1", "COL2"}, - "test1\t1/2\tpodPhase\t6\t", - "\tasd\tzxc\n", - }, - { - // Test name, num of containers, restarts, container ready status - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - Labels: map[string]string{"col1": "asd", "COL2": "zxc"}, - }, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - []string{}, - "test1\t1/2\tpodPhase\t6\t", - "\n", - }, - } - - buf := bytes.NewBuffer([]byte{}) - for _, test := range tests { - printPod(&test.pod, buf, PrintOptions{false, false, false, false, false, false, test.labelColumns}) - // We ignore time - if !strings.HasPrefix(buf.String(), test.startsWith) || !strings.HasSuffix(buf.String(), test.endsWith) { - t.Fatalf("Expected to start with: %s and end with: %s, but got: %s", test.startsWith, test.endsWith, buf.String()) - } - buf.Reset() - } -} - -type stringTestList []struct { - name, got, exp string -} - -func TestTranslateTimestamp(t *testing.T) { - tl := stringTestList{ - {"a while from now", translateTimestamp(unversioned.Time{Time: time.Now().Add(2.1e9)}), ""}, - {"almost now", translateTimestamp(unversioned.Time{Time: time.Now().Add(1.9e9)}), "0s"}, - {"now", translateTimestamp(unversioned.Time{Time: time.Now()}), "0s"}, - {"unknown", translateTimestamp(unversioned.Time{}), ""}, - {"30 seconds ago", translateTimestamp(unversioned.Time{Time: time.Now().Add(-3e10)}), "30s"}, - {"5 minutes ago", translateTimestamp(unversioned.Time{Time: time.Now().Add(-3e11)}), "5m"}, - {"an hour ago", translateTimestamp(unversioned.Time{Time: time.Now().Add(-6e12)}), "1h"}, - {"2 days ago", translateTimestamp(unversioned.Time{Time: time.Now().AddDate(0, 0, -2)}), "2d"}, - {"months ago", translateTimestamp(unversioned.Time{Time: time.Now().AddDate(0, 0, -90)}), "90d"}, - {"10 years ago", translateTimestamp(unversioned.Time{Time: time.Now().AddDate(-10, 0, 0)}), "10y"}, - } - for _, test := range tl { - if test.got != test.exp { - t.Errorf("On %v, expected '%v', but got '%v'", - test.name, test.exp, test.got) - } - } -} - -func TestPrintDeployment(t *testing.T) { - tests := []struct { - deployment extensions.Deployment - expect string - }{ - { - extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - CreationTimestamp: unversioned.Time{Time: time.Now().Add(1.9e9)}, - }, - Spec: extensions.DeploymentSpec{ - Replicas: 5, - Template: api.PodTemplateSpec{ - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - }, - }, - Status: extensions.DeploymentStatus{ - Replicas: 10, - UpdatedReplicas: 2, - AvailableReplicas: 1, - UnavailableReplicas: 4, - }, - }, - "test1\t5\t10\t2\t1\t0s\n", - }, - } - - buf := bytes.NewBuffer([]byte{}) - for _, test := range tests { - printDeployment(&test.deployment, buf, PrintOptions{false, false, false, true, false, false, []string{}}) - if buf.String() != test.expect { - t.Fatalf("Expected: %s, got: %s", test.expect, buf.String()) - } - buf.Reset() - } -} - -func TestPrintPodShowLabels(t *testing.T) { - tests := []struct { - pod api.Pod - startsWith string - endsWith string - showLabels bool - }{ - { - // Test name, num of containers, restarts, container ready status - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - Labels: map[string]string{"col1": "asd", "COL2": "zxc"}, - }, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - "test1\t1/2\tpodPhase\t6\t", - "\tCOL2=zxc,col1=asd\n", - true, - }, - { - // Test name, num of containers, restarts, container ready status - api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "test1", - Labels: map[string]string{"col3": "asd", "COL4": "zxc"}, - }, - Spec: api.PodSpec{Containers: make([]api.Container, 2)}, - Status: api.PodStatus{ - Phase: "podPhase", - ContainerStatuses: []api.ContainerStatus{ - {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, - {RestartCount: 3}, - }, - }, - }, - "test1\t1/2\tpodPhase\t6\t", - "\n", - false, - }, - } - - buf := bytes.NewBuffer([]byte{}) - for _, test := range tests { - printPod(&test.pod, buf, PrintOptions{false, false, false, false, test.showLabels, false, []string{}}) - // We ignore time - if !strings.HasPrefix(buf.String(), test.startsWith) || !strings.HasSuffix(buf.String(), test.endsWith) { - t.Fatalf("Expected to start with: %s and end with: %s, but got: %s", test.startsWith, test.endsWith, buf.String()) - } - buf.Reset() - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/rolling_updater.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/rolling_updater.go index d734b153d..e69d889a7 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/rolling_updater.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/rolling_updater.go @@ -20,7 +20,6 @@ import ( goerrors "errors" "fmt" "io" - "math" "strconv" "strings" "time" @@ -30,6 +29,7 @@ import ( client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/util/deployment" "k8s.io/kubernetes/pkg/util/integer" "k8s.io/kubernetes/pkg/util/intstr" "k8s.io/kubernetes/pkg/util/wait" @@ -113,10 +113,8 @@ type RollingUpdater struct { getOrCreateTargetController func(controller *api.ReplicationController, sourceId string) (*api.ReplicationController, bool, error) // cleanup performs post deployment cleanup tasks for newRc and oldRc. cleanup func(oldRc, newRc *api.ReplicationController, config *RollingUpdaterConfig) error - // waitForReadyPods should block until there are >0 total pods ready amongst - // the old and new controllers, and should return the amount of old and new - // ready. - waitForReadyPods func(interval, timeout time.Duration, oldRc, newRc *api.ReplicationController) (int, int, error) + // getReadyPods returns the amount of old and new ready pods. + getReadyPods func(oldRc, newRc *api.ReplicationController) (int, int, error) } // NewRollingUpdater creates a RollingUpdater from a client. @@ -128,7 +126,7 @@ func NewRollingUpdater(namespace string, client client.Interface) *RollingUpdate // Inject real implementations. updater.scaleAndWait = updater.scaleAndWaitWithScaler updater.getOrCreateTargetController = updater.getOrCreateTargetControllerWithClient - updater.waitForReadyPods = updater.pollForReadyPods + updater.getReadyPods = updater.readyPods updater.cleanup = updater.cleanupWithClients return updater } @@ -194,18 +192,9 @@ func (r *RollingUpdater) Update(config *RollingUpdaterConfig) error { } oldRc = updated } - original, err := strconv.Atoi(oldRc.Annotations[originalReplicasAnnotation]) - if err != nil { - return fmt.Errorf("Unable to parse annotation for %s: %s=%s\n", - oldRc.Name, originalReplicasAnnotation, oldRc.Annotations[originalReplicasAnnotation]) - } - // The maximum pods which can go unavailable during the update. - maxUnavailable, err := extractMaxValue(config.MaxUnavailable, "maxUnavailable", desired) - if err != nil { - return err - } - // The maximum scaling increment. - maxSurge, err := extractMaxValue(config.MaxSurge, "maxSurge", desired) + // maxSurge is the maximum scaling increment and maxUnavailable are the maximum pods + // that can be unavailable during a rollout. + maxSurge, maxUnavailable, err := deployment.ResolveFenceposts(&config.MaxSurge, &config.MaxUnavailable, desired) if err != nil { return err } @@ -220,12 +209,12 @@ func (r *RollingUpdater) Update(config *RollingUpdaterConfig) error { // the effective scale of the old RC regardless of the configuration // (equivalent to 100% maxUnavailable). if desired == 0 { - maxUnavailable = original + maxUnavailable = oldRc.Spec.Replicas minAvailable = 0 } fmt.Fprintf(out, "Scaling up %s from %d to %d, scaling down %s from %d to 0 (keep %d pods available, don't exceed %d pods)\n", - newRc.Name, newRc.Spec.Replicas, desired, oldRc.Name, oldRc.Spec.Replicas, minAvailable, original+maxSurge) + newRc.Name, newRc.Spec.Replicas, desired, oldRc.Name, oldRc.Spec.Replicas, minAvailable, desired+maxSurge) // Scale newRc and oldRc until newRc has the desired number of replicas and // oldRc has 0 replicas. @@ -236,7 +225,7 @@ func (r *RollingUpdater) Update(config *RollingUpdaterConfig) error { oldReplicas := oldRc.Spec.Replicas // Scale up as much as possible. - scaledRc, err := r.scaleUp(newRc, oldRc, original, desired, maxSurge, maxUnavailable, scaleRetryParams, config) + scaledRc, err := r.scaleUp(newRc, oldRc, desired, maxSurge, maxUnavailable, scaleRetryParams, config) if err != nil { return err } @@ -269,14 +258,14 @@ func (r *RollingUpdater) Update(config *RollingUpdaterConfig) error { // scaleUp scales up newRc to desired by whatever increment is possible given // the configured surge threshold. scaleUp will safely no-op as necessary when // it detects redundancy or other relevant conditions. -func (r *RollingUpdater) scaleUp(newRc, oldRc *api.ReplicationController, original, desired, maxSurge, maxUnavailable int, scaleRetryParams *RetryParams, config *RollingUpdaterConfig) (*api.ReplicationController, error) { +func (r *RollingUpdater) scaleUp(newRc, oldRc *api.ReplicationController, desired, maxSurge, maxUnavailable int, scaleRetryParams *RetryParams, config *RollingUpdaterConfig) (*api.ReplicationController, error) { // If we're already at the desired, do nothing. if newRc.Spec.Replicas == desired { return newRc, nil } // Scale up as far as we can based on the surge limit. - increment := (original + maxSurge) - (oldRc.Spec.Replicas + newRc.Spec.Replicas) + increment := (desired + maxSurge) - (oldRc.Spec.Replicas + newRc.Spec.Replicas) // If the old is already scaled down, go ahead and scale all the way up. if oldRc.Spec.Replicas == 0 { increment = desired - newRc.Spec.Replicas @@ -299,7 +288,7 @@ func (r *RollingUpdater) scaleUp(newRc, oldRc *api.ReplicationController, origin return scaledRc, nil } -// scaleDown scales down oldRc to 0 at whatever increment possible given the +// scaleDown scales down oldRc to 0 at whatever decrement possible given the // thresholds defined on the config. scaleDown will safely no-op as necessary // when it detects redundancy or other relevant conditions. func (r *RollingUpdater) scaleDown(newRc, oldRc *api.ReplicationController, desired, minAvailable, maxUnavailable, maxSurge int, config *RollingUpdaterConfig) (*api.ReplicationController, error) { @@ -307,15 +296,19 @@ func (r *RollingUpdater) scaleDown(newRc, oldRc *api.ReplicationController, desi if oldRc.Spec.Replicas == 0 { return oldRc, nil } - // Block until there are any pods ready. - _, newAvailable, err := r.waitForReadyPods(config.Interval, config.Timeout, oldRc, newRc) + // Get ready pods. We shouldn't block, otherwise in case both old and new + // pods are unavailable then the rolling update process blocks. + // Timeout-wise we are already covered by the progress check. + _, newAvailable, err := r.getReadyPods(oldRc, newRc) if err != nil { return nil, err } // The old controller is considered as part of the total because we want to // maintain minimum availability even with a volatile old controller. // Scale down as much as possible while maintaining minimum availability - decrement := oldRc.Spec.Replicas + newAvailable - minAvailable + allPods := oldRc.Spec.Replicas + newRc.Spec.Replicas + newUnavailable := newRc.Spec.Replicas - newAvailable + decrement := allPods - minAvailable - newUnavailable // The decrement normally shouldn't drop below 0 because the available count // always starts below the old replica count, but the old replica count can // decrement due to externalities like pods death in the replica set. This @@ -360,40 +353,34 @@ func (r *RollingUpdater) scaleAndWaitWithScaler(rc *api.ReplicationController, r return r.c.ReplicationControllers(rc.Namespace).Get(rc.Name) } -// pollForReadyPods polls oldRc and newRc each interval and returns the old -// and new ready counts for their pods. If a pod is observed as being ready, -// it's considered ready even if it later becomes notReady. -func (r *RollingUpdater) pollForReadyPods(interval, timeout time.Duration, oldRc, newRc *api.ReplicationController) (int, int, error) { +// readyPods returns the old and new ready counts for their pods. +// If a pod is observed as being ready, it's considered ready even +// if it later becomes notReady. +func (r *RollingUpdater) readyPods(oldRc, newRc *api.ReplicationController) (int, int, error) { controllers := []*api.ReplicationController{oldRc, newRc} oldReady := 0 newReady := 0 - err := wait.Poll(interval, timeout, func() (done bool, err error) { - anyReady := false - for _, controller := range controllers { - selector := labels.Set(controller.Spec.Selector).AsSelector() - options := api.ListOptions{LabelSelector: selector} - pods, err := r.c.Pods(controller.Namespace).List(options) - if err != nil { - return false, err - } - for _, pod := range pods.Items { - if api.IsPodReady(&pod) { - switch controller.Name { - case oldRc.Name: - oldReady++ - case newRc.Name: - newReady++ - } - anyReady = true + + for i := range controllers { + controller := controllers[i] + selector := labels.Set(controller.Spec.Selector).AsSelector() + options := api.ListOptions{LabelSelector: selector} + pods, err := r.c.Pods(controller.Namespace).List(options) + if err != nil { + return 0, 0, err + } + for _, pod := range pods.Items { + if api.IsPodReady(&pod) { + switch controller.Name { + case oldRc.Name: + oldReady++ + case newRc.Name: + newReady++ } } } - if anyReady { - return true, nil - } - return false, nil - }) - return oldReady, newReady, err + } + return oldReady, newReady, nil } // getOrCreateTargetControllerWithClient looks for an existing controller with @@ -490,29 +477,6 @@ func (r *RollingUpdater) cleanupWithClients(oldRc, newRc *api.ReplicationControl } } -// func extractMaxValue is a helper to extract config max values as either -// absolute numbers or based on percentages of the given value. -func extractMaxValue(field intstr.IntOrString, name string, value int) (int, error) { - switch field.Type { - case intstr.Int: - if field.IntVal < 0 { - return 0, fmt.Errorf("%s must be >= 0", name) - } - return field.IntValue(), nil - case intstr.String: - s := strings.Replace(field.StrVal, "%", "", -1) - v, err := strconv.Atoi(s) - if err != nil { - return 0, fmt.Errorf("invalid %s value %q: %v", name, field.StrVal, err) - } - if v < 0 { - return 0, fmt.Errorf("%s must be >= 0", name) - } - return int(math.Ceil(float64(value) * (float64(v)) / 100)), nil - } - return 0, fmt.Errorf("invalid kind %q for %s", field.Type, name) -} - func Rename(c client.ReplicationControllersNamespacer, rc *api.ReplicationController, newName string) error { oldName := rc.Name rc.Name = newName diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/rolling_updater_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/rolling_updater_test.go deleted file mode 100644 index 4ba556847..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/rolling_updater_test.go +++ /dev/null @@ -1,1622 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - apitesting "k8s.io/kubernetes/pkg/api/testing" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/fake" - "k8s.io/kubernetes/pkg/client/unversioned/testclient" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/intstr" - "k8s.io/kubernetes/pkg/util/sets" -) - -func oldRc(replicas int, original int) *api.ReplicationController { - return &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo-v1", - UID: "7764ae47-9092-11e4-8393-42010af018ff", - Annotations: map[string]string{ - originalReplicasAnnotation: fmt.Sprintf("%d", original), - }, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: replicas, - Selector: map[string]string{"version": "v1"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Name: "foo-v1", - Labels: map[string]string{"version": "v1"}, - }, - }, - }, - Status: api.ReplicationControllerStatus{ - Replicas: replicas, - }, - } -} - -func newRc(replicas int, desired int) *api.ReplicationController { - rc := oldRc(replicas, replicas) - rc.Spec.Template = &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Name: "foo-v2", - Labels: map[string]string{"version": "v2"}, - }, - } - rc.Spec.Selector = map[string]string{"version": "v2"} - rc.ObjectMeta = api.ObjectMeta{ - Name: "foo-v2", - Annotations: map[string]string{ - desiredReplicasAnnotation: fmt.Sprintf("%d", desired), - sourceIdAnnotation: "foo-v1:7764ae47-9092-11e4-8393-42010af018ff", - }, - } - return rc -} - -// TestUpdate performs complex scenario testing for rolling updates. It -// provides fine grained control over the states for each update interval to -// allow the expression of as many edge cases as possible. -func TestUpdate(t *testing.T) { - // up represents a simulated scale up event and expectation - type up struct { - // to is the expected replica count for a scale-up - to int - } - // down represents a simulated scale down event and expectation - type down struct { - // oldReady is the number of oldRc replicas which will be seen - // as ready during the scale down attempt - oldReady int - // newReady is the number of newRc replicas which will be seen - // as ready during the scale up attempt - newReady int - // to is the expected replica count for the scale down - to int - // noop and to are mutually exclusive; if noop is true, that means for - // this down event, no scaling attempt should be made (for example, if - // by scaling down, the readiness minimum would be crossed.) - noop bool - } - - tests := []struct { - name string - // oldRc is the "from" deployment - oldRc *api.ReplicationController - // newRc is the "to" deployment - newRc *api.ReplicationController - // whether newRc existed (false means it was created) - newRcExists bool - maxUnavail intstr.IntOrString - maxSurge intstr.IntOrString - // expected is the sequence of up/down events that will be simulated and - // verified - expected []interface{} - // output is the expected textual output written - output string - }{ - { - name: "10->10 30/0 fast readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("30%"), - maxSurge: intstr.FromString("0%"), - expected: []interface{}{ - down{oldReady: 10, newReady: 0, to: 7}, - up{3}, - down{oldReady: 7, newReady: 3, to: 4}, - up{6}, - down{oldReady: 4, newReady: 6, to: 1}, - up{9}, - down{oldReady: 1, newReady: 9, to: 0}, - up{10}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 7 pods available, don't exceed 10 pods) -Scaling foo-v1 down to 7 -Scaling foo-v2 up to 3 -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 6 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 9 -Scaling foo-v1 down to 0 -Scaling foo-v2 up to 10 -`, - }, - { - name: "10->10 30/0 delayed readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("30%"), - maxSurge: intstr.FromString("0%"), - expected: []interface{}{ - down{oldReady: 10, newReady: 0, to: 7}, - up{3}, - down{oldReady: 7, newReady: 0, noop: true}, - down{oldReady: 7, newReady: 1, to: 6}, - up{4}, - down{oldReady: 6, newReady: 4, to: 3}, - up{7}, - down{oldReady: 3, newReady: 7, to: 0}, - up{10}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 7 pods available, don't exceed 10 pods) -Scaling foo-v1 down to 7 -Scaling foo-v2 up to 3 -Scaling foo-v1 down to 6 -Scaling foo-v2 up to 4 -Scaling foo-v1 down to 3 -Scaling foo-v2 up to 7 -Scaling foo-v1 down to 0 -Scaling foo-v2 up to 10 -`, - }, { - name: "10->10 30/0 fast readiness, continuation", - oldRc: oldRc(7, 10), - newRc: newRc(3, 10), - newRcExists: false, - maxUnavail: intstr.FromString("30%"), - maxSurge: intstr.FromString("0%"), - expected: []interface{}{ - down{oldReady: 7, newReady: 3, to: 4}, - up{6}, - down{oldReady: 4, newReady: 6, to: 1}, - up{9}, - down{oldReady: 1, newReady: 9, to: 0}, - up{10}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 3 to 10, scaling down foo-v1 from 7 to 0 (keep 7 pods available, don't exceed 10 pods) -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 6 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 9 -Scaling foo-v1 down to 0 -Scaling foo-v2 up to 10 -`, - }, { - name: "10->10 30/0 fast readiness, continued after restart which prevented first scale-up", - oldRc: oldRc(7, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("30%"), - maxSurge: intstr.FromString("0%"), - expected: []interface{}{ - down{oldReady: 7, newReady: 0, noop: true}, - up{3}, - down{oldReady: 7, newReady: 3, to: 4}, - up{6}, - down{oldReady: 4, newReady: 6, to: 1}, - up{9}, - down{oldReady: 1, newReady: 9, to: 0}, - up{10}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 7 to 0 (keep 7 pods available, don't exceed 10 pods) -Scaling foo-v2 up to 3 -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 6 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 9 -Scaling foo-v1 down to 0 -Scaling foo-v2 up to 10 -`, - }, { - name: "10->10 0/30 fast readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("0%"), - maxSurge: intstr.FromString("30%"), - expected: []interface{}{ - up{3}, - down{oldReady: 10, newReady: 3, to: 7}, - up{6}, - down{oldReady: 7, newReady: 6, to: 4}, - up{9}, - down{oldReady: 4, newReady: 9, to: 1}, - up{10}, - down{oldReady: 1, newReady: 10, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 10 pods available, don't exceed 13 pods) -Scaling foo-v2 up to 3 -Scaling foo-v1 down to 7 -Scaling foo-v2 up to 6 -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 9 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 0/30 delayed readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("0%"), - maxSurge: intstr.FromString("30%"), - expected: []interface{}{ - up{3}, - down{oldReady: 10, newReady: 0, noop: true}, - down{oldReady: 10, newReady: 1, to: 9}, - up{4}, - down{oldReady: 9, newReady: 3, to: 7}, - up{6}, - down{oldReady: 7, newReady: 6, to: 4}, - up{9}, - down{oldReady: 4, newReady: 9, to: 1}, - up{10}, - down{oldReady: 1, newReady: 9, noop: true}, - down{oldReady: 1, newReady: 10, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 10 pods available, don't exceed 13 pods) -Scaling foo-v2 up to 3 -Scaling foo-v1 down to 9 -Scaling foo-v2 up to 4 -Scaling foo-v1 down to 7 -Scaling foo-v2 up to 6 -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 9 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 10/20 fast readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("10%"), - maxSurge: intstr.FromString("20%"), - expected: []interface{}{ - up{2}, - down{oldReady: 10, newReady: 2, to: 7}, - up{5}, - down{oldReady: 7, newReady: 5, to: 4}, - up{8}, - down{oldReady: 4, newReady: 8, to: 1}, - up{10}, - down{oldReady: 1, newReady: 10, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 9 pods available, don't exceed 12 pods) -Scaling foo-v2 up to 2 -Scaling foo-v1 down to 7 -Scaling foo-v2 up to 5 -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 8 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 10/20 delayed readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("10%"), - maxSurge: intstr.FromString("20%"), - expected: []interface{}{ - up{2}, - down{oldReady: 10, newReady: 2, to: 7}, - up{5}, - down{oldReady: 7, newReady: 4, to: 5}, - up{7}, - down{oldReady: 5, newReady: 4, noop: true}, - down{oldReady: 5, newReady: 7, to: 2}, - up{10}, - down{oldReady: 2, newReady: 9, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 9 pods available, don't exceed 12 pods) -Scaling foo-v2 up to 2 -Scaling foo-v1 down to 7 -Scaling foo-v2 up to 5 -Scaling foo-v1 down to 5 -Scaling foo-v2 up to 7 -Scaling foo-v1 down to 2 -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 10/20 fast readiness continued after restart which prevented first scale-down", - oldRc: oldRc(10, 10), - newRc: newRc(2, 10), - newRcExists: false, - maxUnavail: intstr.FromString("10%"), - maxSurge: intstr.FromString("20%"), - expected: []interface{}{ - down{oldReady: 10, newReady: 2, to: 7}, - up{5}, - down{oldReady: 7, newReady: 5, to: 4}, - up{8}, - down{oldReady: 4, newReady: 8, to: 1}, - up{10}, - down{oldReady: 1, newReady: 10, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 2 to 10, scaling down foo-v1 from 10 to 0 (keep 9 pods available, don't exceed 12 pods) -Scaling foo-v1 down to 7 -Scaling foo-v2 up to 5 -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 8 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 0/100 fast readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("0%"), - maxSurge: intstr.FromString("100%"), - expected: []interface{}{ - up{10}, - down{oldReady: 10, newReady: 10, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 10 pods available, don't exceed 20 pods) -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 0/100 delayed readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("0%"), - maxSurge: intstr.FromString("100%"), - expected: []interface{}{ - up{10}, - down{oldReady: 10, newReady: 0, noop: true}, - down{oldReady: 10, newReady: 2, to: 8}, - down{oldReady: 8, newReady: 7, to: 3}, - down{oldReady: 3, newReady: 10, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 10 pods available, don't exceed 20 pods) -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 8 -Scaling foo-v1 down to 3 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 100/0 fast readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 10), - newRcExists: false, - maxUnavail: intstr.FromString("100%"), - maxSurge: intstr.FromString("0%"), - expected: []interface{}{ - down{oldReady: 10, newReady: 0, to: 0}, - up{10}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 10, scaling down foo-v1 from 10 to 0 (keep 0 pods available, don't exceed 10 pods) -Scaling foo-v1 down to 0 -Scaling foo-v2 up to 10 -`, - }, { - name: "1->1 10/0 fast readiness", - oldRc: oldRc(1, 1), - newRc: newRc(0, 1), - newRcExists: false, - maxUnavail: intstr.FromString("10%"), - maxSurge: intstr.FromString("0%"), - expected: []interface{}{ - down{oldReady: 1, newReady: 0, to: 0}, - up{1}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 1, scaling down foo-v1 from 1 to 0 (keep 0 pods available, don't exceed 1 pods) -Scaling foo-v1 down to 0 -Scaling foo-v2 up to 1 -`, - }, { - name: "1->1 0/10 delayed readiness", - oldRc: oldRc(1, 1), - newRc: newRc(0, 1), - newRcExists: false, - maxUnavail: intstr.FromString("0%"), - maxSurge: intstr.FromString("10%"), - expected: []interface{}{ - up{1}, - down{oldReady: 1, newReady: 0, noop: true}, - down{oldReady: 1, newReady: 1, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 1, scaling down foo-v1 from 1 to 0 (keep 1 pods available, don't exceed 2 pods) -Scaling foo-v2 up to 1 -Scaling foo-v1 down to 0 -`, - }, { - name: "1->1 10/10 delayed readiness", - oldRc: oldRc(1, 1), - newRc: newRc(0, 1), - newRcExists: false, - maxUnavail: intstr.FromString("10%"), - maxSurge: intstr.FromString("10%"), - expected: []interface{}{ - up{1}, - down{oldReady: 1, newReady: 0, noop: true}, - down{oldReady: 1, newReady: 1, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 1, scaling down foo-v1 from 1 to 0 (keep 0 pods available, don't exceed 2 pods) -Scaling foo-v2 up to 1 -Scaling foo-v1 down to 0 -`, - }, { - name: "3->3 1/1 fast readiness (absolute values)", - oldRc: oldRc(3, 3), - newRc: newRc(0, 3), - newRcExists: false, - maxUnavail: intstr.FromInt(0), - maxSurge: intstr.FromInt(1), - expected: []interface{}{ - up{1}, - down{oldReady: 3, newReady: 1, to: 2}, - up{2}, - down{oldReady: 2, newReady: 2, to: 1}, - up{3}, - down{oldReady: 1, newReady: 3, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 3, scaling down foo-v1 from 3 to 0 (keep 3 pods available, don't exceed 4 pods) -Scaling foo-v2 up to 1 -Scaling foo-v1 down to 2 -Scaling foo-v2 up to 2 -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 3 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->10 0/20 fast readiness, continued after restart which resulted in partial first scale-up", - oldRc: oldRc(6, 10), - newRc: newRc(5, 10), - newRcExists: false, - maxUnavail: intstr.FromString("0%"), - maxSurge: intstr.FromString("20%"), - expected: []interface{}{ - up{6}, - down{oldReady: 6, newReady: 6, to: 4}, - up{8}, - down{oldReady: 4, newReady: 8, to: 2}, - up{10}, - down{oldReady: 1, newReady: 10, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 5 to 10, scaling down foo-v1 from 6 to 0 (keep 10 pods available, don't exceed 12 pods) -Scaling foo-v2 up to 6 -Scaling foo-v1 down to 4 -Scaling foo-v2 up to 8 -Scaling foo-v1 down to 2 -Scaling foo-v2 up to 10 -Scaling foo-v1 down to 0 -`, - }, { - name: "10->20 0/300 fast readiness", - oldRc: oldRc(10, 10), - newRc: newRc(0, 20), - newRcExists: false, - maxUnavail: intstr.FromString("0%"), - maxSurge: intstr.FromString("300%"), - expected: []interface{}{ - up{20}, - down{oldReady: 10, newReady: 20, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 20, scaling down foo-v1 from 10 to 0 (keep 20 pods available, don't exceed 70 pods) -Scaling foo-v2 up to 20 -Scaling foo-v1 down to 0 -`, - }, { - name: "1->1 0/1 scale down unavailable rc to a ready rc (rollback)", - oldRc: oldRc(1, 1), - newRc: newRc(1, 1), - newRcExists: true, - maxUnavail: intstr.FromInt(0), - maxSurge: intstr.FromInt(1), - expected: []interface{}{ - up{1}, - down{oldReady: 0, newReady: 1, to: 0}, - }, - output: `Continuing update with existing controller foo-v2. -Scaling up foo-v2 from 1 to 1, scaling down foo-v1 from 1 to 0 (keep 1 pods available, don't exceed 2 pods) -Scaling foo-v1 down to 0 -`, - }, - { - name: "3->0 1/1 desired 0 (absolute values)", - oldRc: oldRc(3, 3), - newRc: newRc(0, 0), - newRcExists: true, - maxUnavail: intstr.FromInt(1), - maxSurge: intstr.FromInt(1), - expected: []interface{}{ - down{oldReady: 3, newReady: 0, to: 0}, - }, - output: `Continuing update with existing controller foo-v2. -Scaling up foo-v2 from 0 to 0, scaling down foo-v1 from 3 to 0 (keep 0 pods available, don't exceed 4 pods) -Scaling foo-v1 down to 0 -`, - }, - { - name: "3->0 10/10 desired 0 (percentages)", - oldRc: oldRc(3, 3), - newRc: newRc(0, 0), - newRcExists: true, - maxUnavail: intstr.FromString("10%"), - maxSurge: intstr.FromString("10%"), - expected: []interface{}{ - down{oldReady: 3, newReady: 0, to: 0}, - }, - output: `Continuing update with existing controller foo-v2. -Scaling up foo-v2 from 0 to 0, scaling down foo-v1 from 3 to 0 (keep 0 pods available, don't exceed 3 pods) -Scaling foo-v1 down to 0 -`, - }, - { - name: "3->0 10/10 desired 0 (create new RC)", - oldRc: oldRc(3, 3), - newRc: newRc(0, 0), - newRcExists: false, - maxUnavail: intstr.FromString("10%"), - maxSurge: intstr.FromString("10%"), - expected: []interface{}{ - down{oldReady: 3, newReady: 0, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 0, scaling down foo-v1 from 3 to 0 (keep 0 pods available, don't exceed 3 pods) -Scaling foo-v1 down to 0 -`, - }, - { - name: "0->0 1/1 desired 0 (absolute values)", - oldRc: oldRc(0, 0), - newRc: newRc(0, 0), - newRcExists: true, - maxUnavail: intstr.FromInt(1), - maxSurge: intstr.FromInt(1), - expected: []interface{}{ - down{oldReady: 0, newReady: 0, to: 0}, - }, - output: `Continuing update with existing controller foo-v2. -Scaling up foo-v2 from 0 to 0, scaling down foo-v1 from 0 to 0 (keep 0 pods available, don't exceed 1 pods) -`, - }, { - name: "30->2 50%/0", - oldRc: oldRc(30, 30), - newRc: newRc(0, 2), - newRcExists: false, - maxUnavail: intstr.FromString("50%"), - maxSurge: intstr.FromInt(0), - expected: []interface{}{ - down{oldReady: 30, newReady: 0, to: 1}, - up{2}, - down{oldReady: 1, newReady: 2, to: 0}, - }, - output: `Created foo-v2 -Scaling up foo-v2 from 0 to 2, scaling down foo-v1 from 30 to 0 (keep 1 pods available, don't exceed 30 pods) -Scaling foo-v1 down to 1 -Scaling foo-v2 up to 2 -Scaling foo-v1 down to 0 -`, - }, - } - - for i, test := range tests { - // Extract expectations into some makeshift FIFOs so they can be returned - // in the correct order from the right places. This lets scale downs be - // expressed a single event even though the data is used from multiple - // interface calls. - oldReady := []int{} - newReady := []int{} - upTo := []int{} - downTo := []int{} - for _, event := range test.expected { - switch e := event.(type) { - case down: - oldReady = append(oldReady, e.oldReady) - newReady = append(newReady, e.newReady) - if !e.noop { - downTo = append(downTo, e.to) - } - case up: - upTo = append(upTo, e.to) - } - } - - // Make a way to get the next item from our FIFOs. Returns -1 if the array - // is empty. - next := func(s *[]int) int { - slice := *s - v := -1 - if len(slice) > 0 { - v = slice[0] - if len(slice) > 1 { - *s = slice[1:] - } else { - *s = []int{} - } - } - return v - } - t.Logf("running test %d (%s) (up: %v, down: %v, oldReady: %v, newReady: %v)", i, test.name, upTo, downTo, oldReady, newReady) - updater := &RollingUpdater{ - ns: "default", - scaleAndWait: func(rc *api.ReplicationController, retry *RetryParams, wait *RetryParams) (*api.ReplicationController, error) { - // Return a scale up or scale down expectation depending on the rc, - // and throw errors if there is no expectation expressed for this - // call. - expected := -1 - switch { - case rc == test.newRc: - t.Logf("scaling up %s:%d", rc.Name, rc.Spec.Replicas) - expected = next(&upTo) - case rc == test.oldRc: - t.Logf("scaling down %s:%d", rc.Name, rc.Spec.Replicas) - expected = next(&downTo) - } - if expected == -1 { - t.Fatalf("unexpected scale of %s to %d", rc.Name, rc.Spec.Replicas) - } else if e, a := expected, rc.Spec.Replicas; e != a { - t.Fatalf("expected scale of %s to %d, got %d", rc.Name, e, a) - } - // Simulate the scale. - rc.Status.Replicas = rc.Spec.Replicas - return rc, nil - }, - getOrCreateTargetController: func(controller *api.ReplicationController, sourceId string) (*api.ReplicationController, bool, error) { - // Simulate a create vs. update of an existing controller. - return test.newRc, test.newRcExists, nil - }, - cleanup: func(oldRc, newRc *api.ReplicationController, config *RollingUpdaterConfig) error { - return nil - }, - } - // Set up a mock readiness check which handles the test assertions. - updater.waitForReadyPods = func(interval, timeout time.Duration, oldRc, newRc *api.ReplicationController) (int, int, error) { - // Return simulated readiness, and throw an error if this call has no - // expectations defined. - oldReady := next(&oldReady) - newReady := next(&newReady) - if oldReady == -1 || newReady == -1 { - t.Fatalf("unexpected waitForReadyPods call for:\noldRc: %+v\nnewRc: %+v", oldRc, newRc) - } - return oldReady, newReady, nil - } - var buffer bytes.Buffer - config := &RollingUpdaterConfig{ - Out: &buffer, - OldRc: test.oldRc, - NewRc: test.newRc, - UpdatePeriod: 0, - Interval: time.Millisecond, - Timeout: time.Millisecond, - CleanupPolicy: DeleteRollingUpdateCleanupPolicy, - MaxUnavailable: test.maxUnavail, - MaxSurge: test.maxSurge, - } - err := updater.Update(config) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if buffer.String() != test.output { - t.Errorf("Bad output. expected:\n%s\ngot:\n%s", test.output, buffer.String()) - } - } -} - -// TestUpdate_progressTimeout ensures that an update which isn't making any -// progress will eventually time out with a specified error. -func TestUpdate_progressTimeout(t *testing.T) { - oldRc := oldRc(2, 2) - newRc := newRc(0, 2) - updater := &RollingUpdater{ - ns: "default", - scaleAndWait: func(rc *api.ReplicationController, retry *RetryParams, wait *RetryParams) (*api.ReplicationController, error) { - // Do nothing. - return rc, nil - }, - getOrCreateTargetController: func(controller *api.ReplicationController, sourceId string) (*api.ReplicationController, bool, error) { - return newRc, false, nil - }, - cleanup: func(oldRc, newRc *api.ReplicationController, config *RollingUpdaterConfig) error { - return nil - }, - } - updater.waitForReadyPods = func(interval, timeout time.Duration, oldRc, newRc *api.ReplicationController) (int, int, error) { - // Coerce a timeout by pods never becoming ready. - return 0, 0, nil - } - var buffer bytes.Buffer - config := &RollingUpdaterConfig{ - Out: &buffer, - OldRc: oldRc, - NewRc: newRc, - UpdatePeriod: 0, - Interval: time.Millisecond, - Timeout: time.Millisecond, - CleanupPolicy: DeleteRollingUpdateCleanupPolicy, - MaxUnavailable: intstr.FromInt(0), - MaxSurge: intstr.FromInt(1), - } - err := updater.Update(config) - if err == nil { - t.Fatalf("expected an error") - } - if e, a := "timed out waiting for any update progress to be made", err.Error(); e != a { - t.Fatalf("expected error message: %s, got: %s", e, a) - } -} - -func TestUpdate_assignOriginalAnnotation(t *testing.T) { - oldRc := oldRc(1, 1) - delete(oldRc.Annotations, originalReplicasAnnotation) - newRc := newRc(1, 1) - var updatedOldRc *api.ReplicationController - fake := &testclient.Fake{} - fake.AddReactor("*", "*", func(action testclient.Action) (handled bool, ret runtime.Object, err error) { - switch a := action.(type) { - case testclient.GetAction: - return true, oldRc, nil - case testclient.UpdateAction: - updatedOldRc = a.GetObject().(*api.ReplicationController) - return true, updatedOldRc, nil - } - return false, nil, nil - }) - updater := &RollingUpdater{ - c: fake, - ns: "default", - scaleAndWait: func(rc *api.ReplicationController, retry *RetryParams, wait *RetryParams) (*api.ReplicationController, error) { - return rc, nil - }, - getOrCreateTargetController: func(controller *api.ReplicationController, sourceId string) (*api.ReplicationController, bool, error) { - return newRc, false, nil - }, - cleanup: func(oldRc, newRc *api.ReplicationController, config *RollingUpdaterConfig) error { - return nil - }, - waitForReadyPods: func(interval, timeout time.Duration, oldRc, newRc *api.ReplicationController) (int, int, error) { - return 1, 1, nil - }, - } - var buffer bytes.Buffer - config := &RollingUpdaterConfig{ - Out: &buffer, - OldRc: oldRc, - NewRc: newRc, - UpdatePeriod: 0, - Interval: time.Millisecond, - Timeout: time.Millisecond, - CleanupPolicy: DeleteRollingUpdateCleanupPolicy, - MaxUnavailable: intstr.FromString("100%"), - } - err := updater.Update(config) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if updatedOldRc == nil { - t.Fatalf("expected rc to be updated") - } - if e, a := "1", updatedOldRc.Annotations[originalReplicasAnnotation]; e != a { - t.Fatalf("expected annotation value %s, got %s", e, a) - } -} - -func TestRollingUpdater_multipleContainersInPod(t *testing.T) { - tests := []struct { - oldRc *api.ReplicationController - newRc *api.ReplicationController - - container string - image string - deploymentKey string - }{ - { - oldRc: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "dk": "old", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "dk": "old", - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "container1", - Image: "image1", - }, - { - Name: "container2", - Image: "image2", - }, - }, - }, - }, - }, - }, - newRc: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "dk": "old", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "dk": "old", - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "container1", - Image: "newimage", - }, - { - Name: "container2", - Image: "image2", - }, - }, - }, - }, - }, - }, - container: "container1", - image: "newimage", - deploymentKey: "dk", - }, - { - oldRc: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - }, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "dk": "old", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "dk": "old", - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "container1", - Image: "image1", - }, - }, - }, - }, - }, - }, - newRc: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - }, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "dk": "old", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "dk": "old", - }, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "container1", - Image: "newimage", - }, - }, - }, - }, - }, - }, - container: "container1", - image: "newimage", - deploymentKey: "dk", - }, - } - - for _, test := range tests { - fake := &testclient.Fake{} - fake.AddReactor("*", "*", func(action testclient.Action) (handled bool, ret runtime.Object, err error) { - switch action.(type) { - case testclient.GetAction: - return true, test.oldRc, nil - } - return false, nil, nil - }) - - codec := testapi.Default.Codec() - - deploymentHash, err := api.HashObject(test.newRc, codec) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - test.newRc.Spec.Selector[test.deploymentKey] = deploymentHash - test.newRc.Spec.Template.Labels[test.deploymentKey] = deploymentHash - test.newRc.Name = fmt.Sprintf("%s-%s", test.newRc.Name, deploymentHash) - - updatedRc, err := CreateNewControllerFromCurrentController(fake, codec, "", test.oldRc.ObjectMeta.Name, test.newRc.ObjectMeta.Name, test.image, test.container, test.deploymentKey) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !reflect.DeepEqual(updatedRc, test.newRc) { - t.Errorf("expected:\n%v\ngot:\n%v\n", test.newRc, updatedRc) - } - } -} - -// TestRollingUpdater_cleanupWithClients ensures that the cleanup policy is -// correctly implemented. -func TestRollingUpdater_cleanupWithClients(t *testing.T) { - rc := oldRc(2, 2) - rcExisting := newRc(1, 3) - - tests := []struct { - name string - policy RollingUpdaterCleanupPolicy - responses []runtime.Object - expected []string - }{ - { - name: "preserve", - policy: PreserveRollingUpdateCleanupPolicy, - responses: []runtime.Object{rcExisting}, - expected: []string{ - "get", - "update", - "get", - "get", - }, - }, - { - name: "delete", - policy: DeleteRollingUpdateCleanupPolicy, - responses: []runtime.Object{rcExisting}, - expected: []string{ - "get", - "update", - "get", - "get", - "delete", - }, - }, - { - name: "rename", - policy: RenameRollingUpdateCleanupPolicy, - responses: []runtime.Object{rcExisting}, - expected: []string{ - "get", - "update", - "get", - "get", - "delete", - "create", - "delete", - }, - }, - } - - for _, test := range tests { - fake := testclient.NewSimpleFake(test.responses...) - updater := &RollingUpdater{ - ns: "default", - c: fake, - } - config := &RollingUpdaterConfig{ - Out: ioutil.Discard, - OldRc: rc, - NewRc: rcExisting, - UpdatePeriod: 0, - Interval: time.Millisecond, - Timeout: time.Millisecond, - CleanupPolicy: test.policy, - } - err := updater.cleanupWithClients(rc, rcExisting, config) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(fake.Actions()) != len(test.expected) { - t.Fatalf("%s: unexpected actions: %v, expected %v", test.name, fake.Actions(), test.expected) - } - for j, action := range fake.Actions() { - if e, a := test.expected[j], action.GetVerb(); e != a { - t.Errorf("%s: unexpected action: expected %s, got %s", test.name, e, a) - } - } - } -} - -func TestFindSourceController(t *testing.T) { - ctrl1 := api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - sourceIdAnnotation: "bar:1234", - }, - }, - } - ctrl2 := api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "bar", - Annotations: map[string]string{ - sourceIdAnnotation: "foo:12345", - }, - }, - } - ctrl3 := api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{ - sourceIdAnnotation: "baz:45667", - }, - }, - } - tests := []struct { - list *api.ReplicationControllerList - expectedController *api.ReplicationController - err error - name string - expectError bool - }{ - { - list: &api.ReplicationControllerList{}, - expectError: true, - }, - { - list: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ctrl1}, - }, - name: "foo", - expectError: true, - }, - { - list: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ctrl1}, - }, - name: "bar", - expectedController: &ctrl1, - }, - { - list: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ctrl1, ctrl2}, - }, - name: "bar", - expectedController: &ctrl1, - }, - { - list: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ctrl1, ctrl2}, - }, - name: "foo", - expectedController: &ctrl2, - }, - { - list: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ctrl1, ctrl2, ctrl3}, - }, - name: "baz", - expectedController: &ctrl3, - }, - } - for _, test := range tests { - fakeClient := testclient.NewSimpleFake(test.list) - ctrl, err := FindSourceController(fakeClient, "default", test.name) - if test.expectError && err == nil { - t.Errorf("unexpected non-error") - } - if !test.expectError && err != nil { - t.Errorf("unexpected error") - } - if !reflect.DeepEqual(ctrl, test.expectedController) { - t.Errorf("expected:\n%v\ngot:\n%v\n", test.expectedController, ctrl) - } - } -} - -func TestUpdateExistingReplicationController(t *testing.T) { - tests := []struct { - rc *api.ReplicationController - name string - deploymentKey string - deploymentValue string - - expectedRc *api.ReplicationController - expectErr bool - }{ - { - rc: &api.ReplicationController{ - Spec: api.ReplicationControllerSpec{ - Template: &api.PodTemplateSpec{}, - }, - }, - name: "foo", - deploymentKey: "dk", - deploymentValue: "some-hash", - - expectedRc: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{ - "kubectl.kubernetes.io/next-controller-id": "foo", - }, - }, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "dk": "some-hash", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "dk": "some-hash", - }, - }, - }, - }, - }, - }, - { - rc: &api.ReplicationController{ - Spec: api.ReplicationControllerSpec{ - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "dk": "some-other-hash", - }, - }, - }, - Selector: map[string]string{ - "dk": "some-other-hash", - }, - }, - }, - name: "foo", - deploymentKey: "dk", - deploymentValue: "some-hash", - - expectedRc: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Annotations: map[string]string{ - "kubectl.kubernetes.io/next-controller-id": "foo", - }, - }, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "dk": "some-other-hash", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "dk": "some-other-hash", - }, - }, - }, - }, - }, - }, - } - for _, test := range tests { - buffer := &bytes.Buffer{} - fakeClient := testclient.NewSimpleFake(test.expectedRc) - rc, err := UpdateExistingReplicationController(fakeClient, test.rc, "default", test.name, test.deploymentKey, test.deploymentValue, buffer) - if !reflect.DeepEqual(rc, test.expectedRc) { - t.Errorf("expected:\n%#v\ngot:\n%#v\n", test.expectedRc, rc) - } - if test.expectErr && err == nil { - t.Errorf("unexpected non-error") - } - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - } -} - -func TestUpdateWithRetries(t *testing.T) { - codec := testapi.Default.Codec() - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "rc", - Labels: map[string]string{ - "foo": "bar", - }, - }, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "foo": "bar", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - Spec: apitesting.DeepEqualSafePodSpec(), - }, - }, - } - - // Test end to end updating of the rc with retries. Essentially make sure the update handler - // sees the right updates, failures in update/get are handled properly, and that the updated - // rc with new resource version is returned to the caller. Without any of these rollingupdate - // will fail cryptically. - newRc := *rc - newRc.ResourceVersion = "2" - newRc.Spec.Selector["baz"] = "foobar" - updates := []*http.Response{ - {StatusCode: 500, Body: objBody(codec, &api.ReplicationController{})}, - {StatusCode: 500, Body: objBody(codec, &api.ReplicationController{})}, - {StatusCode: 200, Body: objBody(codec, &newRc)}, - } - gets := []*http.Response{ - {StatusCode: 500, Body: objBody(codec, &api.ReplicationController{})}, - {StatusCode: 200, Body: objBody(codec, rc)}, - } - fakeClient := &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == testapi.Default.ResourcePath("replicationcontrollers", "default", "rc") && m == "PUT": - update := updates[0] - updates = updates[1:] - // We should always get an update with a valid rc even when the get fails. The rc should always - // contain the update. - if c, ok := readOrDie(t, req, codec).(*api.ReplicationController); !ok || !reflect.DeepEqual(rc, c) { - t.Errorf("Unexpected update body, got %+v expected %+v", c, rc) - } else if sel, ok := c.Spec.Selector["baz"]; !ok || sel != "foobar" { - t.Errorf("Expected selector label update, got %+v", c.Spec.Selector) - } else { - delete(c.Spec.Selector, "baz") - } - return update, nil - case p == testapi.Default.ResourcePath("replicationcontrollers", "default", "rc") && m == "GET": - get := gets[0] - gets = gets[1:] - return get, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - clientConfig := &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - client := client.NewOrDie(clientConfig) - client.Client = fakeClient.Client - - if rc, err := updateWithRetries( - client.ReplicationControllers("default"), rc, func(c *api.ReplicationController) { - c.Spec.Selector["baz"] = "foobar" - }); err != nil { - t.Errorf("unexpected error: %v", err) - } else if sel, ok := rc.Spec.Selector["baz"]; !ok || sel != "foobar" || rc.ResourceVersion != "2" { - t.Errorf("Expected updated rc, got %+v", rc) - } - if len(updates) != 0 || len(gets) != 0 { - t.Errorf("Remaining updates %+v gets %+v", updates, gets) - } -} - -func readOrDie(t *testing.T, req *http.Request, codec runtime.Codec) runtime.Object { - data, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("Error reading: %v", err) - t.FailNow() - } - obj, err := runtime.Decode(codec, data) - if err != nil { - t.Errorf("error decoding: %v", err) - t.FailNow() - } - return obj -} - -func objBody(codec runtime.Codec, obj runtime.Object) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, obj)))) -} - -func TestAddDeploymentHash(t *testing.T) { - buf := &bytes.Buffer{} - codec := testapi.Default.Codec() - rc := &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{Name: "rc"}, - Spec: api.ReplicationControllerSpec{ - Selector: map[string]string{ - "foo": "bar", - }, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - } - - podList := &api.PodList{ - Items: []api.Pod{ - {ObjectMeta: api.ObjectMeta{Name: "foo"}}, - {ObjectMeta: api.ObjectMeta{Name: "bar"}}, - {ObjectMeta: api.ObjectMeta{Name: "baz"}}, - }, - } - - seen := sets.String{} - updatedRc := false - fakeClient := &fake.RESTClient{ - Codec: codec, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - switch p, m := req.URL.Path, req.Method; { - case p == testapi.Default.ResourcePath("pods", "default", "") && m == "GET": - if req.URL.RawQuery != "labelSelector=foo%3Dbar" { - t.Errorf("Unexpected query string: %s", req.URL.RawQuery) - } - return &http.Response{StatusCode: 200, Body: objBody(codec, podList)}, nil - case p == testapi.Default.ResourcePath("pods", "default", "foo") && m == "PUT": - seen.Insert("foo") - obj := readOrDie(t, req, codec) - podList.Items[0] = *(obj.(*api.Pod)) - return &http.Response{StatusCode: 200, Body: objBody(codec, &podList.Items[0])}, nil - case p == testapi.Default.ResourcePath("pods", "default", "bar") && m == "PUT": - seen.Insert("bar") - obj := readOrDie(t, req, codec) - podList.Items[1] = *(obj.(*api.Pod)) - return &http.Response{StatusCode: 200, Body: objBody(codec, &podList.Items[1])}, nil - case p == testapi.Default.ResourcePath("pods", "default", "baz") && m == "PUT": - seen.Insert("baz") - obj := readOrDie(t, req, codec) - podList.Items[2] = *(obj.(*api.Pod)) - return &http.Response{StatusCode: 200, Body: objBody(codec, &podList.Items[2])}, nil - case p == testapi.Default.ResourcePath("replicationcontrollers", "default", "rc") && m == "PUT": - updatedRc = true - return &http.Response{StatusCode: 200, Body: objBody(codec, rc)}, nil - default: - t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) - return nil, nil - } - }), - } - clientConfig := &client.Config{ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} - client := client.NewOrDie(clientConfig) - client.Client = fakeClient.Client - - if _, err := AddDeploymentKeyToReplicationController(rc, client, "dk", "hash", api.NamespaceDefault, buf); err != nil { - t.Errorf("unexpected error: %v", err) - } - for _, pod := range podList.Items { - if !seen.Has(pod.Name) { - t.Errorf("Missing update for pod: %s", pod.Name) - } - } - if !updatedRc { - t.Errorf("Failed to update replication controller with new labels") - } -} - -func TestRollingUpdater_pollForReadyPods(t *testing.T) { - mkpod := func(owner *api.ReplicationController, ready bool) *api.Pod { - labels := map[string]string{} - for k, v := range owner.Spec.Selector { - labels[k] = v - } - status := api.ConditionTrue - if !ready { - status = api.ConditionFalse - } - return &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "pod", - Labels: labels, - }, - Status: api.PodStatus{ - Conditions: []api.PodCondition{ - { - Type: api.PodReady, - Status: status, - }, - }, - }, - } - } - - tests := []struct { - oldRc *api.ReplicationController - newRc *api.ReplicationController - // expectated old/new ready counts - oldReady int - newReady int - // pods owned by the rcs; indicate whether they're ready - oldPods []bool - newPods []bool - }{ - { - oldRc: oldRc(4, 4), - newRc: newRc(4, 4), - oldReady: 4, - newReady: 2, - oldPods: []bool{ - true, - true, - true, - true, - }, - newPods: []bool{ - true, - false, - true, - false, - }, - }, - { - oldRc: oldRc(4, 4), - newRc: newRc(4, 4), - oldReady: 0, - newReady: 1, - oldPods: []bool{ - false, - }, - newPods: []bool{ - true, - }, - }, - { - oldRc: oldRc(4, 4), - newRc: newRc(4, 4), - oldReady: 1, - newReady: 0, - oldPods: []bool{ - true, - }, - newPods: []bool{ - false, - }, - }, - } - - for i, test := range tests { - t.Logf("evaluating test %d", i) - // Populate the fake client with pods associated with their owners. - pods := []runtime.Object{} - for _, ready := range test.oldPods { - pods = append(pods, mkpod(test.oldRc, ready)) - } - for _, ready := range test.newPods { - pods = append(pods, mkpod(test.newRc, ready)) - } - client := testclient.NewSimpleFake(pods...) - - updater := &RollingUpdater{ - ns: "default", - c: client, - } - oldReady, newReady, err := updater.pollForReadyPods(time.Millisecond, time.Second, test.oldRc, test.newRc) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if e, a := test.oldReady, oldReady; e != a { - t.Errorf("expected old ready %d, got %d", e, a) - } - if e, a := test.newReady, newReady; e != a { - t.Errorf("expected new ready %d, got %d", e, a) - } - } -} - -func TestRollingUpdater_extractMaxValue(t *testing.T) { - tests := []struct { - field intstr.IntOrString - original int - expected int - valid bool - }{ - { - field: intstr.FromInt(1), - original: 100, - expected: 1, - valid: true, - }, - { - field: intstr.FromInt(0), - original: 100, - expected: 0, - valid: true, - }, - { - field: intstr.FromInt(-1), - original: 100, - valid: false, - }, - { - field: intstr.FromString("10%"), - original: 100, - expected: 10, - valid: true, - }, - { - field: intstr.FromString("100%"), - original: 100, - expected: 100, - valid: true, - }, - { - field: intstr.FromString("200%"), - original: 100, - expected: 200, - valid: true, - }, - { - field: intstr.FromString("0%"), - original: 100, - expected: 0, - valid: true, - }, - { - field: intstr.FromString("-1%"), - original: 100, - valid: false, - }, - } - - for i, test := range tests { - t.Logf("evaluating test %d", i) - max, err := extractMaxValue(test.field, "field", test.original) - if test.valid && err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !test.valid && err == nil { - t.Fatalf("expected an error") - } - if e, a := test.expected, max; e != a { - t.Fatalf("expected max %d, got %d", e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/run.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/run.go index e0ed8ada8..688b570e7 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/run.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/run.go @@ -24,6 +24,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + batchv1 "k8s.io/kubernetes/pkg/apis/batch/v1" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/validation" @@ -187,6 +189,24 @@ func getEnvs(genericParams map[string]interface{}) ([]api.EnvVar, error) { return envs, nil } +func getV1Envs(genericParams map[string]interface{}) ([]v1.EnvVar, error) { + var envs []v1.EnvVar + envStrings, found := genericParams["env"] + if found { + if envStringArray, isArray := envStrings.([]string); isArray { + var err error + envs, err = parseV1Envs(envStringArray) + if err != nil { + return nil, err + } + delete(genericParams, "env") + } else { + return nil, fmt.Errorf("expected []string, found: %v", envStrings) + } + } + return envs, nil +} + type JobV1Beta1 struct{} func (JobV1Beta1) ParamNames() []GeneratorParam { @@ -256,7 +276,7 @@ func (JobV1Beta1) Generate(genericParams map[string]interface{}) (runtime.Object restartPolicy := api.RestartPolicy(params["restart"]) if len(restartPolicy) == 0 { - restartPolicy = api.RestartPolicyAlways + restartPolicy = api.RestartPolicyNever } podSpec.RestartPolicy = restartPolicy @@ -269,6 +289,7 @@ func (JobV1Beta1) Generate(genericParams map[string]interface{}) (runtime.Object Selector: &unversioned.LabelSelector{ MatchLabels: labels, }, + ManualSelector: newBool(true), Template: api.PodTemplateSpec{ ObjectMeta: api.ObjectMeta{ Labels: labels, @@ -281,6 +302,97 @@ func (JobV1Beta1) Generate(genericParams map[string]interface{}) (runtime.Object return &job, nil } +type JobV1 struct{} + +func (JobV1) ParamNames() []GeneratorParam { + return []GeneratorParam{ + {"labels", false}, + {"default-name", false}, + {"name", true}, + {"image", true}, + {"port", false}, + {"hostport", false}, + {"stdin", false}, + {"leave-stdin-open", false}, + {"tty", false}, + {"command", false}, + {"args", false}, + {"env", false}, + {"requests", false}, + {"limits", false}, + {"restart", false}, + } +} + +func (JobV1) Generate(genericParams map[string]interface{}) (runtime.Object, error) { + args, err := getArgs(genericParams) + if err != nil { + return nil, err + } + + envs, err := getV1Envs(genericParams) + if err != nil { + return nil, err + } + + params, err := getParams(genericParams) + if err != nil { + return nil, err + } + + name, err := getName(params) + if err != nil { + return nil, err + } + + labels, err := getLabels(params, true, name) + if err != nil { + return nil, err + } + + podSpec, err := makeV1PodSpec(params, name) + if err != nil { + return nil, err + } + + if err = updateV1PodContainers(params, args, envs, podSpec); err != nil { + return nil, err + } + + leaveStdinOpen, err := GetBool(params, "leave-stdin-open", false) + if err != nil { + return nil, err + } + podSpec.Containers[0].StdinOnce = !leaveStdinOpen && podSpec.Containers[0].Stdin + + if err := updateV1PodPorts(params, podSpec); err != nil { + return nil, err + } + + restartPolicy := v1.RestartPolicy(params["restart"]) + if len(restartPolicy) == 0 { + restartPolicy = v1.RestartPolicyNever + } + podSpec.RestartPolicy = restartPolicy + + job := batchv1.Job{ + ObjectMeta: v1.ObjectMeta{ + Name: name, + Labels: labels, + }, + Spec: batchv1.JobSpec{ + Template: v1.PodTemplateSpec{ + ObjectMeta: v1.ObjectMeta{ + Labels: labels, + }, + Spec: *podSpec, + }, + }, + } + + return &job, nil +} + type BasicReplicationController struct{} func (BasicReplicationController) ParamNames() []GeneratorParam { @@ -326,6 +438,30 @@ func populateResourceList(spec string) (api.ResourceList, error) { return result, nil } +// populateResourceList takes strings of form =,= +func populateV1ResourceList(spec string) (v1.ResourceList, error) { + // empty input gets a nil response to preserve generator test expected behaviors + if spec == "" { + return nil, nil + } + + result := v1.ResourceList{} + resourceStatements := strings.Split(spec, ",") + for _, resourceStatement := range resourceStatements { + parts := strings.Split(resourceStatement, "=") + if len(parts) != 2 { + return nil, fmt.Errorf("Invalid argument syntax %v, expected =", resourceStatement) + } + resourceName := v1.ResourceName(parts[0]) + resourceQuantity, err := resource.ParseQuantity(parts[1]) + if err != nil { + return nil, err + } + result[resourceName] = *resourceQuantity + } + return result, nil +} + // HandleResourceRequirements parses the limits and requests parameters if specified func HandleResourceRequirements(params map[string]string) (api.ResourceRequirements, error) { result := api.ResourceRequirements{} @@ -342,6 +478,22 @@ func HandleResourceRequirements(params map[string]string) (api.ResourceRequireme return result, nil } +// HandleResourceRequirements parses the limits and requests parameters if specified +func handleV1ResourceRequirements(params map[string]string) (v1.ResourceRequirements, error) { + result := v1.ResourceRequirements{} + limits, err := populateV1ResourceList(params["limits"]) + if err != nil { + return result, err + } + result.Limits = limits + requests, err := populateV1ResourceList(params["requests"]) + if err != nil { + return result, err + } + result.Requests = requests + return result, nil +} + func makePodSpec(params map[string]string, name string) (*api.PodSpec, error) { stdin, err := GetBool(params, "stdin", false) if err != nil { @@ -372,6 +524,36 @@ func makePodSpec(params map[string]string, name string) (*api.PodSpec, error) { return &spec, nil } +func makeV1PodSpec(params map[string]string, name string) (*v1.PodSpec, error) { + stdin, err := GetBool(params, "stdin", false) + if err != nil { + return nil, err + } + + tty, err := GetBool(params, "tty", false) + if err != nil { + return nil, err + } + + resourceRequirements, err := handleV1ResourceRequirements(params) + if err != nil { + return nil, err + } + + spec := v1.PodSpec{ + Containers: []v1.Container{ + { + Name: name, + Image: params["image"], + Stdin: stdin, + TTY: tty, + Resources: resourceRequirements, + }, + }, + } + return &spec, nil +} + func (BasicReplicationController) Generate(genericParams map[string]interface{}) (runtime.Object, error) { args, err := getArgs(genericParams) if err != nil { @@ -454,6 +636,25 @@ func updatePodContainers(params map[string]string, args []string, envs []api.Env return nil } +func updateV1PodContainers(params map[string]string, args []string, envs []v1.EnvVar, podSpec *v1.PodSpec) error { + if len(args) > 0 { + command, err := GetBool(params, "command", false) + if err != nil { + return err + } + if command { + podSpec.Containers[0].Command = args + } else { + podSpec.Containers[0].Args = args + } + } + + if len(envs) > 0 { + podSpec.Containers[0].Env = envs + } + return nil +} + func updatePodPorts(params map[string]string, podSpec *api.PodSpec) (err error) { port := -1 hostPort := -1 @@ -488,6 +689,40 @@ func updatePodPorts(params map[string]string, podSpec *api.PodSpec) (err error) return nil } +func updateV1PodPorts(params map[string]string, podSpec *v1.PodSpec) (err error) { + port := -1 + hostPort := -1 + if len(params["port"]) > 0 { + port, err = strconv.Atoi(params["port"]) + if err != nil { + return err + } + } + + if len(params["hostport"]) > 0 { + hostPort, err = strconv.Atoi(params["hostport"]) + if err != nil { + return err + } + if hostPort > 0 && port < 0 { + return fmt.Errorf("--hostport requires --port to be specified") + } + } + + // Don't include the port if it was not specified. + if port > 0 { + podSpec.Containers[0].Ports = []v1.ContainerPort{ + { + ContainerPort: int32(port), + }, + } + if hostPort > 0 { + podSpec.Containers[0].Ports[0].HostPort = int32(hostPort) + } + } + return nil +} + type BasicPod struct{} func (BasicPod) ParamNames() []GeneratorParam { @@ -607,3 +842,27 @@ func parseEnvs(envArray []string) ([]api.EnvVar, error) { } return envs, nil } + +func parseV1Envs(envArray []string) ([]v1.EnvVar, error) { + envs := []v1.EnvVar{} + for _, env := range envArray { + pos := strings.Index(env, "=") + if pos == -1 { + return nil, fmt.Errorf("invalid env: %v", env) + } + name := env[:pos] + value := env[pos+1:] + if len(name) == 0 || !validation.IsCIdentifier(name) || len(value) == 0 { + return nil, fmt.Errorf("invalid env: %v", env) + } + envVar := v1.EnvVar{Name: name, Value: value} + envs = append(envs, envVar) + } + return envs, nil +} + +func newBool(val bool) *bool { + p := new(bool) + *p = val + return p +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/run_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/run_test.go deleted file mode 100644 index 27a366c41..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/run_test.go +++ /dev/null @@ -1,883 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" -) - -func TestGenerate(t *testing.T) { - tests := []struct { - params map[string]interface{} - expected *api.ReplicationController - expectErr bool - }{ - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "port": "-1", - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"run": "foo"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - }, - }, - }, - }, - }, - }, - }, - - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "port": "-1", - "env": []string{"a=b", "c=d"}, - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"run": "foo"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Env: []api.EnvVar{ - { - Name: "a", - Value: "b", - }, - { - Name: "c", - Value: "d", - }, - }, - }, - }, - }, - }, - }, - }, - }, - - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "port": "-1", - "args": []string{"bar", "baz", "blah"}, - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"run": "foo"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Args: []string{"bar", "baz", "blah"}, - }, - }, - }, - }, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "port": "-1", - "args": []string{"bar", "baz", "blah"}, - "command": "true", - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"run": "foo"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Command: []string{"bar", "baz", "blah"}, - }, - }, - }, - }, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "port": "80", - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"run": "foo"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Ports: []api.ContainerPort{ - { - ContainerPort: 80, - }, - }, - }, - }, - }, - }, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "port": "80", - "hostport": "80", - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"run": "foo"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"run": "foo"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Ports: []api.ContainerPort{ - { - ContainerPort: 80, - HostPort: 80, - }, - }, - }, - }, - }, - }, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "hostport": "80", - }, - expected: nil, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"foo": "bar", "baz": "blah"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - }, - }, - }, - }, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "hostport": "80", - }, - expected: nil, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - "requests": "cpu100m,memory=100Mi", - }, - expected: nil, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - "requests": "cpu=100m&memory=100Mi", - }, - expected: nil, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - "requests": "cpu=", - }, - expected: nil, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - "requests": "cpu=100m,memory=100Mi", - "limits": "cpu=400m,memory=200Mi", - }, - expected: &api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 1, - Selector: map[string]string{"foo": "bar", "baz": "blah"}, - Template: &api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100m"), - api.ResourceMemory: resource.MustParse("100Mi"), - }, - Limits: api.ResourceList{ - api.ResourceCPU: resource.MustParse("400m"), - api.ResourceMemory: resource.MustParse("200Mi"), - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - generator := BasicReplicationController{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*api.ReplicationController).Spec.Template, test.expected.Spec.Template) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected.Spec.Template, obj.(*api.ReplicationController).Spec.Template) - } - } -} - -func TestGeneratePod(t *testing.T) { - tests := []struct { - params map[string]interface{} - expected *api.Pod - expectErr bool - }{ - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "port": "-1", - }, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - ImagePullPolicy: api.PullIfNotPresent, - }, - }, - DNSPolicy: api.DNSClusterFirst, - RestartPolicy: api.RestartPolicyAlways, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "env": []string{"a", "c"}, - }, - - expected: nil, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "env": []string{"a=b", "c=d"}, - }, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - ImagePullPolicy: api.PullIfNotPresent, - Env: []api.EnvVar{ - { - Name: "a", - Value: "b", - }, - { - Name: "c", - Value: "d", - }, - }, - }, - }, - DNSPolicy: api.DNSClusterFirst, - RestartPolicy: api.RestartPolicyAlways, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "port": "80", - }, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - ImagePullPolicy: api.PullIfNotPresent, - Ports: []api.ContainerPort{ - { - ContainerPort: 80, - }, - }, - }, - }, - DNSPolicy: api.DNSClusterFirst, - RestartPolicy: api.RestartPolicyAlways, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "port": "80", - "hostport": "80", - }, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - ImagePullPolicy: api.PullIfNotPresent, - Ports: []api.ContainerPort{ - { - ContainerPort: 80, - HostPort: 80, - }, - }, - }, - }, - DNSPolicy: api.DNSClusterFirst, - RestartPolicy: api.RestartPolicyAlways, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "hostport": "80", - }, - expected: nil, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - }, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - ImagePullPolicy: api.PullIfNotPresent, - }, - }, - DNSPolicy: api.DNSClusterFirst, - RestartPolicy: api.RestartPolicyAlways, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - "stdin": "true", - }, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - ImagePullPolicy: api.PullIfNotPresent, - Stdin: true, - StdinOnce: true, - }, - }, - DNSPolicy: api.DNSClusterFirst, - RestartPolicy: api.RestartPolicyAlways, - }, - }, - }, - { - params: map[string]interface{}{ - "name": "foo", - "image": "someimage", - "replicas": "1", - "labels": "foo=bar,baz=blah", - "stdin": "true", - "leave-stdin-open": "true", - }, - expected: &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - ImagePullPolicy: api.PullIfNotPresent, - Stdin: true, - StdinOnce: false, - }, - }, - DNSPolicy: api.DNSClusterFirst, - RestartPolicy: api.RestartPolicyAlways, - }, - }, - }, - } - generator := BasicPod{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*api.Pod), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*api.Pod)) - } - } -} - -func TestGenerateDeployment(t *testing.T) { - tests := []struct { - params map[string]interface{} - expected *extensions.Deployment - expectErr bool - }{ - { - params: map[string]interface{}{ - "labels": "foo=bar,baz=blah", - "name": "foo", - "replicas": "3", - "image": "someimage", - "port": "80", - "hostport": "80", - "stdin": "true", - "command": "true", - "args": []string{"bar", "baz", "blah"}, - "env": []string{"a=b", "c=d"}, - "requests": "cpu=100m,memory=100Mi", - "limits": "cpu=400m,memory=200Mi", - }, - expected: &extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: extensions.DeploymentSpec{ - Replicas: 3, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"foo": "bar", "baz": "blah"}}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Stdin: true, - Ports: []api.ContainerPort{ - { - ContainerPort: 80, - HostPort: 80, - }, - }, - Command: []string{"bar", "baz", "blah"}, - Env: []api.EnvVar{ - { - Name: "a", - Value: "b", - }, - { - Name: "c", - Value: "d", - }, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100m"), - api.ResourceMemory: resource.MustParse("100Mi"), - }, - Limits: api.ResourceList{ - api.ResourceCPU: resource.MustParse("400m"), - api.ResourceMemory: resource.MustParse("200Mi"), - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - - generator := DeploymentV1Beta1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*extensions.Deployment), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*extensions.Deployment)) - } - } -} - -func TestGenerateJob(t *testing.T) { - tests := []struct { - params map[string]interface{} - expected *extensions.Job - expectErr bool - }{ - { - params: map[string]interface{}{ - "labels": "foo=bar,baz=blah", - "name": "foo", - "image": "someimage", - "port": "80", - "hostport": "80", - "stdin": "true", - "leave-stdin-open": "true", - "command": "true", - "args": []string{"bar", "baz", "blah"}, - "env": []string{"a=b", "c=d"}, - "requests": "cpu=100m,memory=100Mi", - "limits": "cpu=400m,memory=200Mi", - "restart": "OnFailure", - }, - expected: &extensions.Job{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: extensions.JobSpec{ - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: map[string]string{"foo": "bar", "baz": "blah"}, - }, - Spec: api.PodSpec{ - RestartPolicy: api.RestartPolicyOnFailure, - Containers: []api.Container{ - { - Name: "foo", - Image: "someimage", - Stdin: true, - StdinOnce: false, - Ports: []api.ContainerPort{ - { - ContainerPort: 80, - HostPort: 80, - }, - }, - Command: []string{"bar", "baz", "blah"}, - Env: []api.EnvVar{ - { - Name: "a", - Value: "b", - }, - { - Name: "c", - Value: "d", - }, - }, - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceCPU: resource.MustParse("100m"), - api.ResourceMemory: resource.MustParse("100Mi"), - }, - Limits: api.ResourceList{ - api.ResourceCPU: resource.MustParse("400m"), - api.ResourceMemory: resource.MustParse("200Mi"), - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - - generator := JobV1Beta1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*extensions.Job), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*extensions.Job)) - } - } -} - -func TestParseEnv(t *testing.T) { - tests := []struct { - envArray []string - expected []api.EnvVar - expectErr bool - test string - }{ - { - envArray: []string{ - "THIS_ENV=isOK", - "HAS_COMMAS=foo,bar", - "HAS_EQUALS=jJnro54iUu75xNy==", - }, - expected: []api.EnvVar{ - { - Name: "THIS_ENV", - Value: "isOK", - }, - { - Name: "HAS_COMMAS", - Value: "foo,bar", - }, - { - Name: "HAS_EQUALS", - Value: "jJnro54iUu75xNy==", - }, - }, - expectErr: false, - test: "test case 1", - }, - { - envArray: []string{ - "WITH_OUT_EQUALS", - }, - expected: []api.EnvVar{}, - expectErr: true, - test: "test case 2", - }, - { - envArray: []string{ - "WITH_OUT_VALUES=", - }, - expected: []api.EnvVar{}, - expectErr: true, - test: "test case 3", - }, - { - envArray: []string{ - "=WITH_OUT_NAME", - }, - expected: []api.EnvVar{}, - expectErr: true, - test: "test case 4", - }, - } - - for _, test := range tests { - envs, err := parseEnvs(test.envArray) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v (%s)", err, test.test) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(envs, test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v (%s)", test.expected, envs, test.test) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/scale.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/scale.go index 963f3050a..14951c028 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/scale.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/scale.go @@ -24,6 +24,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/extensions" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/util/wait" @@ -46,8 +47,8 @@ func ScalerFor(kind unversioned.GroupKind, c client.Interface) (Scaler, error) { return &ReplicationControllerScaler{c}, nil case extensions.Kind("ReplicaSet"): return &ReplicaSetScaler{c.Extensions()}, nil - case extensions.Kind("Job"): - return &JobScaler{c.Extensions()}, nil + case extensions.Kind("Job"), batch.Kind("Job"): + return &JobScaler{c.Extensions()}, nil // Either kind of job can be scaled with Extensions interface. case extensions.Kind("Deployment"): return &DeploymentScaler{c.Extensions()}, nil } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/scale_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/scale_test.go deleted file mode 100644 index 87b674355..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/scale_test.go +++ /dev/null @@ -1,728 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "errors" - "testing" - - "k8s.io/kubernetes/pkg/api" - kerrors "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/apis/extensions" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient" -) - -type ErrorReplicationControllers struct { - testclient.FakeReplicationControllers - invalid bool -} - -func (c *ErrorReplicationControllers) Update(controller *api.ReplicationController) (*api.ReplicationController, error) { - if c.invalid { - return nil, kerrors.NewInvalid(api.Kind(controller.Kind), controller.Name, nil) - } - return nil, errors.New("Replication controller update failure") -} - -type ErrorReplicationControllerClient struct { - testclient.Fake - invalid bool -} - -func (c *ErrorReplicationControllerClient) ReplicationControllers(namespace string) client.ReplicationControllerInterface { - return &ErrorReplicationControllers{testclient.FakeReplicationControllers{Fake: &c.Fake, Namespace: namespace}, c.invalid} -} - -func TestReplicationControllerScaleRetry(t *testing.T) { - fake := &ErrorReplicationControllerClient{Fake: testclient.Fake{}, invalid: false} - scaler := ReplicationControllerScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - namespace := "default" - - scaleFunc := ScaleCondition(&scaler, &preconditions, namespace, name, count) - pass, err := scaleFunc() - if pass { - t.Errorf("Expected an update failure to return pass = false, got pass = %v", pass) - } - if err != nil { - t.Errorf("Did not expect an error on update failure, got %v", err) - } - preconditions = ScalePrecondition{3, ""} - scaleFunc = ScaleCondition(&scaler, &preconditions, namespace, name, count) - pass, err = scaleFunc() - if err == nil { - t.Errorf("Expected error on precondition failure") - } -} - -func TestReplicationControllerScaleInvalid(t *testing.T) { - fake := &ErrorReplicationControllerClient{Fake: testclient.Fake{}, invalid: true} - scaler := ReplicationControllerScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - namespace := "default" - - scaleFunc := ScaleCondition(&scaler, &preconditions, namespace, name, count) - pass, err := scaleFunc() - if pass { - t.Errorf("Expected an update failure to return pass = false, got pass = %v", pass) - } - e, ok := err.(ScaleError) - if err == nil || !ok || e.FailureType != ScaleUpdateInvalidFailure { - t.Errorf("Expected error on invalid update failure, got %v", err) - } -} - -func TestReplicationControllerScale(t *testing.T) { - fake := &testclient.Fake{} - scaler := ReplicationControllerScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - scaler.Scale("default", name, count, &preconditions, nil, nil) - - actions := fake.Actions() - if len(actions) != 2 { - t.Errorf("unexpected actions: %v, expected 2 actions (get, update)", actions) - } - if action, ok := actions[0].(testclient.GetAction); !ok || action.GetResource() != "replicationcontrollers" || action.GetName() != name { - t.Errorf("unexpected action: %v, expected get-replicationController %s", actions[0], name) - } - if action, ok := actions[1].(testclient.UpdateAction); !ok || action.GetResource() != "replicationcontrollers" || action.GetObject().(*api.ReplicationController).Spec.Replicas != int(count) { - t.Errorf("unexpected action %v, expected update-replicationController with replicas = %d", actions[1], count) - } -} - -func TestReplicationControllerScaleFailsPreconditions(t *testing.T) { - fake := testclient.NewSimpleFake(&api.ReplicationController{ - Spec: api.ReplicationControllerSpec{ - Replicas: 10, - }, - }) - scaler := ReplicationControllerScaler{fake} - preconditions := ScalePrecondition{2, ""} - count := uint(3) - name := "foo" - scaler.Scale("default", name, count, &preconditions, nil, nil) - - actions := fake.Actions() - if len(actions) != 1 { - t.Errorf("unexpected actions: %v, expected 1 action (get)", actions) - } - if action, ok := actions[0].(testclient.GetAction); !ok || action.GetResource() != "replicationcontrollers" || action.GetName() != name { - t.Errorf("unexpected action: %v, expected get-replicationController %s", actions[0], name) - } -} - -func TestValidateReplicationController(t *testing.T) { - tests := []struct { - preconditions ScalePrecondition - controller api.ReplicationController - expectError bool - test string - }{ - { - preconditions: ScalePrecondition{-1, ""}, - expectError: false, - test: "defaults", - }, - { - preconditions: ScalePrecondition{-1, ""}, - controller: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 10, - }, - }, - expectError: false, - test: "defaults 2", - }, - { - preconditions: ScalePrecondition{0, ""}, - controller: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - }, - }, - expectError: false, - test: "size matches", - }, - { - preconditions: ScalePrecondition{-1, "foo"}, - controller: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 10, - }, - }, - expectError: false, - test: "resource version matches", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - controller: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 10, - }, - }, - expectError: false, - test: "both match", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - controller: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 20, - }, - }, - expectError: true, - test: "size different", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - controller: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "bar", - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 10, - }, - }, - expectError: true, - test: "version different", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - controller: api.ReplicationController{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "bar", - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 20, - }, - }, - expectError: true, - test: "both different", - }, - } - for _, test := range tests { - err := test.preconditions.ValidateReplicationController(&test.controller) - if err != nil && !test.expectError { - t.Errorf("unexpected error: %v (%s)", err, test.test) - } - if err == nil && test.expectError { - t.Errorf("unexpected non-error: %v (%s)", err, test.test) - } - } -} - -type ErrorJobs struct { - testclient.FakeJobs - invalid bool -} - -func (c *ErrorJobs) Update(job *extensions.Job) (*extensions.Job, error) { - if c.invalid { - return nil, kerrors.NewInvalid(extensions.Kind(job.Kind), job.Name, nil) - } - return nil, errors.New("Job update failure") -} - -func (c *ErrorJobs) Get(name string) (*extensions.Job, error) { - zero := 0 - return &extensions.Job{ - Spec: extensions.JobSpec{ - Parallelism: &zero, - }, - }, nil -} - -type ErrorJobClient struct { - testclient.FakeExperimental - invalid bool -} - -func (c *ErrorJobClient) Jobs(namespace string) client.JobInterface { - return &ErrorJobs{testclient.FakeJobs{Fake: &c.FakeExperimental, Namespace: namespace}, c.invalid} -} - -func TestJobScaleRetry(t *testing.T) { - fake := &ErrorJobClient{FakeExperimental: testclient.FakeExperimental{}, invalid: false} - scaler := JobScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - namespace := "default" - - scaleFunc := ScaleCondition(&scaler, &preconditions, namespace, name, count) - pass, err := scaleFunc() - if pass != false { - t.Errorf("Expected an update failure to return pass = false, got pass = %v", pass) - } - if err != nil { - t.Errorf("Did not expect an error on update failure, got %v", err) - } - preconditions = ScalePrecondition{3, ""} - scaleFunc = ScaleCondition(&scaler, &preconditions, namespace, name, count) - pass, err = scaleFunc() - if err == nil { - t.Errorf("Expected error on precondition failure") - } -} - -func TestJobScale(t *testing.T) { - fake := &testclient.FakeExperimental{Fake: &testclient.Fake{}} - scaler := JobScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - scaler.Scale("default", name, count, &preconditions, nil, nil) - - actions := fake.Actions() - if len(actions) != 2 { - t.Errorf("unexpected actions: %v, expected 2 actions (get, update)", actions) - } - if action, ok := actions[0].(testclient.GetAction); !ok || action.GetResource() != "jobs" || action.GetName() != name { - t.Errorf("unexpected action: %v, expected get-replicationController %s", actions[0], name) - } - if action, ok := actions[1].(testclient.UpdateAction); !ok || action.GetResource() != "jobs" || *action.GetObject().(*extensions.Job).Spec.Parallelism != int(count) { - t.Errorf("unexpected action %v, expected update-job with parallelism = %d", actions[1], count) - } -} - -func TestJobScaleInvalid(t *testing.T) { - fake := &ErrorJobClient{FakeExperimental: testclient.FakeExperimental{}, invalid: true} - scaler := JobScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - namespace := "default" - - scaleFunc := ScaleCondition(&scaler, &preconditions, namespace, name, count) - pass, err := scaleFunc() - if pass { - t.Errorf("Expected an update failure to return pass = false, got pass = %v", pass) - } - e, ok := err.(ScaleError) - if err == nil || !ok || e.FailureType != ScaleUpdateInvalidFailure { - t.Errorf("Expected error on invalid update failure, got %v", err) - } -} - -func TestJobScaleFailsPreconditions(t *testing.T) { - ten := 10 - fake := testclient.NewSimpleFake(&extensions.Job{ - Spec: extensions.JobSpec{ - Parallelism: &ten, - }, - }) - scaler := JobScaler{&testclient.FakeExperimental{fake}} - preconditions := ScalePrecondition{2, ""} - count := uint(3) - name := "foo" - scaler.Scale("default", name, count, &preconditions, nil, nil) - - actions := fake.Actions() - if len(actions) != 1 { - t.Errorf("unexpected actions: %v, expected 1 actions (get)", actions) - } - if action, ok := actions[0].(testclient.GetAction); !ok || action.GetResource() != "jobs" || action.GetName() != name { - t.Errorf("unexpected action: %v, expected get-job %s", actions[0], name) - } -} - -func TestValidateJob(t *testing.T) { - zero, ten, twenty := 0, 10, 20 - tests := []struct { - preconditions ScalePrecondition - job extensions.Job - expectError bool - test string - }{ - { - preconditions: ScalePrecondition{-1, ""}, - expectError: false, - test: "defaults", - }, - { - preconditions: ScalePrecondition{-1, ""}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.JobSpec{ - Parallelism: &ten, - }, - }, - expectError: false, - test: "defaults 2", - }, - { - preconditions: ScalePrecondition{0, ""}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.JobSpec{ - Parallelism: &zero, - }, - }, - expectError: false, - test: "size matches", - }, - { - preconditions: ScalePrecondition{-1, "foo"}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.JobSpec{ - Parallelism: &ten, - }, - }, - expectError: false, - test: "resource version matches", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.JobSpec{ - Parallelism: &ten, - }, - }, - expectError: false, - test: "both match", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.JobSpec{ - Parallelism: &twenty, - }, - }, - expectError: true, - test: "size different", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - }, - expectError: true, - test: "parallelism nil", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "bar", - }, - Spec: extensions.JobSpec{ - Parallelism: &ten, - }, - }, - expectError: true, - test: "version different", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - job: extensions.Job{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "bar", - }, - Spec: extensions.JobSpec{ - Parallelism: &twenty, - }, - }, - expectError: true, - test: "both different", - }, - } - for _, test := range tests { - err := test.preconditions.ValidateJob(&test.job) - if err != nil && !test.expectError { - t.Errorf("unexpected error: %v (%s)", err, test.test) - } - if err == nil && test.expectError { - t.Errorf("unexpected non-error: %v (%s)", err, test.test) - } - } -} - -type ErrorDeployments struct { - testclient.FakeDeployments - invalid bool -} - -func (c *ErrorDeployments) Update(deployment *extensions.Deployment) (*extensions.Deployment, error) { - if c.invalid { - return nil, kerrors.NewInvalid(extensions.Kind(deployment.Kind), deployment.Name, nil) - } - return nil, errors.New("deployment update failure") -} - -func (c *ErrorDeployments) Get(name string) (*extensions.Deployment, error) { - return &extensions.Deployment{ - Spec: extensions.DeploymentSpec{ - Replicas: 0, - }, - }, nil -} - -type ErrorDeploymentClient struct { - testclient.FakeExperimental - invalid bool -} - -func (c *ErrorDeploymentClient) Deployments(namespace string) client.DeploymentInterface { - return &ErrorDeployments{testclient.FakeDeployments{Fake: &c.FakeExperimental, Namespace: namespace}, c.invalid} -} - -func TestDeploymentScaleRetry(t *testing.T) { - fake := &ErrorDeploymentClient{FakeExperimental: testclient.FakeExperimental{Fake: &testclient.Fake{}}, invalid: false} - scaler := &DeploymentScaler{fake} - preconditions := &ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - namespace := "default" - - scaleFunc := ScaleCondition(scaler, preconditions, namespace, name, count) - pass, err := scaleFunc() - if pass != false { - t.Errorf("Expected an update failure to return pass = false, got pass = %v", pass) - } - if err != nil { - t.Errorf("Did not expect an error on update failure, got %v", err) - } - preconditions = &ScalePrecondition{3, ""} - scaleFunc = ScaleCondition(scaler, preconditions, namespace, name, count) - pass, err = scaleFunc() - if err == nil { - t.Errorf("Expected error on precondition failure") - } -} - -func TestDeploymentScale(t *testing.T) { - fake := &testclient.FakeExperimental{Fake: &testclient.Fake{}} - scaler := DeploymentScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - scaler.Scale("default", name, count, &preconditions, nil, nil) - - actions := fake.Actions() - if len(actions) != 2 { - t.Errorf("unexpected actions: %v, expected 2 actions (get, update)", actions) - } - if action, ok := actions[0].(testclient.GetAction); !ok || action.GetResource() != "deployments" || action.GetName() != name { - t.Errorf("unexpected action: %v, expected get-replicationController %s", actions[0], name) - } - if action, ok := actions[1].(testclient.UpdateAction); !ok || action.GetResource() != "deployments" || action.GetObject().(*extensions.Deployment).Spec.Replicas != int(count) { - t.Errorf("unexpected action %v, expected update-deployment with replicas = %d", actions[1], count) - } -} - -func TestDeploymentScaleInvalid(t *testing.T) { - fake := &ErrorDeploymentClient{FakeExperimental: testclient.FakeExperimental{Fake: &testclient.Fake{}}, invalid: true} - scaler := DeploymentScaler{fake} - preconditions := ScalePrecondition{-1, ""} - count := uint(3) - name := "foo" - namespace := "default" - - scaleFunc := ScaleCondition(&scaler, &preconditions, namespace, name, count) - pass, err := scaleFunc() - if pass { - t.Errorf("Expected an update failure to return pass = false, got pass = %v", pass) - } - e, ok := err.(ScaleError) - if err == nil || !ok || e.FailureType != ScaleUpdateInvalidFailure { - t.Errorf("Expected error on invalid update failure, got %v", err) - } -} - -func TestDeploymentScaleFailsPreconditions(t *testing.T) { - fake := testclient.NewSimpleFake(&extensions.Deployment{ - Spec: extensions.DeploymentSpec{ - Replicas: 10, - }, - }) - scaler := DeploymentScaler{&testclient.FakeExperimental{fake}} - preconditions := ScalePrecondition{2, ""} - count := uint(3) - name := "foo" - scaler.Scale("default", name, count, &preconditions, nil, nil) - - actions := fake.Actions() - if len(actions) != 1 { - t.Errorf("unexpected actions: %v, expected 1 actions (get)", actions) - } - if action, ok := actions[0].(testclient.GetAction); !ok || action.GetResource() != "deployments" || action.GetName() != name { - t.Errorf("unexpected action: %v, expected get-deployment %s", actions[0], name) - } -} - -func TestValidateDeployment(t *testing.T) { - zero, ten, twenty := 0, 10, 20 - tests := []struct { - preconditions ScalePrecondition - deployment extensions.Deployment - expectError bool - test string - }{ - { - preconditions: ScalePrecondition{-1, ""}, - expectError: false, - test: "defaults", - }, - { - preconditions: ScalePrecondition{-1, ""}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.DeploymentSpec{ - Replicas: ten, - }, - }, - expectError: false, - test: "defaults 2", - }, - { - preconditions: ScalePrecondition{0, ""}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.DeploymentSpec{ - Replicas: zero, - }, - }, - expectError: false, - test: "size matches", - }, - { - preconditions: ScalePrecondition{-1, "foo"}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.DeploymentSpec{ - Replicas: ten, - }, - }, - expectError: false, - test: "resource version matches", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.DeploymentSpec{ - Replicas: ten, - }, - }, - expectError: false, - test: "both match", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - Spec: extensions.DeploymentSpec{ - Replicas: twenty, - }, - }, - expectError: true, - test: "size different", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "foo", - }, - }, - expectError: true, - test: "no replicas", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "bar", - }, - Spec: extensions.DeploymentSpec{ - Replicas: ten, - }, - }, - expectError: true, - test: "version different", - }, - { - preconditions: ScalePrecondition{10, "foo"}, - deployment: extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - ResourceVersion: "bar", - }, - Spec: extensions.DeploymentSpec{ - Replicas: twenty, - }, - }, - expectError: true, - test: "both different", - }, - } - for _, test := range tests { - err := test.preconditions.ValidateDeployment(&test.deployment) - if err != nil && !test.expectError { - t.Errorf("unexpected error: %v (%s)", err, test.test) - } - if err == nil && test.expectError { - t.Errorf("unexpected non-error: %v (%s)", err, test.test) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/secret_for_docker_registry_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/secret_for_docker_registry_test.go deleted file mode 100644 index 65d8d397d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/secret_for_docker_registry_test.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -func TestSecretForDockerRegistryGenerate(t *testing.T) { - username, password, email, server := "test-user", "test-password", "test-user@example.org", "https://index.docker.io/v1/" - secretData, err := handleDockercfgContent(username, password, email, server) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - tests := map[string]struct { - params map[string]interface{} - expected *api.Secret - expectErr bool - }{ - "test-valid-use": { - params: map[string]interface{}{ - "name": "foo", - "docker-server": server, - "docker-username": username, - "docker-password": password, - "docker-email": email, - }, - expected: &api.Secret{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Data: map[string][]byte{ - api.DockerConfigKey: secretData, - }, - Type: api.SecretTypeDockercfg, - }, - expectErr: false, - }, - "test-missing-required-param": { - params: map[string]interface{}{ - "name": "foo", - "docker-server": server, - "docker-password": password, - "docker-email": email, - }, - expectErr: true, - }, - } - - generator := SecretForDockerRegistryGeneratorV1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*api.Secret), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*api.Secret)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/secret_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/secret_test.go deleted file mode 100644 index e713c9911..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/secret_test.go +++ /dev/null @@ -1,109 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" -) - -func TestSecretGenerate(t *testing.T) { - tests := []struct { - params map[string]interface{} - expected *api.Secret - expectErr bool - }{ - { - params: map[string]interface{}{ - "name": "foo", - }, - expected: &api.Secret{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Data: map[string][]byte{}, - }, - expectErr: false, - }, - { - params: map[string]interface{}{ - "name": "foo", - "type": "my-type", - }, - expected: &api.Secret{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Data: map[string][]byte{}, - Type: "my-type", - }, - expectErr: false, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-literal": []string{"key1=value1", "key2=value2"}, - }, - expected: &api.Secret{ - ObjectMeta: api.ObjectMeta{ - Name: "foo", - }, - Data: map[string][]byte{ - "key1": []byte("value1"), - "key2": []byte("value2"), - }, - }, - expectErr: false, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-literal": []string{"key1value1"}, - }, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-file": []string{"key1=/file=2"}, - }, - expectErr: true, - }, - { - params: map[string]interface{}{ - "name": "foo", - "from-file": []string{"key1==value"}, - }, - expectErr: true, - }, - } - generator := SecretGeneratorV1{} - for _, test := range tests { - obj, err := generator.Generate(test.params) - if !test.expectErr && err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectErr && err != nil { - continue - } - if !reflect.DeepEqual(obj.(*api.Secret), test.expected) { - t.Errorf("\nexpected:\n%#v\nsaw:\n%#v", test.expected, obj.(*api.Secret)) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/service_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/service_test.go deleted file mode 100644 index 80144239e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/service_test.go +++ /dev/null @@ -1,417 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/util/intstr" -) - -func TestGenerateService(t *testing.T) { - tests := []struct { - generator Generator - params map[string]interface{} - expected api.Service - }{ - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "TCP", - "container-port": "1234", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - TargetPort: intstr.FromInt(1234), - }, - }, - }, - }, - }, - { - - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "UDP", - "container-port": "foobar", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "UDP", - TargetPort: intstr.FromString("foobar"), - }, - }, - }, - }, - }, - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "labels": "key1=value1,key2=value2", - "name": "test", - "port": "80", - "protocol": "TCP", - "container-port": "1234", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - Labels: map[string]string{ - "key1": "value1", - "key2": "value2", - }, - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "TCP", - TargetPort: intstr.FromInt(1234), - }, - }, - }, - }, - }, - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "UDP", - "container-port": "foobar", - "external-ip": "1.2.3.4", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "UDP", - TargetPort: intstr.FromString("foobar"), - }, - }, - ExternalIPs: []string{"1.2.3.4"}, - }, - }, - }, - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "UDP", - "container-port": "foobar", - "external-ip": "1.2.3.4", - "create-external-load-balancer": "true", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "UDP", - TargetPort: intstr.FromString("foobar"), - }, - }, - Type: api.ServiceTypeLoadBalancer, - ExternalIPs: []string{"1.2.3.4"}, - }, - }, - }, - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "UDP", - "container-port": "foobar", - "type": string(api.ServiceTypeNodePort), - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "UDP", - TargetPort: intstr.FromString("foobar"), - }, - }, - Type: api.ServiceTypeNodePort, - }, - }, - }, - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "UDP", - "container-port": "foobar", - "create-external-load-balancer": "true", // ignored when type is present - "type": string(api.ServiceTypeNodePort), - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Port: 80, - Protocol: "UDP", - TargetPort: intstr.FromString("foobar"), - }, - }, - Type: api.ServiceTypeNodePort, - }, - }, - }, - { - generator: ServiceGeneratorV1{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "TCP", - "container-port": "1234", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Name: "default", - Port: 80, - Protocol: "TCP", - TargetPort: intstr.FromInt(1234), - }, - }, - }, - }, - }, - { - generator: ServiceGeneratorV1{}, - params: map[string]interface{}{ - "selector": "foo=bar,baz=blah", - "name": "test", - "port": "80", - "protocol": "TCP", - "container-port": "1234", - "session-affinity": "ClientIP", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - "baz": "blah", - }, - Ports: []api.ServicePort{ - { - Name: "default", - Port: 80, - Protocol: "TCP", - TargetPort: intstr.FromInt(1234), - }, - }, - SessionAffinity: api.ServiceAffinityClientIP, - }, - }, - }, - { - generator: ServiceGeneratorV1{}, - params: map[string]interface{}{ - "selector": "foo=bar", - "name": "test", - "ports": "80,443", - "protocol": "TCP", - "container-port": "foobar", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - }, - Ports: []api.ServicePort{ - { - Name: "port-1", - Port: 80, - Protocol: api.ProtocolTCP, - TargetPort: intstr.FromString("foobar"), - }, - { - Name: "port-2", - Port: 443, - Protocol: api.ProtocolTCP, - TargetPort: intstr.FromString("foobar"), - }, - }, - }, - }, - }, - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar", - "name": "test", - "ports": "80,443", - "protocol": "UDP", - "target-port": "1234", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - }, - Ports: []api.ServicePort{ - { - Name: "port-1", - Port: 80, - Protocol: api.ProtocolUDP, - TargetPort: intstr.FromInt(1234), - }, - { - Name: "port-2", - Port: 443, - Protocol: api.ProtocolUDP, - TargetPort: intstr.FromInt(1234), - }, - }, - }, - }, - }, - { - generator: ServiceGeneratorV2{}, - params: map[string]interface{}{ - "selector": "foo=bar", - "name": "test", - "ports": "80,443", - "protocol": "TCP", - }, - expected: api.Service{ - ObjectMeta: api.ObjectMeta{ - Name: "test", - }, - Spec: api.ServiceSpec{ - Selector: map[string]string{ - "foo": "bar", - }, - Ports: []api.ServicePort{ - { - Name: "port-1", - Port: 80, - Protocol: api.ProtocolTCP, - TargetPort: intstr.FromInt(80), - }, - { - Name: "port-2", - Port: 443, - Protocol: api.ProtocolTCP, - TargetPort: intstr.FromInt(443), - }, - }, - }, - }, - }, - } - for _, test := range tests { - obj, err := test.generator.Generate(test.params) - if !reflect.DeepEqual(obj, &test.expected) { - t.Errorf("expected:\n%#v\ngot\n%#v\n", &test.expected, obj) - } - if err != nil { - t.Errorf("unexpected error: %v", err) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/serviceaccount.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/serviceaccount.go new file mode 100644 index 000000000..2be08dd2d --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/serviceaccount.go @@ -0,0 +1,51 @@ +/* +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. +*/ + +package kubectl + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/runtime" +) + +// ServiceAccountGeneratorV1 supports stable generation of a service account +type ServiceAccountGeneratorV1 struct { + // Name of service account + Name string +} + +// Ensure it supports the generator pattern that uses parameters specified during construction +var _ StructuredGenerator = &ServiceAccountGeneratorV1{} + +// StructuredGenerate outputs a service account object using the configured fields +func (g *ServiceAccountGeneratorV1) StructuredGenerate() (runtime.Object, error) { + if err := g.validate(); err != nil { + return nil, err + } + serviceAccount := &api.ServiceAccount{} + serviceAccount.Name = g.Name + return serviceAccount, nil +} + +// validate validates required fields are set to support structured generation +func (g *ServiceAccountGeneratorV1) validate() error { + if len(g.Name) == 0 { + return fmt.Errorf("name must be specified") + } + return nil +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorted_event_list_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorted_event_list_test.go deleted file mode 100644 index 471069ed2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorted_event_list_test.go +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "sort" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" -) - -// VerifyDatesInOrder checks the start of each line for a RFC1123Z date -// and posts error if all subsequent dates are not equal or increasing -func VerifyDatesInOrder( - resultToTest, rowDelimiter, columnDelimiter string, t *testing.T) { - lines := strings.Split(resultToTest, rowDelimiter) - var previousTime time.Time - for _, str := range lines { - columns := strings.Split(str, columnDelimiter) - if len(columns) > 0 { - currentTime, err := time.Parse(time.RFC1123Z, columns[0]) - if err == nil { - if previousTime.After(currentTime) { - t.Errorf( - "Output is not sorted by time. %s should be listed after %s. Complete output: %s", - previousTime.Format(time.RFC1123Z), - currentTime.Format(time.RFC1123Z), - resultToTest) - } - previousTime = currentTime - } - } - } - -} - -func TestSortableEvents(t *testing.T) { - // Arrange - list := SortableEvents([]api.Event{ - { - Source: api.EventSource{Component: "kubelet"}, - Message: "Item 1", - FirstTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(2014, time.January, 15, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - { - Source: api.EventSource{Component: "scheduler"}, - Message: "Item 2", - FirstTimestamp: unversioned.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(1987, time.June, 17, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - { - Source: api.EventSource{Component: "kubelet"}, - Message: "Item 3", - FirstTimestamp: unversioned.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)), - LastTimestamp: unversioned.NewTime(time.Date(2002, time.December, 25, 0, 0, 0, 0, time.UTC)), - Count: 1, - Type: api.EventTypeNormal, - }, - }) - - // Act - sort.Sort(list) - - // Assert - if list[0].Message != "Item 2" || - list[1].Message != "Item 3" || - list[2].Message != "Item 1" { - t.Fatal("List is not sorted by time. List: ", list) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorted_resource_name_list.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorted_resource_name_list.go index 6df122eac..ffaa08ee4 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorted_resource_name_list.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorted_resource_name_list.go @@ -33,3 +33,17 @@ func (list SortableResourceNames) Swap(i, j int) { func (list SortableResourceNames) Less(i, j int) bool { return list[i] < list[j] } + +type SortableResourceQuotas []api.ResourceQuota + +func (list SortableResourceQuotas) Len() int { + return len(list) +} + +func (list SortableResourceQuotas) Swap(i, j int) { + list[i], list[j] = list[j], list[i] +} + +func (list SortableResourceQuotas) Less(i, j int) bool { + return list[i].Name < list[j].Name +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorting_printer_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorting_printer_test.go deleted file mode 100644 index f1d1d0c65..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/sorting_printer_test.go +++ /dev/null @@ -1,236 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "reflect" - "testing" - - internal "k8s.io/kubernetes/pkg/api" - api "k8s.io/kubernetes/pkg/api/v1" - "k8s.io/kubernetes/pkg/runtime" -) - -func encodeOrDie(obj runtime.Object) []byte { - data, err := runtime.Encode(internal.Codecs.LegacyCodec(api.SchemeGroupVersion), obj) - if err != nil { - panic(err.Error()) - } - return data -} - -func TestSortingPrinter(t *testing.T) { - intPtr := func(val int32) *int32 { return &val } - - a := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "a", - }, - } - - b := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "b", - }, - } - - c := &api.Pod{ - ObjectMeta: api.ObjectMeta{ - Name: "c", - }, - } - - tests := []struct { - obj runtime.Object - sort runtime.Object - field string - name string - }{ - { - name: "in-order-already", - obj: &api.PodList{ - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{ - Name: "a", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "b", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "c", - }, - }, - }, - }, - sort: &api.PodList{ - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{ - Name: "a", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "b", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "c", - }, - }, - }, - }, - field: "{.metadata.name}", - }, - { - name: "reverse-order", - obj: &api.PodList{ - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{ - Name: "b", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "c", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "a", - }, - }, - }, - }, - sort: &api.PodList{ - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{ - Name: "a", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "b", - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "c", - }, - }, - }, - }, - field: "{.metadata.name}", - }, - { - name: "random-order-numbers", - obj: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ - { - Spec: api.ReplicationControllerSpec{ - Replicas: intPtr(5), - }, - }, - { - Spec: api.ReplicationControllerSpec{ - Replicas: intPtr(1), - }, - }, - { - Spec: api.ReplicationControllerSpec{ - Replicas: intPtr(9), - }, - }, - }, - }, - sort: &api.ReplicationControllerList{ - Items: []api.ReplicationController{ - { - Spec: api.ReplicationControllerSpec{ - Replicas: intPtr(1), - }, - }, - { - Spec: api.ReplicationControllerSpec{ - Replicas: intPtr(5), - }, - }, - { - Spec: api.ReplicationControllerSpec{ - Replicas: intPtr(9), - }, - }, - }, - }, - field: "{.spec.replicas}", - }, - { - name: "v1.List in order", - obj: &api.List{ - Items: []runtime.RawExtension{ - {RawJSON: encodeOrDie(a)}, - {RawJSON: encodeOrDie(b)}, - {RawJSON: encodeOrDie(c)}, - }, - }, - sort: &api.List{ - Items: []runtime.RawExtension{ - {RawJSON: encodeOrDie(a)}, - {RawJSON: encodeOrDie(b)}, - {RawJSON: encodeOrDie(c)}, - }, - }, - field: "{.metadata.name}", - }, - { - name: "v1.List in reverse", - obj: &api.List{ - Items: []runtime.RawExtension{ - {RawJSON: encodeOrDie(c)}, - {RawJSON: encodeOrDie(b)}, - {RawJSON: encodeOrDie(a)}, - }, - }, - sort: &api.List{ - Items: []runtime.RawExtension{ - {RawJSON: encodeOrDie(a)}, - {RawJSON: encodeOrDie(b)}, - {RawJSON: encodeOrDie(c)}, - }, - }, - field: "{.metadata.name}", - }, - } - for _, test := range tests { - sort := &SortingPrinter{SortField: test.field, Decoder: internal.Codecs.UniversalDecoder()} - if err := sort.sortObj(test.obj); err != nil { - t.Errorf("unexpected error: %v (%s)", err, test.name) - continue - } - if !reflect.DeepEqual(test.obj, test.sort) { - t.Errorf("[%s]\nexpected:\n%v\nsaw:\n%v", test.name, test.sort, test.obj) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/stop.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/stop.go index 0f03d45ab..9112decf7 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/stop.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/stop.go @@ -25,10 +25,12 @@ import ( "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/extensions" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util" + deploymentutil "k8s.io/kubernetes/pkg/util/deployment" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/wait" ) @@ -40,7 +42,8 @@ const ( // A Reaper handles terminating an object as gracefully as possible. // timeout is how long we'll wait for the termination to be successful -// gracePeriod is time given to an API object for it to delete itself cleanly (e.g. pod shutdown) +// gracePeriod is time given to an API object for it to delete itself cleanly, +// e.g., pod shutdown. It may or may not be supported by the API object. type Reaper interface { Stop(namespace, name string, timeout time.Duration, gracePeriod *api.DeleteOptions) error } @@ -75,7 +78,7 @@ func ReaperFor(kind unversioned.GroupKind, c client.Interface) (Reaper, error) { case api.Kind("Service"): return &ServiceReaper{c}, nil - case extensions.Kind("Job"): + case extensions.Kind("Job"), batch.Kind("Job"): return &JobReaper{c, Interval, Timeout}, nil case extensions.Kind("Deployment"): @@ -270,7 +273,7 @@ func (reaper *ReplicaSetReaper) Stop(namespace, name string, timeout time.Durati } } - if err := rsc.Delete(name, gracePeriod); err != nil { + if err := rsc.Delete(name, nil); err != nil { return err } return nil @@ -353,7 +356,7 @@ func (reaper *JobReaper) Stop(namespace, name string, timeout time.Duration, gra return utilerrors.NewAggregate(errList) } // once we have all the pods removed we can safely remove the job itself - return jobs.Delete(name, gracePeriod) + return jobs.Delete(name, nil) } func (reaper *DeploymentReaper) Stop(namespace, name string, timeout time.Duration, gracePeriod *api.DeleteOptions) error { @@ -364,55 +367,27 @@ func (reaper *DeploymentReaper) Stop(namespace, name string, timeout time.Durati deployment, err := reaper.updateDeploymentWithRetries(namespace, name, func(d *extensions.Deployment) { // set deployment's history and scale to 0 // TODO replace with patch when available: https://github.com/kubernetes/kubernetes/issues/20527 - zero := 0 - d.Spec.RevisionHistoryLimit = &zero + d.Spec.RevisionHistoryLimit = util.IntPtr(0) d.Spec.Replicas = 0 - // TODO: un-pausing should not be necessary, remove when this is fixed: - // https://github.com/kubernetes/kubernetes/issues/20966 - // Instead deployment should be Paused at this point and not at next TODO. - d.Spec.Paused = false - }) - if err != nil { - return err - } - - // wait for total no of pods drop to 0 - if err := wait.Poll(reaper.pollInterval, reaper.timeout, func() (bool, error) { - curr, err := deployments.Get(name) - // if deployment was not found it must have been deleted, error out - if err != nil && errors.IsNotFound(err) { - return false, err - } - // if other errors happen, retry - if err != nil { - return false, nil - } - // check if deployment wasn't recreated with the same name - // TODO use generations when deployment will have them - if curr.UID != deployment.UID { - return false, errors.NewNotFound(extensions.Resource("Deployment"), name) - } - return curr.Status.Replicas == 0, nil - }); err != nil { - return err - } - - // TODO: When deployments will allow running cleanup policy while being - // paused, move pausing to above update operation. Without it, we need to - // pause deployment before stopping RSs, to prevent creating new RSs. - // See https://github.com/kubernetes/kubernetes/issues/20966 - deployment, err = reaper.updateDeploymentWithRetries(namespace, name, func(d *extensions.Deployment) { d.Spec.Paused = true }) if err != nil { return err } - // remove remaining RSs + // Use observedGeneration to determine if the deployment controller noticed the pause. + if err := deploymentutil.WaitForObservedDeployment(func() (*extensions.Deployment, error) { + return deployments.Get(name) + }, deployment.Generation, 10*time.Millisecond, 1*time.Minute); err != nil { + return err + } + + // Stop all replica sets. selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { return err } + options := api.ListOptions{LabelSelector: selector} rsList, err := replicaSets.List(options) if err != nil { @@ -430,8 +405,9 @@ func (reaper *DeploymentReaper) Stop(namespace, name string, timeout time.Durati return utilerrors.NewAggregate(errList) } - // and finally deployment - return deployments.Delete(name, gracePeriod) + // Delete deployment at the end. + // Note: We delete deployment at the end so that if removing RSs fails, we atleast have the deployment to retry. + return deployments.Delete(name, nil) } type updateDeploymentFunc func(d *extensions.Deployment) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/stop_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/stop_test.go deleted file mode 100644 index 32a5f52d0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/stop_test.go +++ /dev/null @@ -1,718 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package kubectl - -import ( - "fmt" - "reflect" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - client "k8s.io/kubernetes/pkg/client/unversioned" - "k8s.io/kubernetes/pkg/client/unversioned/testclient" - "k8s.io/kubernetes/pkg/runtime" - deploymentutil "k8s.io/kubernetes/pkg/util/deployment" -) - -func TestReplicationControllerStop(t *testing.T) { - name := "foo" - ns := "default" - tests := []struct { - Name string - Objs []runtime.Object - StopError error - ExpectedActions []string - }{ - { - Name: "OnlyOneRC", - Objs: []runtime.Object{ - &api.ReplicationController{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - &api.ReplicationControllerList{ // LIST - Items: []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get", "list", "get", "update", "get", "get", "delete"}, - }, - { - Name: "NoOverlapping", - Objs: []runtime.Object{ - &api.ReplicationController{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - &api.ReplicationControllerList{ // LIST - Items: []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{ - Name: "baz", - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k3": "v3"}}, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get", "list", "get", "update", "get", "get", "delete"}, - }, - { - Name: "OverlappingError", - Objs: []runtime.Object{ - - &api.ReplicationController{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - &api.ReplicationControllerList{ // LIST - Items: []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{ - Name: "baz", - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1", "k2": "v2"}}, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - }, - }, - }, - StopError: fmt.Errorf("Detected overlapping controllers for rc foo: baz, please manage deletion individually with --cascade=false."), - ExpectedActions: []string{"get", "list"}, - }, - - { - Name: "OverlappingButSafeDelete", - Objs: []runtime.Object{ - - &api.ReplicationController{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1", "k2": "v2"}}, - }, - &api.ReplicationControllerList{ // LIST - Items: []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{ - Name: "baz", - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1", "k2": "v2", "k3": "v3"}}, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: "zaz", - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1", "k2": "v2"}}, - }, - }, - }, - }, - - StopError: fmt.Errorf("Detected overlapping controllers for rc foo: baz,zaz, please manage deletion individually with --cascade=false."), - ExpectedActions: []string{"get", "list"}, - }, - - { - Name: "TwoExactMatchRCs", - Objs: []runtime.Object{ - - &api.ReplicationController{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - &api.ReplicationControllerList{ // LIST - Items: []api.ReplicationController{ - { - ObjectMeta: api.ObjectMeta{ - Name: "zaz", - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: api.ReplicationControllerSpec{ - Replicas: 0, - Selector: map[string]string{"k1": "v1"}}, - }, - }, - }, - }, - - StopError: nil, - ExpectedActions: []string{"get", "list", "delete"}, - }, - } - - for _, test := range tests { - fake := testclient.NewSimpleFake(test.Objs...) - reaper := ReplicationControllerReaper{fake, time.Millisecond, time.Millisecond} - err := reaper.Stop(ns, name, 0, nil) - if !reflect.DeepEqual(err, test.StopError) { - t.Errorf("%s unexpected error: %v", test.Name, err) - continue - } - - actions := fake.Actions() - if len(actions) != len(test.ExpectedActions) { - t.Errorf("%s unexpected actions: %v, expected %d actions got %d", test.Name, actions, len(test.ExpectedActions), len(actions)) - continue - } - for i, verb := range test.ExpectedActions { - if actions[i].GetResource() != "replicationcontrollers" { - t.Errorf("%s unexpected action: %+v, expected %s-replicationController", test.Name, actions[i], verb) - } - if actions[i].GetVerb() != verb { - t.Errorf("%s unexpected action: %+v, expected %s-replicationController", test.Name, actions[i], verb) - } - } - } -} - -func TestReplicaSetStop(t *testing.T) { - name := "foo" - ns := "default" - tests := []struct { - Name string - Objs []runtime.Object - StopError error - ExpectedActions []string - }{ - { - Name: "OnlyOneRS", - Objs: []runtime.Object{ - &extensions.ReplicaSet{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 0, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"k1": "v1"}}, - }, - }, - &extensions.ReplicaSetList{ // LIST - Items: []extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 0, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"k1": "v1"}}, - }, - }, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get", "get", "update", "get", "get", "delete"}, - }, - { - Name: "NoOverlapping", - Objs: []runtime.Object{ - &extensions.ReplicaSet{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 0, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"k1": "v1"}}, - }, - }, - &extensions.ReplicaSetList{ // LIST - Items: []extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{ - Name: "baz", - Namespace: ns, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 0, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"k3": "v3"}}, - }, - }, - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 0, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"k1": "v1"}}, - }, - }, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get", "get", "update", "get", "get", "delete"}, - }, - // TODO: Implement tests for overlapping replica sets, similar to replication controllers, - // when the overlapping checks are implemented for replica sets. - } - - for _, test := range tests { - fake := testclient.NewSimpleFake(test.Objs...) - reaper := ReplicaSetReaper{fake, time.Millisecond, time.Millisecond} - err := reaper.Stop(ns, name, 0, nil) - if !reflect.DeepEqual(err, test.StopError) { - t.Errorf("%s unexpected error: %v", test.Name, err) - continue - } - - actions := fake.Actions() - if len(actions) != len(test.ExpectedActions) { - t.Errorf("%s unexpected actions: %v, expected %d actions got %d", test.Name, actions, len(test.ExpectedActions), len(actions)) - continue - } - for i, verb := range test.ExpectedActions { - if actions[i].GetResource() != "replicasets" { - t.Errorf("%s unexpected action: %+v, expected %s-replicaSet", test.Name, actions[i], verb) - } - if actions[i].GetVerb() != verb { - t.Errorf("%s unexpected action: %+v, expected %s-replicaSet", test.Name, actions[i], verb) - } - } - } -} - -func TestJobStop(t *testing.T) { - name := "foo" - ns := "default" - zero := 0 - tests := []struct { - Name string - Objs []runtime.Object - StopError error - ExpectedActions []string - }{ - { - Name: "OnlyOneJob", - Objs: []runtime.Object{ - &extensions.Job{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.JobSpec{ - Parallelism: &zero, - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"k1": "v1"}, - }, - }, - }, - &extensions.JobList{ // LIST - Items: []extensions.Job{ - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.JobSpec{ - Parallelism: &zero, - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"k1": "v1"}, - }, - }, - }, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get:jobs", "get:jobs", "update:jobs", - "get:jobs", "get:jobs", "list:pods", "delete:jobs"}, - }, - { - Name: "JobWithDeadPods", - Objs: []runtime.Object{ - &extensions.Job{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.JobSpec{ - Parallelism: &zero, - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"k1": "v1"}, - }, - }, - }, - &extensions.JobList{ // LIST - Items: []extensions.Job{ - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.JobSpec{ - Parallelism: &zero, - Selector: &unversioned.LabelSelector{ - MatchLabels: map[string]string{"k1": "v1"}, - }, - }, - }, - }, - }, - &api.PodList{ // LIST - Items: []api.Pod{ - { - ObjectMeta: api.ObjectMeta{ - Name: "pod1", - Namespace: ns, - Labels: map[string]string{"k1": "v1"}, - }, - }, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get:jobs", "get:jobs", "update:jobs", - "get:jobs", "get:jobs", "list:pods", "delete:pods", "delete:jobs"}, - }, - } - - for _, test := range tests { - fake := testclient.NewSimpleFake(test.Objs...) - reaper := JobReaper{fake, time.Millisecond, time.Millisecond} - err := reaper.Stop(ns, name, 0, nil) - if !reflect.DeepEqual(err, test.StopError) { - t.Errorf("%s unexpected error: %v", test.Name, err) - continue - } - - actions := fake.Actions() - if len(actions) != len(test.ExpectedActions) { - t.Errorf("%s unexpected actions: %v, expected %d actions got %d", test.Name, actions, len(test.ExpectedActions), len(actions)) - continue - } - for i, expAction := range test.ExpectedActions { - action := strings.Split(expAction, ":") - if actions[i].GetVerb() != action[0] { - t.Errorf("%s unexpected verb: %+v, expected %s", test.Name, actions[i], expAction) - } - if actions[i].GetResource() != action[1] { - t.Errorf("%s unexpected resource: %+v, expected %s", test.Name, actions[i], expAction) - } - } - } -} - -func TestDeploymentStop(t *testing.T) { - name := "foo" - ns := "default" - deployment := extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.DeploymentSpec{ - Replicas: 0, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"k1": "v1"}}, - }, - Status: extensions.DeploymentStatus{ - Replicas: 0, - }, - } - template := deploymentutil.GetNewReplicaSetTemplate(deployment) - tests := []struct { - Name string - Objs []runtime.Object - StopError error - ExpectedActions []string - }{ - { - Name: "SimpleDeployment", - Objs: []runtime.Object{ - &extensions.Deployment{ // GET - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.DeploymentSpec{ - Replicas: 0, - Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"k1": "v1"}}, - }, - Status: extensions.DeploymentStatus{ - Replicas: 0, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get:deployments", "update:deployments", - "get:deployments", "get:deployments", "update:deployments", - "list:replicasets", "delete:deployments"}, - }, - { - Name: "Deployment with single replicaset", - Objs: []runtime.Object{ - &deployment, // GET - &extensions.ReplicaSetList{ // LIST - Items: []extensions.ReplicaSet{ - { - ObjectMeta: api.ObjectMeta{ - Name: name, - Namespace: ns, - }, - Spec: extensions.ReplicaSetSpec{ - Template: &template, - }, - }, - }, - }, - }, - StopError: nil, - ExpectedActions: []string{"get:deployments", "update:deployments", - "get:deployments", "get:deployments", "update:deployments", - "list:replicasets", "get:replicasets", "get:replicasets", - "update:replicasets", "get:replicasets", "get:replicasets", - "delete:replicasets", "delete:deployments"}, - }, - } - - for _, test := range tests { - fake := testclient.NewSimpleFake(test.Objs...) - reaper := DeploymentReaper{fake, time.Millisecond, time.Millisecond} - err := reaper.Stop(ns, name, 0, nil) - if !reflect.DeepEqual(err, test.StopError) { - t.Errorf("%s unexpected error: %v", test.Name, err) - continue - } - - actions := fake.Actions() - if len(actions) != len(test.ExpectedActions) { - t.Errorf("%s unexpected actions: %v, expected %d actions got %d", test.Name, actions, len(test.ExpectedActions), len(actions)) - continue - } - for i, expAction := range test.ExpectedActions { - action := strings.Split(expAction, ":") - if actions[i].GetVerb() != action[0] { - t.Errorf("%s unexpected verb: %+v, expected %s", test.Name, actions[i], expAction) - } - if actions[i].GetResource() != action[1] { - t.Errorf("%s unexpected resource: %+v, expected %s", test.Name, actions[i], expAction) - } - if len(action) == 3 && actions[i].GetSubresource() != action[2] { - t.Errorf("%s unexpected subresource: %+v, expected %s", test.Name, actions[i], expAction) - } - } - } -} - -type noSuchPod struct { - *testclient.FakePods -} - -func (c *noSuchPod) Get(name string) (*api.Pod, error) { - return nil, fmt.Errorf("%s does not exist", name) -} - -type noDeleteService struct { - *testclient.FakeServices -} - -func (c *noDeleteService) Delete(service string) error { - return fmt.Errorf("I'm afraid I can't do that, Dave") -} - -type reaperFake struct { - *testclient.Fake - noSuchPod, noDeleteService bool -} - -func (c *reaperFake) Pods(namespace string) client.PodInterface { - pods := &testclient.FakePods{Fake: c.Fake, Namespace: namespace} - if c.noSuchPod { - return &noSuchPod{pods} - } - return pods -} - -func (c *reaperFake) Services(namespace string) client.ServiceInterface { - services := &testclient.FakeServices{Fake: c.Fake, Namespace: namespace} - if c.noDeleteService { - return &noDeleteService{services} - } - return services -} - -func TestSimpleStop(t *testing.T) { - tests := []struct { - fake *reaperFake - kind unversioned.GroupKind - actions []testclient.Action - expectError bool - test string - }{ - { - fake: &reaperFake{ - Fake: &testclient.Fake{}, - }, - kind: api.Kind("Pod"), - actions: []testclient.Action{ - testclient.NewGetAction("pods", api.NamespaceDefault, "foo"), - testclient.NewDeleteAction("pods", api.NamespaceDefault, "foo"), - }, - expectError: false, - test: "stop pod succeeds", - }, - { - fake: &reaperFake{ - Fake: &testclient.Fake{}, - }, - kind: api.Kind("Service"), - actions: []testclient.Action{ - testclient.NewGetAction("services", api.NamespaceDefault, "foo"), - testclient.NewDeleteAction("services", api.NamespaceDefault, "foo"), - }, - expectError: false, - test: "stop service succeeds", - }, - { - fake: &reaperFake{ - Fake: &testclient.Fake{}, - noSuchPod: true, - }, - kind: api.Kind("Pod"), - actions: []testclient.Action{}, - expectError: true, - test: "stop pod fails, no pod", - }, - { - fake: &reaperFake{ - Fake: &testclient.Fake{}, - noDeleteService: true, - }, - kind: api.Kind("Service"), - actions: []testclient.Action{ - testclient.NewGetAction("services", api.NamespaceDefault, "foo"), - }, - expectError: true, - test: "stop service fails, can't delete", - }, - } - for _, test := range tests { - fake := test.fake - reaper, err := ReaperFor(test.kind, fake) - if err != nil { - t.Errorf("unexpected error: %v (%s)", err, test.test) - } - err = reaper.Stop("default", "foo", 0, nil) - if err != nil && !test.expectError { - t.Errorf("unexpected error: %v (%s)", err, test.test) - } - if err == nil { - if test.expectError { - t.Errorf("unexpected non-error: %v (%s)", err, test.test) - } - } - actions := fake.Actions() - if len(test.actions) != len(actions) { - t.Errorf("unexpected actions: %v; expected %v (%s)", fake.Actions, test.actions, test.test) - } - for i, action := range actions { - testAction := test.actions[i] - if action != testAction { - t.Errorf("unexpected action: %#v; expected %v (%s)", action, testAction, test.test) - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/testing/types.generated.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/testing/types.generated.go deleted file mode 100644 index b3dd3628d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/testing/types.generated.go +++ /dev/null @@ -1,555 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// ************************************************************ -// DO NOT EDIT. -// THIS FILE IS AUTO-GENERATED BY codecgen. -// ************************************************************ - -package testing - -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 *TestStruct) 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 [7]bool - _, _, _ = yysep2, yyq2, yy2arr2 - const yyr2 bool = false - yyq2[0] = true - yyq2[5] = x.Kind != "" - yyq2[6] = x.APIVersion != "" - var yynn2 int - if yyr2 || yy2arr2 { - r.EncodeArrayStart(7) - } else { - yynn2 = 4 - 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.Key)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("Key")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym10 := z.EncBinary() - _ = yym10 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.Key)) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if x.Map == nil { - r.EncodeNil() - } else { - yym12 := z.EncBinary() - _ = yym12 - if false { - } else { - z.F.EncMapStringIntV(x.Map, false, e) - } - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("Map")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - if x.Map == nil { - r.EncodeNil() - } else { - yym13 := z.EncBinary() - _ = yym13 - if false { - } else { - z.F.EncMapStringIntV(x.Map, false, e) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if x.StringList == nil { - r.EncodeNil() - } else { - yym15 := z.EncBinary() - _ = yym15 - if false { - } else { - z.F.EncSliceStringV(x.StringList, false, e) - } - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("StringList")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - if x.StringList == nil { - r.EncodeNil() - } else { - yym16 := z.EncBinary() - _ = yym16 - if false { - } else { - z.F.EncSliceStringV(x.StringList, false, e) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if x.IntList == nil { - r.EncodeNil() - } else { - yym18 := z.EncBinary() - _ = yym18 - if false { - } else { - z.F.EncSliceIntV(x.IntList, false, e) - } - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("IntList")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - if x.IntList == nil { - r.EncodeNil() - } else { - yym19 := z.EncBinary() - _ = yym19 - if false { - } else { - z.F.EncSliceIntV(x.IntList, false, e) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[5] { - yym21 := z.EncBinary() - _ = yym21 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) - } - } else { - r.EncodeString(codecSelferC_UTF81234, "") - } - } else { - if yyq2[5] { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("kind")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym22 := z.EncBinary() - _ = yym22 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[6] { - yym24 := z.EncBinary() - _ = yym24 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) - } - } else { - r.EncodeString(codecSelferC_UTF81234, "") - } - } else { - if yyq2[6] { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym25 := z.EncBinary() - _ = yym25 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) - } - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayEnd1234) - } else { - z.EncSendContainerState(codecSelfer_containerMapEnd1234) - } - } - } -} - -func (x *TestStruct) 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 *TestStruct) 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 "Key": - if r.TryDecodeAsNil() { - x.Key = "" - } else { - x.Key = string(r.DecodeString()) - } - case "Map": - if r.TryDecodeAsNil() { - x.Map = nil - } else { - yyv6 := &x.Map - yym7 := z.DecBinary() - _ = yym7 - if false { - } else { - z.F.DecMapStringIntX(yyv6, false, d) - } - } - case "StringList": - if r.TryDecodeAsNil() { - x.StringList = nil - } else { - yyv8 := &x.StringList - yym9 := z.DecBinary() - _ = yym9 - if false { - } else { - z.F.DecSliceStringX(yyv8, false, d) - } - } - case "IntList": - if r.TryDecodeAsNil() { - x.IntList = nil - } else { - yyv10 := &x.IntList - yym11 := z.DecBinary() - _ = yym11 - if false { - } else { - z.F.DecSliceIntX(yyv10, 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 *TestStruct) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer1234 - z, r := codec1978.GenHelperDecoder(d) - _, _, _ = h, z, r - var yyj14 int - var yyb14 bool - var yyhl14 bool = l >= 0 - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.ObjectMeta = pkg2_api.ObjectMeta{} - } else { - yyv15 := &x.ObjectMeta - yyv15.CodecDecodeSelf(d) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.Key = "" - } else { - x.Key = string(r.DecodeString()) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.Map = nil - } else { - yyv17 := &x.Map - yym18 := z.DecBinary() - _ = yym18 - if false { - } else { - z.F.DecMapStringIntX(yyv17, false, d) - } - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.StringList = nil - } else { - yyv19 := &x.StringList - yym20 := z.DecBinary() - _ = yym20 - if false { - } else { - z.F.DecSliceStringX(yyv19, false, d) - } - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.IntList = nil - } else { - yyv21 := &x.IntList - yym22 := z.DecBinary() - _ = yym22 - if false { - } else { - z.F.DecSliceIntX(yyv21, false, d) - } - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.Kind = "" - } else { - x.Kind = string(r.DecodeString()) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) - return - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - if r.TryDecodeAsNil() { - x.APIVersion = "" - } else { - x.APIVersion = string(r.DecodeString()) - } - for { - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = r.CheckBreak() - } - if yyb14 { - break - } - z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj14-1, "") - } - z.DecSendContainerState(codecSelfer_containerArrayEnd1234) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/testing/types.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/testing/types.go deleted file mode 100644 index 2fbc2ed45..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubectl/testing/types.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testing - -import ( - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" -) - -type TestStruct struct { - unversioned.TypeMeta `json:",inline"` - api.ObjectMeta `json:"metadata,omitempty"` - Key string `json:"Key"` - Map map[string]int `json:"Map"` - StringList []string `json:"StringList"` - IntList []int `json:"IntList"` -} - -func (obj *TestStruct) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubelet/qos/memory_policy_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubelet/qos/memory_policy_test.go deleted file mode 100644 index 27af3fd11..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/kubelet/qos/memory_policy_test.go +++ /dev/null @@ -1,187 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package qos - -import ( - "strconv" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/resource" -) - -const ( - standardMemoryAmount = 8000000000 -) - -var ( - zeroRequestMemoryBestEffort = api.Container{ - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("5m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("0G"), - }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("5m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - } - - edgeMemoryBestEffort = api.Container{ - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("0G"), - }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("0G"), - }, - }, - } - - noRequestMemoryBestEffort = api.Container{ - Resources: api.ResourceRequirements{ - Limits: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - } - - noLimitMemoryBestEffort = api.Container{} - - memoryGuaranteed = api.Container{ - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceCPU): resource.MustParse("5m"), - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - } - - memoryBurstable = api.Container{ - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount / 2)), - }, - Limits: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse("10G"), - }, - }, - } - - memoryBurstableNoLimit = api.Container{ - Resources: api.ResourceRequirements{ - Requests: api.ResourceList{ - api.ResourceName(api.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount - 1)), - }, - }, - } -) - -func TestIsMemoryBestEffort(t *testing.T) { - validCases := []api.Container{zeroRequestMemoryBestEffort, noRequestMemoryBestEffort, noLimitMemoryBestEffort, edgeMemoryBestEffort} - for _, container := range validCases { - if !isMemoryBestEffort(&container) { - t.Errorf("container %+v is memory best-effort", container) - } - } - invalidCases := []api.Container{memoryGuaranteed, memoryBurstable} - for _, container := range invalidCases { - if isMemoryBestEffort(&container) { - t.Errorf("container %+v is not memory best-effort", container) - } - } -} - -func TestIsMemoryGuaranteed(t *testing.T) { - validCases := []api.Container{memoryGuaranteed} - for _, container := range validCases { - if !isMemoryGuaranteed(&container) { - t.Errorf("container %+v is memory guaranteed", container) - } - } - invalidCases := []api.Container{zeroRequestMemoryBestEffort, noRequestMemoryBestEffort, noLimitMemoryBestEffort, edgeMemoryBestEffort, memoryBurstable} - for _, container := range invalidCases { - if isMemoryGuaranteed(&container) { - t.Errorf("container %+v is not memory guaranteed", container) - } - } -} - -type oomTest struct { - container *api.Container - memoryCapacity int64 - lowOOMScoreAdj int // The max oom_score_adj score the container should be assigned. - highOOMScoreAdj int // The min oom_score_adj score the container should be assigned. -} - -func TestGetContainerOOMScoreAdjust(t *testing.T) { - - oomTests := []oomTest{ - { - container: &zeroRequestMemoryBestEffort, - memoryCapacity: 4000000000, - lowOOMScoreAdj: 1000, - highOOMScoreAdj: 1000, - }, - { - container: &edgeMemoryBestEffort, - memoryCapacity: 8000000000, - lowOOMScoreAdj: 1000, - highOOMScoreAdj: 1000, - }, - { - container: &noRequestMemoryBestEffort, - memoryCapacity: 7230457451, - lowOOMScoreAdj: 1000, - highOOMScoreAdj: 1000, - }, - { - container: &noLimitMemoryBestEffort, - memoryCapacity: 4000000000, - lowOOMScoreAdj: 1000, - highOOMScoreAdj: 1000, - }, - { - container: &memoryGuaranteed, - memoryCapacity: 123456789, - lowOOMScoreAdj: -999, - highOOMScoreAdj: -999, - }, - { - container: &memoryBurstable, - memoryCapacity: standardMemoryAmount, - lowOOMScoreAdj: 495, - highOOMScoreAdj: 505, - }, - { - container: &memoryBurstableNoLimit, - memoryCapacity: standardMemoryAmount, - lowOOMScoreAdj: 2, - highOOMScoreAdj: 2, - }, - } - for _, test := range oomTests { - oomScoreAdj := GetContainerOOMScoreAdjust(test.container, test.memoryCapacity) - if oomScoreAdj < test.lowOOMScoreAdj || oomScoreAdj > test.highOOMScoreAdj { - t.Errorf("oom_score_adj should be between %d and %d, but was %d", test.lowOOMScoreAdj, test.highOOMScoreAdj, oomScoreAdj) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/labels_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/labels_test.go deleted file mode 100644 index 8d3834d51..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/labels_test.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package labels - -import ( - "testing" -) - -func matches(t *testing.T, ls Set, want string) { - if ls.String() != want { - t.Errorf("Expected '%s', but got '%s'", want, ls.String()) - } -} - -func TestSetString(t *testing.T) { - matches(t, Set{"x": "y"}, "x=y") - matches(t, Set{"foo": "bar"}, "foo=bar") - matches(t, Set{"foo": "bar", "baz": "qup"}, "baz=qup,foo=bar") - - // TODO: Make our label representation robust enough to handle labels - // with ",=!" characters in their names. -} - -func TestLabelHas(t *testing.T) { - labelHasTests := []struct { - Ls Labels - Key string - Has bool - }{ - {Set{"x": "y"}, "x", true}, - {Set{"x": ""}, "x", true}, - {Set{"x": "y"}, "foo", false}, - } - for _, lh := range labelHasTests { - if has := lh.Ls.Has(lh.Key); has != lh.Has { - t.Errorf("%#v.Has(%#v) => %v, expected %v", lh.Ls, lh.Key, has, lh.Has) - } - } -} - -func TestLabelGet(t *testing.T) { - ls := Set{"x": "y"} - if ls.Get("x") != "y" { - t.Errorf("Set.Get is broken") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/selector.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/selector.go index 520377486..fb48b10e9 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/selector.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/selector.go @@ -72,8 +72,8 @@ const ( NotEqualsOperator Operator = "!=" NotInOperator Operator = "notin" ExistsOperator Operator = "exists" - GreaterThanOperator Operator = "Gt" - LessThanOperator Operator = "Lt" + GreaterThanOperator Operator = "gt" + LessThanOperator Operator = "lt" ) func NewSelector() Selector { @@ -743,13 +743,25 @@ func (p *Parser) parseExactValue() (sets.String, error) { // (5) A requirement with just !KEY requires that the KEY not exist. // func Parse(selector string) (Selector, error) { - p := &Parser{l: &Lexer{s: selector, pos: 0}} - items, error := p.parse() - if error == nil { - sort.Sort(ByKey(items)) // sort to grant determistic parsing - return internalSelector(items), error + parsedSelector, err := parse(selector) + if err == nil { + return parsedSelector, nil } - return nil, error + return nil, err +} + +// parse parses the string representation of the selector and returns the internalSelector struct. +// The callers of this method can then decide how to return the internalSelector struct to their +// callers. This function has two callers now, one returns a Selector interface and the other +// returns a list of requirements. +func parse(selector string) (internalSelector, error) { + p := &Parser{l: &Lexer{s: selector, pos: 0}} + items, err := p.parse() + if err != nil { + return nil, err + } + sort.Sort(ByKey(items)) // sort to grant determistic parsing + return internalSelector(items), err } var qualifiedNameErrorMsg string = fmt.Sprintf(`must be a qualified name (at most %d characters, matching regex %s), with an optional DNS subdomain prefix (at most %d characters, matching regex %s) and slash (/): e.g. "MyName" or "example.com/MyName"`, validation.QualifiedNameMaxLength, validation.QualifiedNameFmt, validation.DNS1123SubdomainMaxLength, validation.DNS1123SubdomainFmt) @@ -788,3 +800,12 @@ func SelectorFromSet(ls Set) Selector { sort.Sort(ByKey(requirements)) return internalSelector(requirements) } + +// ParseToRequirements takes a string representing a selector and returns a list of +// requirements. This function is suitable for those callers that perform additional +// processing on selector requirements. +// See the documentation for Parse() function for more details. +// TODO: Consider exporting the internalSelector type instead. +func ParseToRequirements(selector string) ([]Requirement, error) { + return parse(selector) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/selector_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/selector_test.go deleted file mode 100644 index 5fbb1fc76..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/labels/selector_test.go +++ /dev/null @@ -1,574 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package labels - -import ( - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/util/sets" -) - -func TestSelectorParse(t *testing.T) { - testGoodStrings := []string{ - "x=a,y=b,z=c", - "", - "x!=a,y=b", - "x=", - "x= ", - "x=,z= ", - "x= ,z= ", - "!x", - "x>1.1", - "x>1.1,z<5.3", - } - testBadStrings := []string{ - "x=a||y=b", - "x==a==b", - "!x=a", - "x1.1", Set{"x": "1.2"}) - expectMatch(t, "x<1.1", Set{"x": "0.8"}) - expectNoMatch(t, "x=z", Set{}) - expectNoMatch(t, "x=y", Set{"x": "z"}) - expectNoMatch(t, "x=y,z=w", Set{"x": "w", "z": "w"}) - expectNoMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "w"}) - expectNoMatch(t, "x", Set{"y": "z"}) - expectNoMatch(t, "!x", Set{"x": "z"}) - expectNoMatch(t, "x>1.1", Set{"x": "0.8"}) - expectNoMatch(t, "x<1.1", Set{"x": "1.1"}) - - labelset := Set{ - "foo": "bar", - "baz": "blah", - } - expectMatch(t, "foo=bar", labelset) - expectMatch(t, "baz=blah", labelset) - expectMatch(t, "foo=bar,baz=blah", labelset) - expectNoMatch(t, "foo=blah", labelset) - expectNoMatch(t, "baz=bar", labelset) - expectNoMatch(t, "foo=bar,foobar=bar,baz=blah", labelset) -} - -func expectMatchDirect(t *testing.T, selector, ls Set) { - if !SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls) - } -} - -func expectNoMatchDirect(t *testing.T, selector, ls Set) { - if SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) - } -} - -func TestSetMatches(t *testing.T) { - labelset := Set{ - "foo": "bar", - "baz": "blah", - } - expectMatchDirect(t, Set{}, labelset) - expectMatchDirect(t, Set{"foo": "bar"}, labelset) - expectMatchDirect(t, Set{"baz": "blah"}, labelset) - expectMatchDirect(t, Set{"foo": "bar", "baz": "blah"}, labelset) - - //TODO: bad values not handled for the moment in SelectorFromSet - //expectNoMatchDirect(t, Set{"foo": "=blah"}, labelset) - //expectNoMatchDirect(t, Set{"baz": "=bar"}, labelset) - //expectNoMatchDirect(t, Set{"foo": "=bar", "foobar": "bar", "baz": "blah"}, labelset) -} - -func TestNilMapIsValid(t *testing.T) { - selector := Set(nil).AsSelector() - if selector == nil { - t.Errorf("Selector for nil set should be Everything") - } - if !selector.Empty() { - t.Errorf("Selector for nil set should be Empty") - } -} - -func TestSetIsEmpty(t *testing.T) { - if !(Set{}).AsSelector().Empty() { - t.Errorf("Empty set should be empty") - } - if !(NewSelector()).Empty() { - t.Errorf("Nil Selector should be empty") - } -} - -func TestLexer(t *testing.T) { - testcases := []struct { - s string - t Token - }{ - {"", EndOfStringToken}, - {",", CommaToken}, - {"notin", NotInToken}, - {"in", InToken}, - {"=", EqualsToken}, - {"==", DoubleEqualsToken}, - {">", GreaterThanToken}, - {"<", LessThanToken}, - //Note that Lex returns the longest valid token found - {"!", DoesNotExistToken}, - {"!=", NotEqualsToken}, - {"(", OpenParToken}, - {")", ClosedParToken}, - //Non-"special" characters are considered part of an identifier - {"~", IdentifierToken}, - {"||", IdentifierToken}, - } - for _, v := range testcases { - l := &Lexer{s: v.s, pos: 0} - token, lit := l.Lex() - if token != v.t { - t.Errorf("Got %d it should be %d for '%s'", token, v.t, v.s) - } - if v.t != ErrorToken && lit != v.s { - t.Errorf("Got '%s' it should be '%s'", lit, v.s) - } - } -} - -func min(l, r int) (m int) { - m = r - if l < r { - m = l - } - return m -} - -func TestLexerSequence(t *testing.T) { - testcases := []struct { - s string - t []Token - }{ - {"key in ( value )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, ClosedParToken}}, - {"key notin ( value )", []Token{IdentifierToken, NotInToken, OpenParToken, IdentifierToken, ClosedParToken}}, - {"key in ( value1, value2 )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, CommaToken, IdentifierToken, ClosedParToken}}, - {"key", []Token{IdentifierToken}}, - {"!key", []Token{DoesNotExistToken, IdentifierToken}}, - {"()", []Token{OpenParToken, ClosedParToken}}, - {"x in (),y", []Token{IdentifierToken, InToken, OpenParToken, ClosedParToken, CommaToken, IdentifierToken}}, - {"== != (), = notin", []Token{DoubleEqualsToken, NotEqualsToken, OpenParToken, ClosedParToken, CommaToken, EqualsToken, NotInToken}}, - {"key>1.1", []Token{IdentifierToken, GreaterThanToken, IdentifierToken}}, - {"key<0.8", []Token{IdentifierToken, LessThanToken, IdentifierToken}}, - } - for _, v := range testcases { - var literals []string - var tokens []Token - l := &Lexer{s: v.s, pos: 0} - for { - token, lit := l.Lex() - if token == EndOfStringToken { - break - } - tokens = append(tokens, token) - literals = append(literals, lit) - } - if len(tokens) != len(v.t) { - t.Errorf("Bad number of tokens for '%s %d, %d", v.s, len(tokens), len(v.t)) - } - for i := 0; i < min(len(tokens), len(v.t)); i++ { - if tokens[i] != v.t[i] { - t.Errorf("Test '%s': Mismatching in token type found '%v' it should be '%v'", v.s, tokens[i], v.t[i]) - } - } - } -} -func TestParserLookahead(t *testing.T) { - testcases := []struct { - s string - t []Token - }{ - {"key in ( value )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, ClosedParToken, EndOfStringToken}}, - {"key notin ( value )", []Token{IdentifierToken, NotInToken, OpenParToken, IdentifierToken, ClosedParToken, EndOfStringToken}}, - {"key in ( value1, value2 )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, CommaToken, IdentifierToken, ClosedParToken, EndOfStringToken}}, - {"key", []Token{IdentifierToken, EndOfStringToken}}, - {"!key", []Token{DoesNotExistToken, IdentifierToken, EndOfStringToken}}, - {"()", []Token{OpenParToken, ClosedParToken, EndOfStringToken}}, - {"", []Token{EndOfStringToken}}, - {"x in (),y", []Token{IdentifierToken, InToken, OpenParToken, ClosedParToken, CommaToken, IdentifierToken, EndOfStringToken}}, - {"== != (), = notin", []Token{DoubleEqualsToken, NotEqualsToken, OpenParToken, ClosedParToken, CommaToken, EqualsToken, NotInToken, EndOfStringToken}}, - {"key>1.1", []Token{IdentifierToken, GreaterThanToken, IdentifierToken, EndOfStringToken}}, - {"key<0.8", []Token{IdentifierToken, LessThanToken, IdentifierToken, EndOfStringToken}}, - } - for _, v := range testcases { - p := &Parser{l: &Lexer{s: v.s, pos: 0}, position: 0} - p.scan() - if len(p.scannedItems) != len(v.t) { - t.Errorf("Expected %d items found %d", len(v.t), len(p.scannedItems)) - } - for { - token, lit := p.lookahead(KeyAndOperator) - - token2, lit2 := p.consume(KeyAndOperator) - if token == EndOfStringToken { - break - } - if token != token2 || lit != lit2 { - t.Errorf("Bad values") - } - } - } -} - -func TestRequirementConstructor(t *testing.T) { - requirementConstructorTests := []struct { - Key string - Op Operator - Vals sets.String - Success bool - }{ - {"x", InOperator, nil, false}, - {"x", NotInOperator, sets.NewString(), false}, - {"x", InOperator, sets.NewString("foo"), true}, - {"x", NotInOperator, sets.NewString("foo"), true}, - {"x", ExistsOperator, nil, true}, - {"x", DoesNotExistOperator, nil, true}, - {"1foo", InOperator, sets.NewString("bar"), true}, - {"1234", InOperator, sets.NewString("bar"), true}, - {"y", GreaterThanOperator, sets.NewString("1.1"), true}, - {"z", LessThanOperator, sets.NewString("5.3"), true}, - {"foo", GreaterThanOperator, sets.NewString("bar"), false}, - {"barz", LessThanOperator, sets.NewString("blah"), false}, - {strings.Repeat("a", 254), ExistsOperator, nil, false}, //breaks DNS rule that len(key) <= 253 - } - for _, rc := range requirementConstructorTests { - if _, err := NewRequirement(rc.Key, rc.Op, rc.Vals); err == nil && !rc.Success { - t.Errorf("expected error with key:%#v op:%v vals:%v, got no error", rc.Key, rc.Op, rc.Vals) - } else if err != nil && rc.Success { - t.Errorf("expected no error with key:%#v op:%v vals:%v, got:%v", rc.Key, rc.Op, rc.Vals, err) - } - } -} - -func TestToString(t *testing.T) { - var req Requirement - toStringTests := []struct { - In *internalSelector - Out string - Valid bool - }{ - - {&internalSelector{ - getRequirement("x", InOperator, sets.NewString("abc", "def"), t), - getRequirement("y", NotInOperator, sets.NewString("jkl"), t), - getRequirement("z", ExistsOperator, nil, t)}, - "x in (abc,def),y notin (jkl),z", true}, - {&internalSelector{ - getRequirement("x", NotInOperator, sets.NewString("abc", "def"), t), - getRequirement("y", NotEqualsOperator, sets.NewString("jkl"), t), - getRequirement("z", DoesNotExistOperator, nil, t)}, - "x notin (abc,def),y!=jkl,!z", true}, - {&internalSelector{ - getRequirement("x", InOperator, sets.NewString("abc", "def"), t), - req}, // adding empty req for the trailing ',' - "x in (abc,def),", false}, - {&internalSelector{ - getRequirement("x", NotInOperator, sets.NewString("abc"), t), - getRequirement("y", InOperator, sets.NewString("jkl", "mno"), t), - getRequirement("z", NotInOperator, sets.NewString(""), t)}, - "x notin (abc),y in (jkl,mno),z notin ()", true}, - {&internalSelector{ - getRequirement("x", EqualsOperator, sets.NewString("abc"), t), - getRequirement("y", DoubleEqualsOperator, sets.NewString("jkl"), t), - getRequirement("z", NotEqualsOperator, sets.NewString("a"), t), - getRequirement("z", ExistsOperator, nil, t)}, - "x=abc,y==jkl,z!=a,z", true}, - {&internalSelector{ - getRequirement("x", GreaterThanOperator, sets.NewString("2.4"), t), - getRequirement("y", LessThanOperator, sets.NewString("7.1"), t), - getRequirement("z", ExistsOperator, nil, t)}, - "x>2.4,y<7.1,z", true}, - } - for _, ts := range toStringTests { - if out := ts.In.String(); out == "" && ts.Valid { - t.Errorf("%+v.String() => '%v' expected no error", ts.In, out) - } else if out != ts.Out { - t.Errorf("%+v.String() => '%v' want '%v'", ts.In, out, ts.Out) - } - } -} - -func TestRequirementSelectorMatching(t *testing.T) { - var req Requirement - labelSelectorMatchingTests := []struct { - Set Set - Sel Selector - Match bool - }{ - {Set{"x": "foo", "y": "baz"}, &internalSelector{ - req, - }, false}, - {Set{"x": "foo", "y": "baz"}, &internalSelector{ - getRequirement("x", InOperator, sets.NewString("foo"), t), - getRequirement("y", NotInOperator, sets.NewString("alpha"), t), - }, true}, - {Set{"x": "foo", "y": "baz"}, &internalSelector{ - getRequirement("x", InOperator, sets.NewString("foo"), t), - getRequirement("y", InOperator, sets.NewString("alpha"), t), - }, false}, - {Set{"y": ""}, &internalSelector{ - getRequirement("x", NotInOperator, sets.NewString(""), t), - getRequirement("y", ExistsOperator, nil, t), - }, true}, - {Set{"y": ""}, &internalSelector{ - getRequirement("x", DoesNotExistOperator, nil, t), - getRequirement("y", ExistsOperator, nil, t), - }, true}, - {Set{"y": ""}, &internalSelector{ - getRequirement("x", NotInOperator, sets.NewString(""), t), - getRequirement("y", DoesNotExistOperator, nil, t), - }, false}, - {Set{"y": "baz"}, &internalSelector{ - getRequirement("x", InOperator, sets.NewString(""), t), - }, false}, - {Set{"z": "1.2"}, &internalSelector{ - getRequirement("z", GreaterThanOperator, sets.NewString("1.0"), t), - }, true}, - {Set{"z": "v1.2"}, &internalSelector{ - getRequirement("z", GreaterThanOperator, sets.NewString("1.0"), t), - }, false}, - } - for _, lsm := range labelSelectorMatchingTests { - if match := lsm.Sel.Matches(lsm.Set); match != lsm.Match { - t.Errorf("%+v.Matches(%#v) => %v, want %v", lsm.Sel, lsm.Set, match, lsm.Match) - } - } -} - -func TestSetSelectorParser(t *testing.T) { - setSelectorParserTests := []struct { - In string - Out Selector - Match bool - Valid bool - }{ - {"", NewSelector(), true, true}, - {"\rx", internalSelector{ - getRequirement("x", ExistsOperator, nil, t), - }, true, true}, - {"this-is-a-dns.domain.com/key-with-dash", internalSelector{ - getRequirement("this-is-a-dns.domain.com/key-with-dash", ExistsOperator, nil, t), - }, true, true}, - {"this-is-another-dns.domain.com/key-with-dash in (so,what)", internalSelector{ - getRequirement("this-is-another-dns.domain.com/key-with-dash", InOperator, sets.NewString("so", "what"), t), - }, true, true}, - {"0.1.2.domain/99 notin (10.10.100.1, tick.tack.clock)", internalSelector{ - getRequirement("0.1.2.domain/99", NotInOperator, sets.NewString("10.10.100.1", "tick.tack.clock"), t), - }, true, true}, - {"foo in (abc)", internalSelector{ - getRequirement("foo", InOperator, sets.NewString("abc"), t), - }, true, true}, - {"x notin\n (abc)", internalSelector{ - getRequirement("x", NotInOperator, sets.NewString("abc"), t), - }, true, true}, - {"x notin \t (abc,def)", internalSelector{ - getRequirement("x", NotInOperator, sets.NewString("abc", "def"), t), - }, true, true}, - {"x in (abc,def)", internalSelector{ - getRequirement("x", InOperator, sets.NewString("abc", "def"), t), - }, true, true}, - {"x in (abc,)", internalSelector{ - getRequirement("x", InOperator, sets.NewString("abc", ""), t), - }, true, true}, - {"x in ()", internalSelector{ - getRequirement("x", InOperator, sets.NewString(""), t), - }, true, true}, - {"x notin (abc,,def),bar,z in (),w", internalSelector{ - getRequirement("bar", ExistsOperator, nil, t), - getRequirement("w", ExistsOperator, nil, t), - getRequirement("x", NotInOperator, sets.NewString("abc", "", "def"), t), - getRequirement("z", InOperator, sets.NewString(""), t), - }, true, true}, - {"x,y in (a)", internalSelector{ - getRequirement("y", InOperator, sets.NewString("a"), t), - getRequirement("x", ExistsOperator, nil, t), - }, false, true}, - {"x=a", internalSelector{ - getRequirement("x", EqualsOperator, sets.NewString("a"), t), - }, true, true}, - {"x>1.1", internalSelector{ - getRequirement("x", GreaterThanOperator, sets.NewString("1.1"), t), - }, true, true}, - {"x<7.1", internalSelector{ - getRequirement("x", LessThanOperator, sets.NewString("7.1"), t), - }, true, true}, - {"x=a,y!=b", internalSelector{ - getRequirement("x", EqualsOperator, sets.NewString("a"), t), - getRequirement("y", NotEqualsOperator, sets.NewString("b"), t), - }, true, true}, - {"x=a,y!=b,z in (h,i,j)", internalSelector{ - getRequirement("x", EqualsOperator, sets.NewString("a"), t), - getRequirement("y", NotEqualsOperator, sets.NewString("b"), t), - getRequirement("z", InOperator, sets.NewString("h", "i", "j"), t), - }, true, true}, - {"x=a||y=b", internalSelector{}, false, false}, - {"x,,y", nil, true, false}, - {",x,y", nil, true, false}, - {"x nott in (y)", nil, true, false}, - {"x notin ( )", internalSelector{ - getRequirement("x", NotInOperator, sets.NewString(""), t), - }, true, true}, - {"x notin (, a)", internalSelector{ - getRequirement("x", NotInOperator, sets.NewString("", "a"), t), - }, true, true}, - {"a in (xyz),", nil, true, false}, - {"a in (xyz)b notin ()", nil, true, false}, - {"a ", internalSelector{ - getRequirement("a", ExistsOperator, nil, t), - }, true, true}, - {"a in (x,y,notin, z,in)", internalSelector{ - getRequirement("a", InOperator, sets.NewString("in", "notin", "x", "y", "z"), t), - }, true, true}, // operator 'in' inside list of identifiers - {"a in (xyz abc)", nil, false, false}, // no comma - {"a notin(", nil, true, false}, // bad formed - {"a (", nil, false, false}, // cpar - {"(", nil, false, false}, // opar - } - - for _, ssp := range setSelectorParserTests { - if sel, err := Parse(ssp.In); err != nil && ssp.Valid { - t.Errorf("Parse(%s) => %v expected no error", ssp.In, err) - } else if err == nil && !ssp.Valid { - t.Errorf("Parse(%s) => %+v expected error", ssp.In, sel) - } else if ssp.Match && !reflect.DeepEqual(sel, ssp.Out) { - t.Errorf("Parse(%s) => parse output '%#v' doesn't match '%#v' expected match", ssp.In, sel, ssp.Out) - } - } -} - -func getRequirement(key string, op Operator, vals sets.String, t *testing.T) Requirement { - req, err := NewRequirement(key, op, vals) - if err != nil { - t.Errorf("NewRequirement(%v, %v, %v) resulted in error:%v", key, op, vals, err) - return Requirement{} - } - return *req -} - -func TestAdd(t *testing.T) { - testCases := []struct { - name string - sel Selector - key string - operator Operator - values []string - refSelector Selector - }{ - { - "keyInOperator", - internalSelector{}, - "key", - InOperator, - []string{"value"}, - internalSelector{Requirement{"key", InOperator, sets.NewString("value")}}, - }, - { - "keyEqualsOperator", - internalSelector{Requirement{"key", InOperator, sets.NewString("value")}}, - "key2", - EqualsOperator, - []string{"value2"}, - internalSelector{ - Requirement{"key", InOperator, sets.NewString("value")}, - Requirement{"key2", EqualsOperator, sets.NewString("value2")}, - }, - }, - } - for _, ts := range testCases { - req, err := NewRequirement(ts.key, ts.operator, sets.NewString(ts.values...)) - if err != nil { - t.Errorf("%s - Unable to create labels.Requirement", ts.name) - } - ts.sel = ts.sel.Add(*req) - if !reflect.DeepEqual(ts.sel, ts.refSelector) { - t.Errorf("%s - Expected %v found %v", ts.name, ts.refSelector, ts.sel) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/OWNERS b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/OWNERS new file mode 100644 index 000000000..d038b5e9b --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/OWNERS @@ -0,0 +1,5 @@ +assignees: + - caesarxuchao + - deads2k + - lavalamp + - smarterclayton diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/conversion_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/conversion_test.go deleted file mode 100644 index 6105e5aad..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/conversion_test.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package runtime_test - -import ( - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -type InternalComplex struct { - runtime.TypeMeta - String string - Integer int - Integer64 int64 - Int64 int64 - Bool bool -} - -type ExternalComplex struct { - runtime.TypeMeta `json:",inline"` - String string `json:"string" description:"testing"` - Integer int `json:"int"` - Integer64 int64 `json:",omitempty"` - Int64 int64 - Bool bool `json:"bool"` -} - -func (obj *InternalComplex) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ExternalComplex) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } - -func TestStringMapConversion(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "external"} - - scheme := runtime.NewScheme() - scheme.Log(t) - scheme.AddKnownTypeWithName(internalGV.WithKind("Complex"), &InternalComplex{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("Complex"), &ExternalComplex{}) - - testCases := map[string]struct { - input map[string][]string - errFn func(error) bool - expected runtime.Object - }{ - "ignores omitempty": { - input: map[string][]string{ - "String": {"not_used"}, - "string": {"value"}, - "int": {"1"}, - "Integer64": {"2"}, - }, - expected: &ExternalComplex{String: "value", Integer: 1}, - }, - "returns error on bad int": { - input: map[string][]string{ - "int": {"a"}, - }, - errFn: func(err error) bool { return err != nil }, - expected: &ExternalComplex{}, - }, - "parses int64": { - input: map[string][]string{ - "Int64": {"-1"}, - }, - expected: &ExternalComplex{Int64: -1}, - }, - "returns error on bad int64": { - input: map[string][]string{ - "Int64": {"a"}, - }, - errFn: func(err error) bool { return err != nil }, - expected: &ExternalComplex{}, - }, - "parses boolean true": { - input: map[string][]string{ - "bool": {"true"}, - }, - expected: &ExternalComplex{Bool: true}, - }, - "parses boolean any value": { - input: map[string][]string{ - "bool": {"foo"}, - }, - expected: &ExternalComplex{Bool: true}, - }, - "parses boolean false": { - input: map[string][]string{ - "bool": {"false"}, - }, - expected: &ExternalComplex{Bool: false}, - }, - "parses boolean empty value": { - input: map[string][]string{ - "bool": {""}, - }, - expected: &ExternalComplex{Bool: true}, - }, - "parses boolean no value": { - input: map[string][]string{ - "bool": {}, - }, - expected: &ExternalComplex{Bool: false}, - }, - } - - for k, tc := range testCases { - out := &ExternalComplex{} - if err := scheme.Convert(&tc.input, out); (tc.errFn == nil && err != nil) || (tc.errFn != nil && !tc.errFn(err)) { - t.Errorf("%s: unexpected error: %v", k, err) - continue - } else if err != nil { - continue - } - if !reflect.DeepEqual(out, tc.expected) { - t.Errorf("%s: unexpected output: %#v", k, out) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/embedded_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/embedded_test.go deleted file mode 100644 index 64d6d74fb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/embedded_test.go +++ /dev/null @@ -1,287 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package runtime_test - -import ( - "encoding/json" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/runtime/serializer" - "k8s.io/kubernetes/pkg/util" -) - -type EmbeddedTest struct { - runtime.TypeMeta - ID string - Object runtime.Object - EmptyObject runtime.Object -} - -type EmbeddedTestExternal struct { - runtime.TypeMeta `json:",inline"` - ID string `json:"id,omitempty"` - Object runtime.RawExtension `json:"object,omitempty"` - EmptyObject runtime.RawExtension `json:"emptyObject,omitempty"` -} - -type ObjectTest struct { - runtime.TypeMeta - - ID string - Items []runtime.Object -} - -type ObjectTestExternal struct { - runtime.TypeMeta `yaml:",inline" json:",inline"` - - ID string `json:"id,omitempty"` - Items []runtime.RawExtension `json:"items,omitempty"` -} - -func (obj *ObjectTest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ObjectTestExternal) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *EmbeddedTest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *EmbeddedTestExternal) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } - -func TestDecodeEmptyRawExtensionAsObject(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "v1test"} - externalGVK := externalGV.WithKind("ObjectTest") - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &ObjectTest{}) - s.AddKnownTypeWithName(externalGVK, &ObjectTestExternal{}) - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - obj, gvk, err := codec.Decode([]byte(`{"kind":"`+externalGVK.Kind+`","apiVersion":"`+externalGV.String()+`","items":[{}]}`), nil, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - test := obj.(*ObjectTest) - if unk, ok := test.Items[0].(*runtime.Unknown); !ok || unk.Kind != "" || unk.APIVersion != "" || string(unk.RawJSON) != "{}" { - t.Fatalf("unexpected object: %#v", test.Items[0]) - } - if *gvk != externalGVK { - t.Fatalf("unexpected kind: %#v", gvk) - } - - obj, gvk, err = codec.Decode([]byte(`{"kind":"`+externalGVK.Kind+`","apiVersion":"`+externalGV.String()+`","items":[{"kind":"Other","apiVersion":"v1"}]}`), nil, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - test = obj.(*ObjectTest) - if unk, ok := test.Items[0].(*runtime.Unknown); !ok || unk.Kind != "" || unk.APIVersion != "" || string(unk.RawJSON) != `{"kind":"Other","apiVersion":"v1"}` { - t.Fatalf("unexpected object: %#v", test.Items[0]) - } - if *gvk != externalGVK { - t.Fatalf("unexpected kind: %#v", gvk) - } -} - -func TestArrayOfRuntimeObject(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "v1test"} - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &EmbeddedTest{}) - s.AddKnownTypeWithName(externalGV.WithKind("EmbeddedTest"), &EmbeddedTestExternal{}) - s.AddKnownTypes(internalGV, &ObjectTest{}) - s.AddKnownTypeWithName(externalGV.WithKind("ObjectTest"), &ObjectTestExternal{}) - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - innerItems := []runtime.Object{ - &EmbeddedTest{ID: "baz"}, - } - items := []runtime.Object{ - &EmbeddedTest{ID: "foo"}, - &EmbeddedTest{ID: "bar"}, - // TODO: until YAML is removed, this JSON must be in ascending key order to ensure consistent roundtrip serialization - &runtime.Unknown{RawJSON: []byte(`{"apiVersion":"unknown.group/unknown","foo":"bar","kind":"OtherTest"}`)}, - &ObjectTest{ - Items: runtime.NewEncodableList(codec, innerItems), - }, - } - internal := &ObjectTest{ - Items: runtime.NewEncodableList(codec, items), - } - wire, err := runtime.Encode(codec, internal) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - t.Logf("Wire format is:\n%s\n", string(wire)) - - obj := &ObjectTestExternal{} - if err := json.Unmarshal(wire, obj); err != nil { - t.Fatalf("unexpected error: %v", err) - } - t.Logf("exact wire is: %s", string(obj.Items[0].RawJSON)) - - items[3] = &ObjectTest{Items: innerItems} - internal.Items = items - - decoded, err := runtime.Decode(codec, wire) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - list, err := meta.ExtractList(decoded) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if errs := runtime.DecodeList(list, codec); len(errs) > 0 { - t.Fatalf("unexpected error: %v", errs) - } - - list2, err := meta.ExtractList(list[3]) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if errs := runtime.DecodeList(list2, codec); len(errs) > 0 { - t.Fatalf("unexpected error: %v", errs) - } - if err := meta.SetList(list[3], list2); err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // we want DecodeList to set type meta if possible, even on runtime.Unknown objects - internal.Items[2].(*runtime.Unknown).TypeMeta = runtime.TypeMeta{Kind: "OtherTest", APIVersion: "unknown.group/unknown"} - if e, a := internal.Items, list; !reflect.DeepEqual(e, a) { - t.Errorf("mismatched decoded: %s", util.ObjectGoPrintSideBySide(e, a)) - } -} - -func TestNestedObject(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "v1test"} - embeddedTestExternalGVK := externalGV.WithKind("EmbeddedTest") - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &EmbeddedTest{}) - s.AddKnownTypeWithName(embeddedTestExternalGVK, &EmbeddedTestExternal{}) - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - inner := &EmbeddedTest{ - ID: "inner", - } - outer := &EmbeddedTest{ - ID: "outer", - Object: runtime.NewEncodable(codec, inner), - } - - wire, err := runtime.Encode(codec, outer) - if err != nil { - t.Fatalf("Unexpected encode error '%v'", err) - } - - t.Logf("Wire format is:\n%v\n", string(wire)) - - decoded, err := runtime.Decode(codec, wire) - if err != nil { - t.Fatalf("Unexpected decode error %v", err) - } - - // for later tests - outer.Object = inner - - if e, a := outer, decoded; reflect.DeepEqual(e, a) { - t.Errorf("Expected unequal %#v %#v", e, a) - } - - obj, err := runtime.Decode(codec, decoded.(*EmbeddedTest).Object.(*runtime.Unknown).RawJSON) - if err != nil { - t.Fatal(err) - } - decoded.(*EmbeddedTest).Object = obj - if e, a := outer, decoded; !reflect.DeepEqual(e, a) { - t.Errorf("Expected equal %#v %#v", e, a) - } - - // test JSON decoding of the external object, which should preserve - // raw bytes - var externalViaJSON EmbeddedTestExternal - err = json.Unmarshal(wire, &externalViaJSON) - if err != nil { - t.Fatalf("Unexpected decode error %v", err) - } - if externalViaJSON.Kind == "" || externalViaJSON.APIVersion == "" || externalViaJSON.ID != "outer" { - t.Errorf("Expected objects to have type info set, got %#v", externalViaJSON) - } - if !reflect.DeepEqual(externalViaJSON.EmptyObject.RawJSON, []byte("null")) || len(externalViaJSON.Object.RawJSON) == 0 { - t.Errorf("Expected deserialization of nested objects into bytes, got %#v", externalViaJSON) - } - - // test JSON decoding, too, since Decode uses yaml unmarshalling. - // Generic Unmarshalling of JSON cannot load the nested objects because there is - // no default schema set. Consumers wishing to get direct JSON decoding must use - // the external representation - var decodedViaJSON EmbeddedTest - err = json.Unmarshal(wire, &decodedViaJSON) - if err == nil || !strings.Contains(err.Error(), "unmarshal object into Go value of type runtime.Object") { - t.Fatalf("Unexpected decode error %v", err) - } - if a := decodedViaJSON; a.Object != nil || a.EmptyObject != nil { - t.Errorf("Expected embedded objects to be nil: %#v", a) - } -} - -// TestDeepCopyOfRuntimeObject checks to make sure that runtime.Objects's can be passed through DeepCopy with fidelity -func TestDeepCopyOfRuntimeObject(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "v1test"} - embeddedTestExternalGVK := externalGV.WithKind("EmbeddedTest") - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &EmbeddedTest{}) - s.AddKnownTypeWithName(embeddedTestExternalGVK, &EmbeddedTestExternal{}) - - original := &EmbeddedTest{ - ID: "outer", - Object: &EmbeddedTest{ - ID: "inner", - }, - } - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - originalData, err := runtime.Encode(codec, original) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - t.Logf("originalRole = %v\n", string(originalData)) - - copyOfOriginal, err := s.DeepCopy(original) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - copiedData, err := runtime.Encode(codec, copyOfOriginal.(runtime.Object)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - t.Logf("copyOfRole = %v\n", string(copiedData)) - - if !reflect.DeepEqual(original, copyOfOriginal) { - t.Errorf("expected \n%v\n, got \n%v", string(originalData), string(copiedData)) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/extension_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/extension_test.go deleted file mode 100644 index 3d8a087a9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/extension_test.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package runtime_test - -import ( - "encoding/json" - "testing" - - "k8s.io/kubernetes/pkg/runtime" -) - -func TestEmbeddedRawExtensionMarshal(t *testing.T) { - type test struct { - Ext runtime.RawExtension - } - - extension := test{Ext: runtime.RawExtension{RawJSON: []byte(`{"foo":"bar"}`)}} - data, err := json.Marshal(extension) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if string(data) != `{"Ext":{"foo":"bar"}}` { - t.Errorf("unexpected data: %s", string(data)) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/helper_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/helper_test.go deleted file mode 100644 index be7f0dedd..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/helper_test.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package runtime_test - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestDecodeList(t *testing.T) { - pl := &api.List{ - Items: []runtime.Object{ - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}}, - &runtime.Unknown{TypeMeta: runtime.TypeMeta{Kind: "Pod", APIVersion: testapi.Default.GroupVersion().String()}, RawJSON: []byte(`{"kind":"Pod","apiVersion":"` + testapi.Default.GroupVersion().String() + `","metadata":{"name":"test"}}`)}, - &runtime.Unstructured{TypeMeta: runtime.TypeMeta{Kind: "Foo", APIVersion: "Bar"}, Object: map[string]interface{}{"test": "value"}}, - }, - } - if errs := runtime.DecodeList(pl.Items, testapi.Default.Codec()); len(errs) != 0 { - t.Fatalf("unexpected error %v", errs) - } - if pod, ok := pl.Items[1].(*api.Pod); !ok || pod.Name != "test" { - t.Errorf("object not converted: %#v", pl.Items[1]) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/protobuf/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/protobuf/doc.go deleted file mode 100644 index 33316d0c4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/protobuf/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package protobuf implements ProtoBuf serialization and deserialization. -package protobuf diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/protobuf/protobuf.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/protobuf/protobuf.go deleted file mode 100644 index cc050a50b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/protobuf/protobuf.go +++ /dev/null @@ -1,158 +0,0 @@ -// +build proto - -/* -Copyright 2015 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. -*/ - -package protobuf - -import ( - "fmt" - "io" - "net/url" - "reflect" - - "github.com/gogo/protobuf/proto" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" -) - -// NewCodec -func NewCodec(version string, creater runtime.ObjectCreater, typer runtime.ObjectTyper, convertor runtime.ObjectConvertor) runtime.Codec { - return &codec{ - version: version, - creater: creater, - typer: typer, - convertor: convertor, - } -} - -// codec decodes protobuf objects -type codec struct { - version string - outputVersion string - creater runtime.ObjectCreater - typer runtime.ObjectTyper - convertor runtime.ObjectConvertor -} - -var _ runtime.Codec = codec{} - -func (c codec) Decode(data []byte) (runtime.Object, error) { - unknown := &runtime.Unknown{} - if err := proto.Unmarshal(data, unknown); err != nil { - return nil, err - } - obj, err := c.creater.New(unknown.APIVersion, unknown.Kind) - if err != nil { - return nil, err - } - pobj, ok := obj.(proto.Message) - if !ok { - return nil, fmt.Errorf("runtime object is not a proto.Message: %v", reflect.TypeOf(obj)) - } - if err := proto.Unmarshal(unknown.RawJSON, pobj); err != nil { - return nil, err - } - if unknown.APIVersion != c.outputVersion { - out, err := c.convertor.ConvertToVersion(obj, c.outputVersion) - if err != nil { - return nil, err - } - obj = out - } - return obj, nil -} - -func (c codec) DecodeToVersion(data []byte, version unversioned.GroupVersion) (runtime.Object, error) { - return nil, fmt.Errorf("unimplemented") -} - -func (c codec) DecodeInto(data []byte, obj runtime.Object) error { - version, kind, err := c.typer.ObjectVersionAndKind(obj) - if err != nil { - return err - } - unknown := &runtime.Unknown{} - if err := proto.Unmarshal(data, unknown); err != nil { - return err - } - if unknown.APIVersion == version && unknown.Kind == kind { - pobj, ok := obj.(proto.Message) - if !ok { - return fmt.Errorf("runtime object is not a proto.Message: %v", reflect.TypeOf(obj)) - } - - return proto.Unmarshal(unknown.RawJSON, pobj) - } - - versioned, err := c.creater.New(unknown.APIVersion, unknown.Kind) - if err != nil { - return err - } - - pobj, ok := versioned.(proto.Message) - if !ok { - return fmt.Errorf("runtime object is not a proto.Message: %v", reflect.TypeOf(obj)) - } - - if err := proto.Unmarshal(unknown.RawJSON, pobj); err != nil { - return err - } - return c.convertor.Convert(versioned, obj) -} - -func (c codec) DecodeIntoWithSpecifiedVersionKind(data []byte, obj runtime.Object, kind unversioned.GroupVersionKind) error { - return fmt.Errorf("unimplemented") -} - -func (c codec) DecodeParametersInto(parameters url.Values, obj runtime.Object) error { - return fmt.Errorf("unimplemented") -} - -func (c codec) Encode(obj runtime.Object) (data []byte, err error) { - version, kind, err := c.typer.ObjectVersionAndKind(obj) - if err != nil { - return nil, err - } - if len(version) == 0 { - version = c.version - converted, err := c.convertor.ConvertToVersion(obj, version) - if err != nil { - return nil, err - } - obj = converted - } - m, ok := obj.(proto.Marshaler) - if !ok { - return nil, fmt.Errorf("object %v (kind: %s in version: %s) does not implement ProtoBuf marshalling", reflect.TypeOf(obj), kind, c.version) - } - b, err := m.Marshal() - if err != nil { - return nil, err - } - return (&runtime.Unknown{ - TypeMeta: runtime.TypeMeta{ - Kind: kind, - APIVersion: version, - }, - RawJSON: b, - }).Marshal() -} - -func (c codec) EncodeToStream(obj runtime.Object, stream io.Writer) error { - return fmt.Errorf("unimplemented") -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/scheme_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/scheme_test.go deleted file mode 100644 index 5b933d84b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/scheme_test.go +++ /dev/null @@ -1,673 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package runtime_test - -import ( - "reflect" - "testing" - - "github.com/google/gofuzz" - flag "github.com/spf13/pflag" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/conversion" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/runtime/serializer" - "k8s.io/kubernetes/pkg/util" -) - -var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.") - -type InternalSimple struct { - runtime.TypeMeta `json:",inline"` - TestString string `json:"testString"` -} - -type ExternalSimple struct { - runtime.TypeMeta `json:",inline"` - TestString string `json:"testString"` -} - -func (obj *InternalSimple) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ExternalSimple) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } - -func TestScheme(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "testExternal"} - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGV.WithKind("Simple"), &InternalSimple{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("Simple"), &ExternalSimple{}) - - // If set, would clear TypeMeta during conversion. - //scheme.AddIgnoredConversionType(&TypeMeta{}, &TypeMeta{}) - - // test that scheme is an ObjectTyper - var _ runtime.ObjectTyper = scheme - - internalToExternalCalls := 0 - externalToInternalCalls := 0 - - // Register functions to verify that scope.Meta() gets set correctly. - err := scheme.AddConversionFuncs( - func(in *InternalSimple, out *ExternalSimple, scope conversion.Scope) error { - if e, a := internalGV.String(), scope.Meta().SrcVersion; e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - if e, a := externalGV.String(), scope.Meta().DestVersion; e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - scope.Convert(&in.TypeMeta, &out.TypeMeta, 0) - scope.Convert(&in.TestString, &out.TestString, 0) - internalToExternalCalls++ - return nil - }, - func(in *ExternalSimple, out *InternalSimple, scope conversion.Scope) error { - if e, a := externalGV.String(), scope.Meta().SrcVersion; e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - if e, a := internalGV.String(), scope.Meta().DestVersion; e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - scope.Convert(&in.TypeMeta, &out.TypeMeta, 0) - scope.Convert(&in.TestString, &out.TestString, 0) - externalToInternalCalls++ - return nil - }, - ) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - codecs := serializer.NewCodecFactory(scheme) - codec := codecs.LegacyCodec(externalGV) - jsonserializer, _ := codecs.SerializerForFileExtension("json") - - simple := &InternalSimple{ - TestString: "foo", - } - - // Test Encode, Decode, DecodeInto, and DecodeToVersion - obj := runtime.Object(simple) - data, err := runtime.Encode(codec, obj) - if err != nil { - t.Fatal(err) - } - - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Fatal(err) - } - if _, ok := obj2.(*InternalSimple); !ok { - t.Fatalf("Got wrong type") - } - if e, a := simple, obj2; !reflect.DeepEqual(e, a) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", e, a) - } - - obj3 := &InternalSimple{} - if err := runtime.DecodeInto(codec, data, obj3); err != nil { - t.Fatal(err) - } - // clearing TypeMeta is a function of the scheme, which we do not test here (ConvertToVersion - // does not automatically clear TypeMeta anymore). - simple.TypeMeta = runtime.TypeMeta{Kind: "Simple", APIVersion: externalGV.String()} - if e, a := simple, obj3; !reflect.DeepEqual(e, a) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", e, a) - } - - obj4, err := runtime.Decode(jsonserializer, data) - if err != nil { - t.Fatal(err) - } - if _, ok := obj4.(*ExternalSimple); !ok { - t.Fatalf("Got wrong type") - } - - // Test Convert - external := &ExternalSimple{} - err = scheme.Convert(simple, external) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if e, a := simple.TestString, external.TestString; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - - // Encode and Convert should each have caused an increment. - if e, a := 2, internalToExternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - // DecodeInto and Decode should each have caused an increment because of a conversion - if e, a := 2, externalToInternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } -} - -func TestBadJSONRejection(t *testing.T) { - scheme := runtime.NewScheme() - codecs := serializer.NewCodecFactory(scheme) - jsonserializer, _ := codecs.SerializerForFileExtension("json") - - badJSONMissingKind := []byte(`{ }`) - if _, err := runtime.Decode(jsonserializer, badJSONMissingKind); err == nil { - t.Errorf("Did not reject despite lack of kind field: %s", badJSONMissingKind) - } - badJSONUnknownType := []byte(`{"kind": "bar"}`) - if _, err1 := runtime.Decode(jsonserializer, badJSONUnknownType); err1 == nil { - t.Errorf("Did not reject despite use of unknown type: %s", badJSONUnknownType) - } - /*badJSONKindMismatch := []byte(`{"kind": "Pod"}`) - if err2 := DecodeInto(badJSONKindMismatch, &Minion{}); err2 == nil { - t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch) - }*/ -} - -type ExtensionA struct { - runtime.TypeMeta `json:",inline"` - TestString string `json:"testString"` -} - -type ExtensionB struct { - runtime.TypeMeta `json:",inline"` - TestString string `json:"testString"` -} - -type ExternalExtensionType struct { - runtime.TypeMeta `json:",inline"` - Extension runtime.RawExtension `json:"extension"` -} - -type InternalExtensionType struct { - runtime.TypeMeta `json:",inline"` - Extension runtime.Object `json:"extension"` -} - -type ExternalOptionalExtensionType struct { - runtime.TypeMeta `json:",inline"` - Extension runtime.RawExtension `json:"extension,omitempty"` -} - -type InternalOptionalExtensionType struct { - runtime.TypeMeta `json:",inline"` - Extension runtime.Object `json:"extension,omitempty"` -} - -func (obj *ExtensionA) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ExtensionB) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ExternalExtensionType) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *InternalExtensionType) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *ExternalOptionalExtensionType) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } -func (obj *InternalOptionalExtensionType) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } - -func TestExternalToInternalMapping(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "testExternal"} - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGV.WithKind("OptionalExtensionType"), &InternalOptionalExtensionType{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("OptionalExtensionType"), &ExternalOptionalExtensionType{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - table := []struct { - obj runtime.Object - encoded string - }{ - { - &InternalOptionalExtensionType{Extension: nil}, - `{"kind":"OptionalExtensionType","apiVersion":"` + externalGV.String() + `"}`, - }, - } - - for i, item := range table { - gotDecoded, err := runtime.Decode(codec, []byte(item.encoded)) - if err != nil { - t.Errorf("unexpected error '%v' (%v)", err, item.encoded) - } else if e, a := item.obj, gotDecoded; !reflect.DeepEqual(e, a) { - t.Errorf("%d: unexpected objects:\n%s", i, util.ObjectGoPrintSideBySide(e, a)) - } - } -} - -func TestExtensionMapping(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "testExternal"} - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGV.WithKind("ExtensionType"), &InternalExtensionType{}) - scheme.AddKnownTypeWithName(internalGV.WithKind("OptionalExtensionType"), &InternalOptionalExtensionType{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("ExtensionType"), &ExternalExtensionType{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("OptionalExtensionType"), &ExternalOptionalExtensionType{}) - - // register external first when the object is the same in both schemes, so ObjectVersionAndKind reports the - // external version. - scheme.AddKnownTypeWithName(externalGV.WithKind("A"), &ExtensionA{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("B"), &ExtensionB{}) - scheme.AddKnownTypeWithName(internalGV.WithKind("A"), &ExtensionA{}) - scheme.AddKnownTypeWithName(internalGV.WithKind("B"), &ExtensionB{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - table := []struct { - obj runtime.Object - expected runtime.Object - encoded string - }{ - { - &InternalExtensionType{ - Extension: runtime.NewEncodable(codec, &ExtensionA{TestString: "foo"}), - }, - &InternalExtensionType{ - Extension: &runtime.Unknown{ - RawJSON: []byte(`{"apiVersion":"test.group/testExternal","kind":"A","testString":"foo"}`), - }, - }, - // apiVersion is set in the serialized object for easier consumption by clients - `{"apiVersion":"` + externalGV.String() + `","kind":"ExtensionType","extension":{"apiVersion":"test.group/testExternal","kind":"A","testString":"foo"}} -`, - }, { - &InternalExtensionType{Extension: runtime.NewEncodable(codec, &ExtensionB{TestString: "bar"})}, - &InternalExtensionType{ - Extension: &runtime.Unknown{ - RawJSON: []byte(`{"apiVersion":"test.group/testExternal","kind":"B","testString":"bar"}`), - }, - }, - // apiVersion is set in the serialized object for easier consumption by clients - `{"apiVersion":"` + externalGV.String() + `","kind":"ExtensionType","extension":{"apiVersion":"test.group/testExternal","kind":"B","testString":"bar"}} -`, - }, { - &InternalExtensionType{Extension: nil}, - &InternalExtensionType{ - Extension: nil, - }, - `{"apiVersion":"` + externalGV.String() + `","kind":"ExtensionType","extension":null} -`, - }, - } - - for i, item := range table { - gotEncoded, err := runtime.Encode(codec, item.obj) - if err != nil { - t.Errorf("unexpected error '%v' (%#v)", err, item.obj) - } else if e, a := item.encoded, string(gotEncoded); e != a { - t.Errorf("expected\n%#v\ngot\n%#v\n", e, a) - } - - gotDecoded, err := runtime.Decode(codec, []byte(item.encoded)) - if err != nil { - t.Errorf("unexpected error '%v' (%v)", err, item.encoded) - } else if e, a := item.expected, gotDecoded; !reflect.DeepEqual(e, a) { - t.Errorf("%d: unexpected objects:\n%s", i, util.ObjectGoPrintSideBySide(e, a)) - } - } -} - -func TestEncode(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "testExternal"} - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGV.WithKind("Simple"), &InternalSimple{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("Simple"), &ExternalSimple{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - test := &InternalSimple{ - TestString: "I'm the same", - } - obj := runtime.Object(test) - data, err := runtime.Encode(codec, obj) - obj2, gvk, err2 := codec.Decode(data, nil, nil) - if err != nil || err2 != nil { - t.Fatalf("Failure: '%v' '%v'", err, err2) - } - if _, ok := obj2.(*InternalSimple); !ok { - t.Fatalf("Got wrong type") - } - if !reflect.DeepEqual(obj2, test) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", test, obj2) - } - if !reflect.DeepEqual(gvk, &unversioned.GroupVersionKind{Group: "test.group", Version: "testExternal", Kind: "Simple"}) { - t.Errorf("unexpected gvk returned by decode: %#v", gvk) - } -} - -func TestUnversionedTypes(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "testExternal"} - otherGV := unversioned.GroupVersion{Group: "group", Version: "other"} - - scheme := runtime.NewScheme() - scheme.AddUnversionedTypes(externalGV, &InternalSimple{}) - scheme.AddKnownTypeWithName(internalGV.WithKind("Simple"), &InternalSimple{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("Simple"), &ExternalSimple{}) - scheme.AddKnownTypeWithName(otherGV.WithKind("Simple"), &ExternalSimple{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - if unv, ok := scheme.IsUnversioned(&InternalSimple{}); !unv || !ok { - t.Fatal("type not unversioned and in scheme: %t %t", unv, ok) - } - - kind, err := scheme.ObjectKind(&InternalSimple{}) - if err != nil { - t.Fatal(err) - } - if kind != externalGV.WithKind("InternalSimple") { - t.Fatalf("unexpected: %#v", kind) - } - - test := &InternalSimple{ - TestString: "I'm the same", - } - obj := runtime.Object(test) - data, err := runtime.Encode(codec, obj) - if err != nil { - t.Fatal(err) - } - obj2, gvk, err := codec.Decode(data, nil, nil) - if err != nil { - t.Fatal(err) - } - if _, ok := obj2.(*InternalSimple); !ok { - t.Fatalf("Got wrong type") - } - if !reflect.DeepEqual(obj2, test) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", test, obj2) - } - // object is serialized as an unversioned object (in the group and version it was defined in) - if !reflect.DeepEqual(gvk, &unversioned.GroupVersionKind{Group: "test.group", Version: "testExternal", Kind: "InternalSimple"}) { - t.Errorf("unexpected gvk returned by decode: %#v", gvk) - } - - // when serialized to a different group, the object is kept in its preferred name - codec = serializer.NewCodecFactory(scheme).LegacyCodec(otherGV) - data, err = runtime.Encode(codec, obj) - if err != nil { - t.Fatal(err) - } - if string(data) != `{"apiVersion":"test.group/testExternal","kind":"InternalSimple","testString":"I'm the same"}`+"\n" { - t.Errorf("unexpected data: %s", data) - } -} - -// Test a weird version/kind embedding format. -type MyWeirdCustomEmbeddedVersionKindField struct { - ID string `json:"ID,omitempty"` - APIVersion string `json:"myVersionKey,omitempty"` - ObjectKind string `json:"myKindKey,omitempty"` - Z string `json:"Z,omitempty"` - Y uint64 `json:"Y,omitempty"` -} - -type TestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]TestType2 `json:"N,omitempty"` - O *TestType2 `json:"O,omitempty"` - P []TestType2 `json:"Q,omitempty"` -} - -type TestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} - -type ExternalTestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} -type ExternalTestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]ExternalTestType2 `json:"N,omitempty"` - O *ExternalTestType2 `json:"O,omitempty"` - P []ExternalTestType2 `json:"Q,omitempty"` -} - -type ExternalInternalSame struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A TestType2 `json:"A,omitempty"` -} - -func (obj *MyWeirdCustomEmbeddedVersionKindField) GetObjectKind() unversioned.ObjectKind { return obj } -func (obj *MyWeirdCustomEmbeddedVersionKindField) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { - obj.APIVersion, obj.ObjectKind = gvk.ToAPIVersionAndKind() -} -func (obj *MyWeirdCustomEmbeddedVersionKindField) GroupVersionKind() *unversioned.GroupVersionKind { - return unversioned.FromAPIVersionAndKind(obj.APIVersion, obj.ObjectKind) -} - -func (obj *ExternalInternalSame) GetObjectKind() unversioned.ObjectKind { - return &obj.MyWeirdCustomEmbeddedVersionKindField -} - -func (obj *TestType1) GetObjectKind() unversioned.ObjectKind { - return &obj.MyWeirdCustomEmbeddedVersionKindField -} - -func (obj *ExternalTestType1) GetObjectKind() unversioned.ObjectKind { - return &obj.MyWeirdCustomEmbeddedVersionKindField -} - -func (obj *TestType2) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } -func (obj *ExternalTestType2) GetObjectKind() unversioned.ObjectKind { - return unversioned.EmptyObjectKind -} - -// TestObjectFuzzer can randomly populate all the above objects. -var TestObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 100).Funcs( - func(j *MyWeirdCustomEmbeddedVersionKindField, c fuzz.Continue) { - // We have to customize the randomization of MyWeirdCustomEmbeddedVersionKindFields because their - // APIVersion and Kind must remain blank in memory. - j.APIVersion = "" - j.ObjectKind = "" - j.ID = c.RandString() - }, -) - -// Returns a new Scheme set up with the test objects. -func GetTestScheme() *runtime.Scheme { - internalGV := unversioned.GroupVersion{Version: "__internal"} - externalGV := unversioned.GroupVersion{Version: "v1"} - - s := runtime.NewScheme() - // Ordinarily, we wouldn't add TestType2, but because this is a test and - // both types are from the same package, we need to get it into the system - // so that converter will match it with ExternalType2. - s.AddKnownTypes(internalGV, &TestType1{}, &TestType2{}, &ExternalInternalSame{}) - s.AddKnownTypes(externalGV, &ExternalInternalSame{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType2"), &ExternalTestType2{}) - s.AddKnownTypeWithName(internalGV.WithKind("TestType3"), &TestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType3"), &ExternalTestType1{}) - return s -} - -func TestKnownTypes(t *testing.T) { - s := GetTestScheme() - if len(s.KnownTypes(unversioned.GroupVersion{Group: "group", Version: "v2"})) != 0 { - t.Errorf("should have no known types for v2") - } - - types := s.KnownTypes(unversioned.GroupVersion{Version: "v1"}) - for _, s := range []string{"TestType1", "TestType2", "TestType3", "ExternalInternalSame"} { - if _, ok := types[s]; !ok { - t.Errorf("missing type %q", s) - } - } -} - -func TestConvertToVersion(t *testing.T) { - s := GetTestScheme() - tt := &TestType1{A: "I'm not a pointer object"} - other, err := s.ConvertToVersion(tt, "v1") - if err != nil { - t.Fatalf("Failure: %v", err) - } - converted, ok := other.(*ExternalTestType1) - if !ok { - t.Fatalf("Got wrong type") - } - if tt.A != converted.A { - t.Fatalf("Failed to convert object correctly: %#v", converted) - } -} - -func TestMetaValues(t *testing.T) { - internalGV := unversioned.GroupVersion{Group: "test.group", Version: "__internal"} - externalGV := unversioned.GroupVersion{Group: "test.group", Version: "externalVersion"} - - s := runtime.NewScheme() - s.AddKnownTypeWithName(internalGV.WithKind("Simple"), &InternalSimple{}) - s.AddKnownTypeWithName(externalGV.WithKind("Simple"), &ExternalSimple{}) - - internalToExternalCalls := 0 - externalToInternalCalls := 0 - - // Register functions to verify that scope.Meta() gets set correctly. - err := s.AddConversionFuncs( - func(in *InternalSimple, out *ExternalSimple, scope conversion.Scope) error { - t.Logf("internal -> external") - if e, a := internalGV.String(), scope.Meta().SrcVersion; e != a { - t.Fatalf("Expected '%v', got '%v'", e, a) - } - if e, a := externalGV.String(), scope.Meta().DestVersion; e != a { - t.Fatalf("Expected '%v', got '%v'", e, a) - } - scope.Convert(&in.TestString, &out.TestString, 0) - internalToExternalCalls++ - return nil - }, - func(in *ExternalSimple, out *InternalSimple, scope conversion.Scope) error { - t.Logf("external -> internal") - if e, a := externalGV.String(), scope.Meta().SrcVersion; e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - if e, a := internalGV.String(), scope.Meta().DestVersion; e != a { - t.Fatalf("Expected '%v', got '%v'", e, a) - } - scope.Convert(&in.TestString, &out.TestString, 0) - externalToInternalCalls++ - return nil - }, - ) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - simple := &InternalSimple{ - TestString: "foo", - } - - s.Log(t) - - out, err := s.ConvertToVersion(simple, externalGV.String()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - internal, err := s.ConvertToVersion(out, internalGV.String()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if e, a := simple, internal; !reflect.DeepEqual(e, a) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", e, a) - } - - if e, a := 1, internalToExternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - if e, a := 1, externalToInternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } -} - -func TestMetaValuesUnregisteredConvert(t *testing.T) { - type InternalSimple struct { - Version string `json:"apiVersion,omitempty"` - Kind string `json:"kind,omitempty"` - TestString string `json:"testString"` - } - type ExternalSimple struct { - Version string `json:"apiVersion,omitempty"` - Kind string `json:"kind,omitempty"` - TestString string `json:"testString"` - } - s := runtime.NewScheme() - // We deliberately don't register the types. - - internalToExternalCalls := 0 - - // Register functions to verify that scope.Meta() gets set correctly. - err := s.AddConversionFuncs( - func(in *InternalSimple, out *ExternalSimple, scope conversion.Scope) error { - if e, a := "unknown/unknown", scope.Meta().SrcVersion; e != a { - t.Fatalf("Expected '%v', got '%v'", e, a) - } - if e, a := "unknown/unknown", scope.Meta().DestVersion; e != a { - t.Fatalf("Expected '%v', got '%v'", e, a) - } - scope.Convert(&in.TestString, &out.TestString, 0) - internalToExternalCalls++ - return nil - }, - ) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - simple := &InternalSimple{TestString: "foo"} - external := &ExternalSimple{} - err = s.Convert(simple, external) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if e, a := simple.TestString, external.TestString; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - - // Verify that our conversion handler got called. - if e, a := 1, internalToExternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/codec_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/codec_test.go deleted file mode 100644 index 6c1b2ff95..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/codec_test.go +++ /dev/null @@ -1,400 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package serializer - -import ( - "encoding/json" - "fmt" - "log" - "os" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/conversion" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" - - "github.com/ghodss/yaml" - "github.com/google/gofuzz" - flag "github.com/spf13/pflag" -) - -var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.") - -type testMetaFactory struct{} - -func (testMetaFactory) Interpret(data []byte) (*unversioned.GroupVersionKind, error) { - findKind := struct { - APIVersion string `json:"myVersionKey,omitempty"` - ObjectKind string `json:"myKindKey,omitempty"` - }{} - // yaml is a superset of json, so we use it to decode here. That way, - // we understand both. - if err := yaml.Unmarshal(data, &findKind); err != nil { - return nil, fmt.Errorf("couldn't get version/kind: %v", err) - } - gv, err := unversioned.ParseGroupVersion(findKind.APIVersion) - if err != nil { - return nil, err - } - return &unversioned.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: findKind.ObjectKind}, nil -} - -// Test a weird version/kind embedding format. -type MyWeirdCustomEmbeddedVersionKindField struct { - ID string `json:"ID,omitempty"` - APIVersion string `json:"myVersionKey,omitempty"` - ObjectKind string `json:"myKindKey,omitempty"` - Z string `json:"Z,omitempty"` - Y uint64 `json:"Y,omitempty"` -} - -type TestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]TestType2 `json:"N,omitempty"` - O *TestType2 `json:"O,omitempty"` - P []TestType2 `json:"Q,omitempty"` -} - -type TestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} - -type ExternalTestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} -type ExternalTestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]ExternalTestType2 `json:"N,omitempty"` - O *ExternalTestType2 `json:"O,omitempty"` - P []ExternalTestType2 `json:"Q,omitempty"` -} - -type ExternalInternalSame struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A TestType2 `json:"A,omitempty"` -} - -// TestObjectFuzzer can randomly populate all the above objects. -var TestObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 100).Funcs( - func(j *MyWeirdCustomEmbeddedVersionKindField, c fuzz.Continue) { - c.FuzzNoCustom(j) - j.APIVersion = "" - j.ObjectKind = "" - }, -) - -func (obj *MyWeirdCustomEmbeddedVersionKindField) GetObjectKind() unversioned.ObjectKind { return obj } -func (obj *MyWeirdCustomEmbeddedVersionKindField) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { - obj.APIVersion, obj.ObjectKind = gvk.ToAPIVersionAndKind() -} -func (obj *MyWeirdCustomEmbeddedVersionKindField) GroupVersionKind() *unversioned.GroupVersionKind { - return unversioned.FromAPIVersionAndKind(obj.APIVersion, obj.ObjectKind) -} - -func (obj *ExternalInternalSame) GetObjectKind() unversioned.ObjectKind { - return &obj.MyWeirdCustomEmbeddedVersionKindField -} - -func (obj *TestType1) GetObjectKind() unversioned.ObjectKind { - return &obj.MyWeirdCustomEmbeddedVersionKindField -} - -func (obj *ExternalTestType1) GetObjectKind() unversioned.ObjectKind { - return &obj.MyWeirdCustomEmbeddedVersionKindField -} - -func (obj *TestType2) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } -func (obj *ExternalTestType2) GetObjectKind() unversioned.ObjectKind { - return unversioned.EmptyObjectKind -} - -// Returns a new Scheme set up with the test objects. -func GetTestScheme() (*runtime.Scheme, runtime.Codec) { - internalGV := unversioned.GroupVersion{Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Version: "v1"} - externalGV2 := unversioned.GroupVersion{Version: "v2"} - - s := runtime.NewScheme() - // Ordinarily, we wouldn't add TestType2, but because this is a test and - // both types are from the same package, we need to get it into the system - // so that converter will match it with ExternalType2. - s.AddKnownTypes(internalGV, &TestType1{}, &TestType2{}, &ExternalInternalSame{}) - s.AddKnownTypes(externalGV, &ExternalInternalSame{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType2"), &ExternalTestType2{}) - s.AddKnownTypeWithName(internalGV.WithKind("TestType3"), &TestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType3"), &ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV2.WithKind("TestType1"), &ExternalTestType1{}) - - s.AddUnversionedTypes(externalGV, &unversioned.Status{}) - - cf := newCodecFactory(s, testMetaFactory{}) - codec := cf.LegacyCodec(unversioned.GroupVersion{Version: "v1"}) - return s, codec -} - -func objDiff(a, b interface{}) string { - ab, err := json.Marshal(a) - if err != nil { - panic("a") - } - bb, err := json.Marshal(b) - if err != nil { - panic("b") - } - return util.StringDiff(string(ab), string(bb)) - - // An alternate diff attempt, in case json isn't showing you - // the difference. (reflect.DeepEqual makes a distinction between - // nil and empty slices, for example.) - //return util.StringDiff( - // fmt.Sprintf("%#v", a), - // fmt.Sprintf("%#v", b), - //) -} - -var semantic = conversion.EqualitiesOrDie( - func(a, b MyWeirdCustomEmbeddedVersionKindField) bool { - a.APIVersion, a.ObjectKind = "", "" - b.APIVersion, b.ObjectKind = "", "" - return a == b - }, -) - -func runTest(t *testing.T, source interface{}) { - name := reflect.TypeOf(source).Elem().Name() - TestObjectFuzzer.Fuzz(source) - - _, codec := GetTestScheme() - data, err := runtime.Encode(codec, source.(runtime.Object)) - if err != nil { - t.Errorf("%v: %v (%#v)", name, err, source) - return - } - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Errorf("%v: %v (%v)", name, err, string(data)) - return - } - if !semantic.DeepEqual(source, obj2) { - t.Errorf("1: %v: diff: %v", name, util.ObjectGoPrintSideBySide(source, obj2)) - return - } - obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface() - if err := runtime.DecodeInto(codec, data, obj3.(runtime.Object)); err != nil { - t.Errorf("2: %v: %v", name, err) - return - } - if !semantic.DeepEqual(source, obj3) { - t.Errorf("3: %v: diff: %v", name, objDiff(source, obj3)) - return - } -} - -func TestTypes(t *testing.T) { - table := []interface{}{ - &TestType1{}, - &ExternalInternalSame{}, - } - for _, item := range table { - // Try a few times, since runTest uses random values. - for i := 0; i < *fuzzIters; i++ { - runTest(t, item) - } - } -} - -func TestVersionedEncoding(t *testing.T) { - s, codec := GetTestScheme() - out, err := runtime.Encode(codec, &TestType1{}, unversioned.GroupVersion{Version: "v2"}) - if err != nil { - t.Fatal(err) - } - if string(out) != `{"myVersionKey":"v2","myKindKey":"TestType1"}`+"\n" { - t.Fatal(string(out)) - } - _, err = runtime.Encode(codec, &TestType1{}, unversioned.GroupVersion{Version: "v3"}) - if err == nil { - t.Fatal(err) - } - - cf := newCodecFactory(s, testMetaFactory{}) - encoder, _ := cf.SerializerForFileExtension("json") - - // codec that is unversioned uses the target version - unversionedCodec := cf.CodecForVersions(encoder, nil, nil) - _, err = runtime.Encode(unversionedCodec, &TestType1{}, unversioned.GroupVersion{Version: "v3"}) - if err == nil || !runtime.IsNotRegisteredError(err) { - t.Fatal(err) - } - - // unversioned encode with no versions is written directly to wire - out, err = runtime.Encode(unversionedCodec, &TestType1{}) - if err != nil { - t.Fatal(err) - } - if string(out) != `{"myVersionKey":"__internal","myKindKey":"TestType1"}`+"\n" { - t.Fatal(string(out)) - } -} - -func TestMultipleNames(t *testing.T) { - _, codec := GetTestScheme() - - obj, _, err := codec.Decode([]byte(`{"myKindKey":"TestType3","myVersionKey":"v1","A":"value"}`), nil, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - internal := obj.(*TestType1) - if internal.A != "value" { - t.Fatalf("unexpected decoded object: %#v", internal) - } - - out, err := runtime.Encode(codec, internal) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !strings.Contains(string(out), `"myKindKey":"TestType1"`) { - t.Errorf("unexpected encoded output: %s", string(out)) - } -} - -func TestConvertTypesWhenDefaultNamesMatch(t *testing.T) { - internalGV := unversioned.GroupVersion{Version: runtime.APIVersionInternal} - externalGV := unversioned.GroupVersion{Version: "v1"} - - s := runtime.NewScheme() - // create two names internally, with TestType1 being preferred - s.AddKnownTypeWithName(internalGV.WithKind("TestType1"), &TestType1{}) - s.AddKnownTypeWithName(internalGV.WithKind("OtherType1"), &TestType1{}) - // create two names externally, with TestType1 being preferred - s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("OtherType1"), &ExternalTestType1{}) - - ext := &ExternalTestType1{} - ext.APIVersion = "v1" - ext.ObjectKind = "OtherType1" - ext.A = "test" - data, err := json.Marshal(ext) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - expect := &TestType1{A: "test"} - - codec := newCodecFactory(s, testMetaFactory{}).LegacyCodec(unversioned.GroupVersion{Version: "v1"}) - - obj, err := runtime.Decode(codec, data) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !semantic.DeepEqual(expect, obj) { - t.Errorf("unexpected object: %#v", obj) - } - - into := &TestType1{} - if err := runtime.DecodeInto(codec, data, into); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !semantic.DeepEqual(expect, into) { - t.Errorf("unexpected object: %#v", obj) - } -} - -func TestEncode_Ptr(t *testing.T) { - _, codec := GetTestScheme() - tt := &TestType1{A: "I am a pointer object"} - data, err := runtime.Encode(codec, tt) - obj2, err2 := runtime.Decode(codec, data) - if err != nil || err2 != nil { - t.Fatalf("Failure: '%v' '%v'\n%s", err, err2, data) - } - if _, ok := obj2.(*TestType1); !ok { - t.Fatalf("Got wrong type") - } - if !semantic.DeepEqual(obj2, tt) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", tt, obj2) - } -} - -func TestBadJSONRejection(t *testing.T) { - log.SetOutput(os.Stderr) - _, codec := GetTestScheme() - badJSONs := [][]byte{ - []byte(`{"myVersionKey":"v1"}`), // Missing kind - []byte(`{"myVersionKey":"v1","myKindKey":"bar"}`), // Unknown kind - []byte(`{"myVersionKey":"bar","myKindKey":"TestType1"}`), // Unknown version - []byte(`{"myKindKey":"TestType1"}`), // Missing version - } - for _, b := range badJSONs { - if _, err := runtime.Decode(codec, b); err == nil { - t.Errorf("Did not reject bad json: %s", string(b)) - } - } - badJSONKindMismatch := []byte(`{"myVersionKey":"v1","myKindKey":"ExternalInternalSame"}`) - if err := runtime.DecodeInto(codec, badJSONKindMismatch, &TestType1{}); err == nil { - t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch) - } - if err := runtime.DecodeInto(codec, []byte(``), &TestType1{}); err != nil { - t.Errorf("Should allow empty decode: %v", err) - } - if _, _, err := codec.Decode([]byte(``), &unversioned.GroupVersionKind{Kind: "ExternalInternalSame"}, nil); err == nil { - t.Errorf("Did not give error for empty data with only kind default") - } - if _, _, err := codec.Decode([]byte(`{"myVersionKey":"v1"}`), &unversioned.GroupVersionKind{Kind: "ExternalInternalSame"}, nil); err != nil { - t.Errorf("Gave error for version and kind default") - } - if _, _, err := codec.Decode([]byte(`{"myKindKey":"ExternalInternalSame"}`), &unversioned.GroupVersionKind{Version: "v1"}, nil); err != nil { - t.Errorf("Gave error for version and kind default") - } - if _, _, err := codec.Decode([]byte(``), &unversioned.GroupVersionKind{Kind: "ExternalInternalSame", Version: "v1"}, nil); err != nil { - t.Errorf("Gave error for version and kind defaulted: %v", err) - } - if _, err := runtime.Decode(codec, []byte(``)); err == nil { - t.Errorf("Did not give error for empty data") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/json/json_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/json/json_test.go deleted file mode 100644 index b9e1319fa..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/json/json_test.go +++ /dev/null @@ -1,268 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package json_test - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/runtime/serializer/json" - "k8s.io/kubernetes/pkg/util" -) - -type testDecodable struct { - Other string - Value int `json:"value"` - gvk *unversioned.GroupVersionKind -} - -func (d *testDecodable) GetObjectKind() unversioned.ObjectKind { return d } -func (d *testDecodable) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { d.gvk = gvk } -func (d *testDecodable) GroupVersionKind() *unversioned.GroupVersionKind { return d.gvk } - -func TestDecode(t *testing.T) { - testCases := []struct { - creater runtime.ObjectCreater - typer runtime.Typer - yaml bool - pretty bool - - data []byte - defaultGVK *unversioned.GroupVersionKind - into runtime.Object - - errFn func(error) bool - expectedObject runtime.Object - expectedGVK *unversioned.GroupVersionKind - }{ - { - data: []byte("{}"), - - expectedGVK: &unversioned.GroupVersionKind{}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "Object 'Kind' is missing in") }, - }, - { - data: []byte("{}"), - defaultGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{err: fmt.Errorf("fake error")}, - - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - errFn: func(err error) bool { return err.Error() == "fake error" }, - }, - { - data: []byte("{}"), - defaultGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{err: fmt.Errorf("fake error")}, - - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - errFn: func(err error) bool { return err.Error() == "fake error" }, - }, - { - data: []byte("{}"), - defaultGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{ - gvk: nil, // json serializer does NOT set GVK - }, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - }, - - // version without group is not defaulted - { - data: []byte(`{"apiVersion":"blah"}`), - defaultGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{ - gvk: nil, // json serializer does NOT set GVK - }, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "", Version: "blah"}, - }, - // group without version is defaulted - { - data: []byte(`{"apiVersion":"other/"}`), - defaultGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{ - gvk: nil, // json serializer does NOT set GVK - }, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - }, - - // accept runtime.Unknown as into and bypass creator - { - data: []byte(`{}`), - into: &runtime.Unknown{}, - - expectedGVK: &unversioned.GroupVersionKind{}, - expectedObject: &runtime.Unknown{ - RawJSON: []byte(`{}`), - }, - }, - { - data: []byte(`{"test":"object"}`), - into: &runtime.Unknown{}, - - expectedGVK: &unversioned.GroupVersionKind{}, - expectedObject: &runtime.Unknown{ - RawJSON: []byte(`{"test":"object"}`), - }, - }, - { - data: []byte(`{"test":"object"}`), - into: &runtime.Unknown{}, - defaultGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &runtime.Unknown{ - TypeMeta: runtime.TypeMeta{APIVersion: "other/blah", Kind: "Test"}, - RawJSON: []byte(`{"test":"object"}`), - }, - }, - - // unregistered objects can be decoded into directly - { - data: []byte(`{"kind":"Test","apiVersion":"other/blah","value":1,"Other":"test"}`), - into: &testDecodable{}, - typer: &mockTyper{err: runtime.NewNotRegisteredErr(unversioned.GroupVersionKind{}, nil)}, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &testDecodable{ - Other: "test", - Value: 1, - }, - }, - // registered types get defaulted by the into object kind - { - data: []byte(`{"value":1,"Other":"test"}`), - into: &testDecodable{}, - typer: &mockTyper{gvk: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}}, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &testDecodable{ - Other: "test", - Value: 1, - }, - }, - // registered types get defaulted by the into object kind even without version, but return an error - { - data: []byte(`{"value":1,"Other":"test"}`), - into: &testDecodable{}, - typer: &mockTyper{gvk: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: ""}}, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: ""}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "Object 'apiVersion' is missing in") }, - expectedObject: &testDecodable{ - Other: "test", - Value: 1, - }, - }, - - // runtime.VersionedObjects are decoded - { - data: []byte(`{"value":1,"Other":"test"}`), - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - creater: &mockCreater{obj: &testDecodable{}}, - typer: &mockTyper{gvk: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}}, - defaultGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &runtime.VersionedObjects{ - Objects: []runtime.Object{ - &testDecodable{ - Other: "test", - Value: 1, - }, - }, - }, - }, - // runtime.VersionedObjects with an object are decoded into - { - data: []byte(`{"Other":"test"}`), - into: &runtime.VersionedObjects{Objects: []runtime.Object{&testDecodable{Value: 2}}}, - typer: &mockTyper{gvk: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}}, - expectedGVK: &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &runtime.VersionedObjects{ - Objects: []runtime.Object{ - &testDecodable{ - Other: "test", - Value: 2, - }, - }, - }, - }, - } - - for i, test := range testCases { - var s runtime.Serializer - if test.yaml { - s = json.NewYAMLSerializer(json.DefaultMetaFactory, test.creater, test.typer) - } else { - s = json.NewSerializer(json.DefaultMetaFactory, test.creater, test.typer, test.pretty) - } - obj, gvk, err := s.Decode([]byte(test.data), test.defaultGVK, test.into) - - if !reflect.DeepEqual(test.expectedGVK, gvk) { - t.Errorf("%d: unexpected GVK: %v", i, gvk) - } - - switch { - case err == nil && test.errFn != nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil && test.errFn == nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil: - if !test.errFn(err) { - t.Errorf("%d: failed: %v", i, err) - } - if obj != nil { - t.Errorf("%d: should have returned nil object", i) - } - continue - } - - if test.into != nil && test.into != obj { - t.Errorf("%d: expected into to be returned: %v", i, obj) - continue - } - - if !reflect.DeepEqual(test.expectedObject, obj) { - t.Errorf("%d: unexpected object:\n%s", i, util.ObjectGoPrintSideBySide(test.expectedObject, obj)) - } - } -} - -type mockCreater struct { - apiVersion string - kind string - err error - obj runtime.Object -} - -func (c *mockCreater) New(kind unversioned.GroupVersionKind) (runtime.Object, error) { - c.apiVersion, c.kind = kind.GroupVersion().String(), kind.Kind - return c.obj, c.err -} - -type mockTyper struct { - gvk *unversioned.GroupVersionKind - err error -} - -func (t *mockTyper) ObjectKind(obj runtime.Object) (*unversioned.GroupVersionKind, bool, error) { - return t.gvk, false, t.err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/json/meta_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/json/meta_test.go deleted file mode 100644 index 4b6351286..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/json/meta_test.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package json - -import "testing" - -func TestSimpleMetaFactoryInterpret(t *testing.T) { - factory := SimpleMetaFactory{} - gvk, err := factory.Interpret([]byte(`{"apiVersion":"1","kind":"object"}`)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if gvk.Version != "1" || gvk.Kind != "object" { - t.Errorf("unexpected interpret: %#v", gvk) - } - - // no kind or version - gvk, err = factory.Interpret([]byte(`{}`)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if gvk.Version != "" || gvk.Kind != "" { - t.Errorf("unexpected interpret: %#v", gvk) - } - - // unparsable - gvk, err = factory.Interpret([]byte(`{`)) - if err == nil { - t.Errorf("unexpected non-error") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/recognizer/recognizer_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/recognizer/recognizer_test.go deleted file mode 100644 index c83b87aa4..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/recognizer/recognizer_test.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package recognizer - -import ( - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/runtime/serializer/json" -) - -type A struct{} - -func (A) GetObjectKind() unversioned.ObjectKind { return unversioned.EmptyObjectKind } - -func TestRecognizer(t *testing.T) { - s := runtime.NewScheme() - s.AddKnownTypes(unversioned.GroupVersion{Version: "v1"}, &A{}) - d := NewDecoder( - json.NewSerializer(json.DefaultMetaFactory, s, runtime.ObjectTyperToTyper(s), false), - json.NewYAMLSerializer(json.DefaultMetaFactory, s, runtime.ObjectTyperToTyper(s)), - ) - out, _, err := d.Decode([]byte(` -kind: A -apiVersion: v1 -`), nil, nil) - if err != nil { - t.Fatal(err) - } - t.Logf("%#v", out) - - out, _, err = d.Decode([]byte(` -{ - "kind":"A", - "apiVersion":"v1" -} -`), nil, nil) - if err != nil { - t.Fatal(err) - } - t.Logf("%#v", out) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/versioning/versioning_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/versioning/versioning_test.go deleted file mode 100644 index 3d7eba27e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/versioning/versioning_test.go +++ /dev/null @@ -1,300 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package versioning - -import ( - "fmt" - "io" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" -) - -type testDecodable struct { - Other string - Value int `json:"value"` - gvk *unversioned.GroupVersionKind -} - -func (d *testDecodable) GetObjectKind() unversioned.ObjectKind { return d } -func (d *testDecodable) SetGroupVersionKind(gvk *unversioned.GroupVersionKind) { d.gvk = gvk } -func (d *testDecodable) GroupVersionKind() *unversioned.GroupVersionKind { return d.gvk } - -func TestDecode(t *testing.T) { - gvk1 := &unversioned.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"} - decodable1 := &testDecodable{} - decodable2 := &testDecodable{} - decodable3 := &testDecodable{} - versionedDecodable1 := &runtime.VersionedObjects{Objects: []runtime.Object{decodable1}} - - testCases := []struct { - serializer runtime.Serializer - convertor runtime.ObjectConvertor - creater runtime.ObjectCreater - copier runtime.ObjectCopier - typer runtime.Typer - yaml bool - pretty bool - - encodes, decodes []unversioned.GroupVersion - - defaultGVK *unversioned.GroupVersionKind - into runtime.Object - - errFn func(error) bool - expectedObject runtime.Object - sameObject runtime.Object - expectedGVK *unversioned.GroupVersionKind - }{ - { - serializer: &mockSerializer{actual: gvk1}, - convertor: &checkConvertor{groupVersion: "other/__internal"}, - expectedGVK: gvk1, - }, - { - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable2, groupVersion: "other/__internal"}, - expectedGVK: gvk1, - sameObject: decodable2, - }, - // defaultGVK.Group is allowed to force a conversion to the destination group - { - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - defaultGVK: &unversioned.GroupVersionKind{Group: "force"}, - convertor: &checkConvertor{in: decodable1, obj: decodable2, groupVersion: "force/__internal"}, - expectedGVK: gvk1, - sameObject: decodable2, - }, - // uses direct conversion for into when objects differ - { - into: decodable3, - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable3, directConvert: true}, - expectedGVK: gvk1, - sameObject: decodable3, - }, - { - into: versionedDecodable1, - serializer: &mockSerializer{actual: gvk1, obj: decodable3}, - convertor: &checkConvertor{in: decodable3, obj: decodable1, directConvert: true}, - expectedGVK: gvk1, - sameObject: versionedDecodable1, - }, - // returns directly when serializer returns into - { - into: decodable3, - serializer: &mockSerializer{actual: gvk1, obj: decodable3}, - expectedGVK: gvk1, - sameObject: decodable3, - }, - // returns directly when serializer returns into - { - into: versionedDecodable1, - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - expectedGVK: gvk1, - sameObject: versionedDecodable1, - }, - - // runtime.VersionedObjects are decoded - { - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - copier: &checkCopy{in: decodable1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable2, groupVersion: "other/__internal"}, - expectedGVK: gvk1, - expectedObject: &runtime.VersionedObjects{Objects: []runtime.Object{decodable1, decodable2}}, - }, - { - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - copier: &checkCopy{in: decodable1, obj: nil, err: fmt.Errorf("error on copy")}, - convertor: &checkConvertor{in: decodable1, obj: decodable2, groupVersion: "other/__internal"}, - expectedGVK: gvk1, - expectedObject: &runtime.VersionedObjects{Objects: []runtime.Object{decodable1, decodable2}}, - }, - - // decode into the same version as the serialized object - { - decodes: []unversioned.GroupVersion{gvk1.GroupVersion()}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - expectedGVK: gvk1, - expectedObject: decodable1, - }, - { - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - decodes: []unversioned.GroupVersion{gvk1.GroupVersion()}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - expectedGVK: gvk1, - expectedObject: &runtime.VersionedObjects{Objects: []runtime.Object{decodable1}}, - }, - - // codec with non matching version skips conversion altogether - { - decodes: []unversioned.GroupVersion{{Group: "something", Version: "else"}}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - expectedGVK: gvk1, - expectedObject: decodable1, - }, - { - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - decodes: []unversioned.GroupVersion{{Group: "something", Version: "else"}}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - expectedGVK: gvk1, - expectedObject: &runtime.VersionedObjects{Objects: []runtime.Object{decodable1}}, - }, - } - - for i, test := range testCases { - t.Logf("%d", i) - s := NewCodec(test.serializer, test.convertor, test.creater, test.copier, test.typer, test.encodes, test.decodes) - obj, gvk, err := s.Decode([]byte(`{}`), test.defaultGVK, test.into) - - if !reflect.DeepEqual(test.expectedGVK, gvk) { - t.Errorf("%d: unexpected GVK: %v", i, gvk) - } - - switch { - case err == nil && test.errFn != nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil && test.errFn == nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil: - if !test.errFn(err) { - t.Errorf("%d: failed: %v", i, err) - } - if obj != nil { - t.Errorf("%d: should have returned nil object", i) - } - continue - } - - if test.into != nil && test.into != obj { - t.Errorf("%d: expected into to be returned: %v", i, obj) - continue - } - - switch { - case test.expectedObject != nil: - if !reflect.DeepEqual(test.expectedObject, obj) { - t.Errorf("%d: unexpected object:\n%s", i, util.ObjectGoPrintSideBySide(test.expectedObject, obj)) - } - case test.sameObject != nil: - if test.sameObject != obj { - t.Errorf("%d: unexpected object:\n%s", i, util.ObjectGoPrintSideBySide(test.sameObject, obj)) - } - case obj != nil: - t.Errorf("%d: unexpected object: %#v", i, obj) - } - } -} - -type checkCopy struct { - in, obj runtime.Object - err error -} - -func (c *checkCopy) Copy(obj runtime.Object) (runtime.Object, error) { - if c.in != nil && c.in != obj { - return nil, fmt.Errorf("unexpected input to copy: %#v", obj) - } - return c.obj, c.err -} - -type checkConvertor struct { - err error - in, obj runtime.Object - groupVersion string - directConvert bool -} - -func (c *checkConvertor) Convert(in, out interface{}) error { - if !c.directConvert { - return fmt.Errorf("unexpected call to Convert") - } - if c.in != nil && c.in != in { - return fmt.Errorf("unexpected in: %s", in) - } - if c.obj != nil && c.obj != out { - return fmt.Errorf("unexpected out: %s", out) - } - return c.err -} -func (c *checkConvertor) ConvertToVersion(in runtime.Object, outVersion string) (out runtime.Object, err error) { - if c.directConvert { - return nil, fmt.Errorf("unexpected call to ConvertToVersion") - } - if c.in != nil && c.in != in { - return nil, fmt.Errorf("unexpected in: %s", in) - } - if c.groupVersion != outVersion { - return nil, fmt.Errorf("unexpected outversion: %s", outVersion) - } - return c.obj, c.err -} -func (c *checkConvertor) ConvertFieldLabel(version, kind, label, value string) (string, string, error) { - return "", "", fmt.Errorf("unexpected call to ConvertFieldLabel") -} - -type mockSerializer struct { - err error - obj runtime.Object - versions []unversioned.GroupVersion - - defaults, actual *unversioned.GroupVersionKind - into runtime.Object -} - -func (s *mockSerializer) Decode(data []byte, defaults *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) { - s.defaults = defaults - s.into = into - return s.obj, s.actual, s.err -} - -func (s *mockSerializer) EncodeToStream(obj runtime.Object, w io.Writer, versions ...unversioned.GroupVersion) error { - s.obj = obj - s.versions = versions - return s.err -} - -type mockCreater struct { - err error - obj runtime.Object -} - -func (c *mockCreater) New(kind unversioned.GroupVersionKind) (runtime.Object, error) { - return c.obj, c.err -} - -type mockTyper struct { - gvk *unversioned.GroupVersionKind - err error -} - -func (t *mockTyper) ObjectKind(obj runtime.Object) (*unversioned.GroupVersionKind, bool, error) { - return t.gvk, false, t.err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/yaml/yaml.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/yaml/yaml.go deleted file mode 100644 index 637c777be..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/serializer/yaml/yaml.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package yaml - -import ( - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/yaml" -) - -// yamlSerializer converts YAML passed to the Decoder methods to JSON. -type yamlSerializer struct { - // the nested serializer - runtime.Serializer -} - -// yamlSerializer implements Serializer -var _ runtime.Serializer = yamlSerializer{} - -// NewDecodingSerializer adds YAML decoding support to a serializer that supports JSON. -func NewDecodingSerializer(jsonSerializer runtime.Serializer) runtime.Serializer { - return &yamlSerializer{jsonSerializer} -} - -func (c yamlSerializer) Decode(data []byte, gvk *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) { - out, err := yaml.ToJSON(data) - if err != nil { - return nil, nil, err - } - data = out - return c.Serializer.Decode(data, gvk, into) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/swagger_doc_generator_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/swagger_doc_generator_test.go deleted file mode 100644 index 095dddff5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/swagger_doc_generator_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package runtime - -import ( - "testing" -) - -func TestFmtRawDoc(t *testing.T) { - tests := []struct { - t, expected string - }{ - {"aaa\n --- asd\n TODO: tooooodo\n toooodoooooo\n", "aaa"}, - {"aaa\nasd\n TODO: tooooodo\nbbbb\n --- toooodoooooo\n", "aaa asd bbbb"}, - {" TODO: tooooodo\n", ""}, - {"Par1\n\nPar2\n\n", "Par1\\n\\nPar2"}, - {"", ""}, - {" ", ""}, - {" \n", ""}, - {" \n\n ", ""}, - {"Example:\n\tl1\n\t\tl2\n", "Example:\\n\\tl1\\n\\t\\tl2"}, - } - - for _, test := range tests { - if o := fmtRawDoc(test.t); o != test.expected { - t.Fatalf("Expected: %q, got %q", test.expected, o) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/unstructured_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/unstructured_test.go deleted file mode 100644 index ea1d87440..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/unstructured_test.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package runtime_test - -import ( - "fmt" - "reflect" - "testing" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/runtime" -) - -func TestDecodeUnstructured(t *testing.T) { - groupVersionString := testapi.Default.GroupVersion().String() - rawJson := fmt.Sprintf(`{"kind":"Pod","apiVersion":"%s","metadata":{"name":"test"}}`, groupVersionString) - pl := &api.List{ - Items: []runtime.Object{ - &api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}}, - &runtime.Unknown{TypeMeta: runtime.TypeMeta{Kind: "Pod", APIVersion: groupVersionString}, RawJSON: []byte(rawJson)}, - &runtime.Unknown{TypeMeta: runtime.TypeMeta{Kind: "", APIVersion: groupVersionString}, RawJSON: []byte(rawJson)}, - &runtime.Unstructured{TypeMeta: runtime.TypeMeta{Kind: "Foo", APIVersion: "Bar"}, Object: map[string]interface{}{"test": "value"}}, - }, - } - if errs := runtime.DecodeList(pl.Items, runtime.UnstructuredJSONScheme); len(errs) == 1 { - t.Fatalf("unexpected error %v", errs) - } - if pod, ok := pl.Items[1].(*runtime.Unstructured); !ok || pod.Object["kind"] != "Pod" || pod.Object["metadata"].(map[string]interface{})["name"] != "test" { - t.Errorf("object not converted: %#v", pl.Items[1]) - } - if pod, ok := pl.Items[2].(*runtime.Unstructured); !ok || pod.Object["kind"] != "Pod" || pod.Object["metadata"].(map[string]interface{})["name"] != "test" { - t.Errorf("object not converted: %#v", pl.Items[2]) - } -} - -func TestDecode(t *testing.T) { - tcs := []struct { - json []byte - want runtime.Object - }{ - { - json: []byte(`{"apiVersion": "test", "kind": "test_kind"}`), - want: &runtime.Unstructured{ - TypeMeta: runtime.TypeMeta{ - APIVersion: "test", - Kind: "test_kind", - }, - Object: map[string]interface{}{"apiVersion": "test", "kind": "test_kind"}, - }, - }, - { - json: []byte(`{"apiVersion": "test", "kind": "test_list", "items": []}`), - want: &runtime.UnstructuredList{ - TypeMeta: runtime.TypeMeta{ - APIVersion: "test", - Kind: "test_list", - }, - }, - }, - { - json: []byte(`{"items": [{"metadata": {"name": "object1"}, "apiVersion": "test", "kind": "test_kind"}, {"metadata": {"name": "object2"}, "apiVersion": "test", "kind": "test_kind"}], "apiVersion": "test", "kind": "test_list"}`), - want: &runtime.UnstructuredList{ - TypeMeta: runtime.TypeMeta{ - APIVersion: "test", - Kind: "test_list", - }, - Items: []*runtime.Unstructured{ - { - TypeMeta: runtime.TypeMeta{ - APIVersion: "test", - Kind: "test_kind", - }, - Name: "object1", - Object: map[string]interface{}{ - "metadata": map[string]interface{}{"name": "object1"}, - "apiVersion": "test", - "kind": "test_kind", - }, - }, - { - TypeMeta: runtime.TypeMeta{ - APIVersion: "test", - Kind: "test_kind", - }, - Name: "object2", - Object: map[string]interface{}{ - "metadata": map[string]interface{}{"name": "object2"}, - "apiVersion": "test", - "kind": "test_kind", - }, - }, - }, - }, - }, - } - - for _, tc := range tcs { - got, _, err := runtime.UnstructuredJSONScheme.Decode(tc.json, nil, nil) - if err != nil { - t.Errorf("Unexpected error for %q: %v", string(tc.json), err) - continue - } - - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("Decode(%q) want: %v\ngot: %v", string(tc.json), tc.want, got) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/unversioned_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/unversioned_test.go deleted file mode 100644 index 7943581ea..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/runtime/unversioned_test.go +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package runtime_test - -import ( - "encoding/json" - "reflect" - "testing" - - // TODO: Ideally we should create the necessary package structure in e.g., - // pkg/conversion/test/... instead of importing pkg/api here. - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/runtime" -) - -var status = &unversioned.Status{ - Status: unversioned.StatusFailure, - Code: 200, - Reason: unversioned.StatusReasonUnknown, - Message: "", -} - -func TestV1EncodeDecodeStatus(t *testing.T) { - - v1Codec := testapi.Default.Codec() - - encoded, err := runtime.Encode(v1Codec, status) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - typeMeta := unversioned.TypeMeta{} - if err := json.Unmarshal(encoded, &typeMeta); err != nil { - t.Errorf("unexpected error: %v", err) - } - if typeMeta.Kind != "Status" { - t.Errorf("Kind is not set to \"Status\". Got %v", string(encoded)) - } - if typeMeta.APIVersion != "v1" { - t.Errorf("APIVersion is not set to \"v1\". Got %v", string(encoded)) - } - decoded, err := runtime.Decode(v1Codec, encoded) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !reflect.DeepEqual(status, decoded) { - t.Errorf("expected: %v, got: %v", status, decoded) - } -} - -func TestExperimentalEncodeDecodeStatus(t *testing.T) { - // TODO: caesarxuchao: use the testapi.Extensions.Codec() once the PR that - // moves experimental from v1 to v1beta1 got merged. - expCodec := api.Codecs.LegacyCodec(extensions.SchemeGroupVersion) - encoded, err := runtime.Encode(expCodec, status) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - typeMeta := unversioned.TypeMeta{} - if err := json.Unmarshal(encoded, &typeMeta); err != nil { - t.Errorf("unexpected error: %v", err) - } - if typeMeta.Kind != "Status" { - t.Errorf("Kind is not set to \"Status\". Got %s", encoded) - } - if typeMeta.APIVersion != "v1" { - t.Errorf("APIVersion is not set to \"\". Got %s", encoded) - } - decoded, err := runtime.Decode(expCodec, encoded) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !reflect.DeepEqual(status, decoded) { - t.Errorf("expected: %v, got: %v", status, decoded) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_scale.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/types/unix_user_id.go similarity index 77% rename from Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_scale.go rename to Godeps/_workspace/src/k8s.io/kubernetes/pkg/types/unix_user_id.go index d2cfc5f7b..b59792abf 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/client/typed/generated/extensions/unversioned/fake/fake_scale.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/types/unix_user_id.go @@ -14,10 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ -package fake +package types -// FakeScales implements ScaleInterface -type FakeScales struct { - Fake *FakeExtensions - ns string -} +// int64 is used as a safe bet against wrap-around (uid's are general +// int32) and to support uid_t -1, and -2. + +type UnixUserID int64 +type UnixGroupID int64 diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/atomic/value.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/atomic/value.go deleted file mode 100644 index a9bc8cd81..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/atomic/value.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package atomic - -import ( - "sync" -) - -// TODO(ArtfulCoder) -// sync/atomic/Value was added in golang 1.4 -// Once support is dropped for go 1.3, this type must be deprecated in favor of sync/atomic/Value. -// The functions are named Load/Store to match sync/atomic/Value function names. -type Value struct { - value interface{} - valueMutex sync.RWMutex -} - -func (at *Value) Store(val interface{}) { - at.valueMutex.Lock() - defer at.valueMutex.Unlock() - at.value = val -} - -func (at *Value) Load() interface{} { - at.valueMutex.RLock() - defer at.valueMutex.RUnlock() - return at.value -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/atomic/value_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/atomic/value_test.go deleted file mode 100644 index 052b35082..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/atomic/value_test.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package atomic - -import ( - "testing" - "time" - - "k8s.io/kubernetes/pkg/util/wait" -) - -func ExpectValue(t *testing.T, atomicValue *Value, expectedValue interface{}) { - actualValue := atomicValue.Load() - if actualValue != expectedValue { - t.Errorf("Expected to find %v, found %v", expectedValue, actualValue) - } - ch := make(chan interface{}) - go func() { - ch <- atomicValue.Load() - }() - select { - case actualValue = <-ch: - if actualValue != expectedValue { - t.Errorf("Expected to find %v, found %v", expectedValue, actualValue) - return - } - case <-time.After(wait.ForeverTestTimeout): - t.Error("Value could not be read") - return - } -} - -func TestAtomicValue(t *testing.T) { - atomicValue := &Value{} - ExpectValue(t, atomicValue, nil) - atomicValue.Store(10) - ExpectValue(t, atomicValue, 10) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/backoff.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/backoff.go index 1426590ac..275a58a22 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/backoff.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/backoff.go @@ -36,6 +36,15 @@ type Backoff struct { perItemBackoff map[string]*backoffEntry } +func NewFakeBackOff(initial, max time.Duration, tc *FakeClock) *Backoff { + return &Backoff{ + perItemBackoff: map[string]*backoffEntry{}, + Clock: tc, + defaultDuration: initial, + maxDuration: max, + } +} + func NewBackOff(initial, max time.Duration) *Backoff { return &Backoff{ perItemBackoff: map[string]*backoffEntry{}, @@ -120,6 +129,12 @@ func (p *Backoff) GC() { } } +func (p *Backoff) DeleteEntry(id string) { + p.Lock() + defer p.Unlock() + delete(p.perItemBackoff, id) +} + // Take a lock on *Backoff, before calling initEntryUnsafe func (p *Backoff) initEntryUnsafe(id string) *backoffEntry { entry := &backoffEntry{backoff: p.defaultDuration} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/backoff_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/backoff_test.go deleted file mode 100644 index d5b744cb3..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/backoff_test.go +++ /dev/null @@ -1,202 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package util - -import ( - "testing" - "time" -) - -func NewFakeBackOff(initial, max time.Duration, tc *FakeClock) *Backoff { - return &Backoff{ - perItemBackoff: map[string]*backoffEntry{}, - Clock: tc, - defaultDuration: initial, - maxDuration: max, - } -} - -func TestSlowBackoff(t *testing.T) { - id := "_idSlow" - tc := NewFakeClock(time.Now()) - step := time.Second - maxDuration := 50 * step - - b := NewFakeBackOff(step, maxDuration, tc) - cases := []time.Duration{0, 1, 2, 4, 8, 16, 32, 50, 50, 50} - for ix, c := range cases { - tc.Step(step) - w := b.Get(id) - if w != c*step { - t.Errorf("input: '%d': expected %s, got %s", ix, c*step, w) - } - b.Next(id, tc.Now()) - } - - //Now confirm that the Reset cancels backoff. - b.Next(id, tc.Now()) - b.Reset(id) - if b.Get(id) != 0 { - t.Errorf("Reset didn't clear the backoff.") - } - -} - -func TestBackoffReset(t *testing.T) { - id := "_idReset" - tc := NewFakeClock(time.Now()) - step := time.Second - maxDuration := step * 5 - b := NewFakeBackOff(step, maxDuration, tc) - startTime := tc.Now() - - // get to backoff = maxDuration - for i := 0; i <= int(maxDuration/step); i++ { - tc.Step(step) - b.Next(id, tc.Now()) - } - - // backoff should be capped at maxDuration - if !b.IsInBackOffSince(id, tc.Now()) { - t.Errorf("expected to be in Backoff got %s", b.Get(id)) - } - - lastUpdate := tc.Now() - tc.Step(2*maxDuration + step) // time += 11s, 11 > 2*maxDuration - if b.IsInBackOffSince(id, lastUpdate) { - t.Errorf("now=%s lastUpdate=%s (%s) expected Backoff reset got %s b.lastUpdate=%s", tc.Now(), startTime, tc.Now().Sub(lastUpdate), b.Get(id)) - } -} - -func TestBackoffHightWaterMark(t *testing.T) { - id := "_idHiWaterMark" - tc := NewFakeClock(time.Now()) - step := time.Second - maxDuration := 5 * step - b := NewFakeBackOff(step, maxDuration, tc) - - // get to backoff = maxDuration - for i := 0; i <= int(maxDuration/step); i++ { - tc.Step(step) - b.Next(id, tc.Now()) - } - - // backoff high watermark expires after 2*maxDuration - tc.Step(maxDuration + step) - b.Next(id, tc.Now()) - - if b.Get(id) != maxDuration { - t.Errorf("expected Backoff to stay at high watermark %s got %s", maxDuration, b.Get(id)) - } -} - -func TestBackoffGC(t *testing.T) { - id := "_idGC" - tc := NewFakeClock(time.Now()) - step := time.Second - maxDuration := 5 * step - - b := NewFakeBackOff(step, maxDuration, tc) - - for i := 0; i <= int(maxDuration/step); i++ { - tc.Step(step) - b.Next(id, tc.Now()) - } - lastUpdate := tc.Now() - tc.Step(maxDuration + step) - b.GC() - _, found := b.perItemBackoff[id] - if !found { - t.Errorf("expected GC to skip entry, elapsed time=%s maxDuration=%s", tc.Now().Sub(lastUpdate), maxDuration) - } - - tc.Step(maxDuration + step) - b.GC() - r, found := b.perItemBackoff[id] - if found { - t.Errorf("expected GC of entry after %s got entry %v", tc.Now().Sub(lastUpdate), r) - } -} - -func TestIsInBackOffSinceUpdate(t *testing.T) { - id := "_idIsInBackOffSinceUpdate" - tc := NewFakeClock(time.Now()) - step := time.Second - maxDuration := 10 * step - b := NewFakeBackOff(step, maxDuration, tc) - startTime := tc.Now() - - cases := []struct { - tick time.Duration - inBackOff bool - value int - }{ - {tick: 0, inBackOff: false, value: 0}, - {tick: 1, inBackOff: false, value: 1}, - {tick: 2, inBackOff: true, value: 2}, - {tick: 3, inBackOff: false, value: 2}, - {tick: 4, inBackOff: true, value: 4}, - {tick: 5, inBackOff: true, value: 4}, - {tick: 6, inBackOff: true, value: 4}, - {tick: 7, inBackOff: false, value: 4}, - {tick: 8, inBackOff: true, value: 8}, - {tick: 9, inBackOff: true, value: 8}, - {tick: 10, inBackOff: true, value: 8}, - {tick: 11, inBackOff: true, value: 8}, - {tick: 12, inBackOff: true, value: 8}, - {tick: 13, inBackOff: true, value: 8}, - {tick: 14, inBackOff: true, value: 8}, - {tick: 15, inBackOff: false, value: 8}, - {tick: 16, inBackOff: true, value: 10}, - {tick: 17, inBackOff: true, value: 10}, - {tick: 18, inBackOff: true, value: 10}, - {tick: 19, inBackOff: true, value: 10}, - {tick: 20, inBackOff: true, value: 10}, - {tick: 21, inBackOff: true, value: 10}, - {tick: 22, inBackOff: true, value: 10}, - {tick: 23, inBackOff: true, value: 10}, - {tick: 24, inBackOff: true, value: 10}, - {tick: 25, inBackOff: false, value: 10}, - {tick: 26, inBackOff: true, value: 10}, - {tick: 27, inBackOff: true, value: 10}, - {tick: 28, inBackOff: true, value: 10}, - {tick: 29, inBackOff: true, value: 10}, - {tick: 30, inBackOff: true, value: 10}, - {tick: 31, inBackOff: true, value: 10}, - {tick: 32, inBackOff: true, value: 10}, - {tick: 33, inBackOff: true, value: 10}, - {tick: 34, inBackOff: true, value: 10}, - {tick: 35, inBackOff: false, value: 10}, - {tick: 56, inBackOff: false, value: 0}, - {tick: 57, inBackOff: false, value: 1}, - } - - for _, c := range cases { - tc.SetTime(startTime.Add(c.tick * step)) - if c.inBackOff != b.IsInBackOffSinceUpdate(id, tc.Now()) { - t.Errorf("expected IsInBackOffSinceUpdate %v got %v at tick %s", c.inBackOff, b.IsInBackOffSinceUpdate(id, tc.Now()), c.tick*step) - } - - if c.inBackOff && (time.Duration(c.value)*step != b.Get(id)) { - t.Errorf("expected backoff value=%s got %s at tick %s", time.Duration(c.value)*step, b.Get(id), c.tick*step) - } - - if !c.inBackOff { - b.Next(id, tc.Now()) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/doc.go deleted file mode 100644 index 5ae73e8be..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package bandwidth provides utilities for bandwidth shaping -package bandwidth diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/fake_shaper.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/fake_shaper.go deleted file mode 100644 index 12798bde1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/fake_shaper.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package bandwidth - -import ( - "errors" - - "k8s.io/kubernetes/pkg/api/resource" -) - -type FakeShaper struct { - CIDRs []string - ResetCIDRs []string -} - -func (f *FakeShaper) Limit(cidr string, egress, ingress *resource.Quantity) error { - return errors.New("unimplemented") -} - -func (f *FakeShaper) Reset(cidr string) error { - f.ResetCIDRs = append(f.ResetCIDRs, cidr) - return nil -} - -func (f *FakeShaper) ReconcileInterface() error { - return errors.New("unimplemented") -} - -func (f *FakeShaper) ReconcileCIDR(cidr string, egress, ingress *resource.Quantity) error { - return errors.New("unimplemented") -} - -func (f *FakeShaper) GetCIDRs() ([]string, error) { - return f.CIDRs, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/interfaces.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/interfaces.go deleted file mode 100644 index 62b20d87d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/interfaces.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package bandwidth - -import "k8s.io/kubernetes/pkg/api/resource" - -type BandwidthShaper interface { - // Limit the bandwidth for a particular CIDR on a particular interface - // * ingress and egress are in bits/second - // * cidr is expected to be a valid network CIDR (e.g. '1.2.3.4/32' or '10.20.0.1/16') - // 'egress' bandwidth limit applies to all packets on the interface whose source matches 'cidr' - // 'ingress' bandwidth limit applies to all packets on the interface whose destination matches 'cidr' - // Limits are aggregate limits for the CIDR, not per IP address. CIDRs must be unique, but can be overlapping, traffic - // that matches multiple CIDRs counts against all limits. - Limit(cidr string, egress, ingress *resource.Quantity) error - // Remove a bandwidth limit for a particular CIDR on a particular network interface - Reset(cidr string) error - // Reconcile the interface managed by this shaper with the state on the ground. - ReconcileInterface() error - // Reconcile a CIDR managed by this shaper with the state on the ground - ReconcileCIDR(cidr string, egress, ingress *resource.Quantity) error - // GetCIDRs returns the set of CIDRs that are being managed by this shaper - GetCIDRs() ([]string, error) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/linux.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/linux.go deleted file mode 100644 index edb480c69..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/linux.go +++ /dev/null @@ -1,322 +0,0 @@ -// +build linux - -/* -Copyright 2015 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. -*/ - -package bandwidth - -import ( - "bufio" - "bytes" - "encoding/hex" - "fmt" - "net" - "strings" - - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/util/exec" - "k8s.io/kubernetes/pkg/util/sets" - - "github.com/golang/glog" -) - -// tcShaper provides an implementation of the BandwidthShaper interface on Linux using the 'tc' tool. -// In general, using this requires that the caller posses the NET_CAP_ADMIN capability, though if you -// do this within an container, it only requires the NS_CAPABLE capability for manipulations to that -// container's network namespace. -// Uses the hierarchical token bucket queuing discipline (htb), this requires Linux 2.4.20 or newer -// or a custom kernel with that queuing discipline backported. -type tcShaper struct { - e exec.Interface - iface string -} - -func NewTCShaper(iface string) BandwidthShaper { - shaper := &tcShaper{ - e: exec.New(), - iface: iface, - } - return shaper -} - -func (t *tcShaper) execAndLog(cmdStr string, args ...string) error { - glog.V(6).Infof("Running: %s %s", cmdStr, strings.Join(args, " ")) - cmd := t.e.Command(cmdStr, args...) - out, err := cmd.CombinedOutput() - glog.V(6).Infof("Output from tc: %s", string(out)) - return err -} - -func (t *tcShaper) nextClassID() (int, error) { - data, err := t.e.Command("tc", "class", "show", "dev", t.iface).CombinedOutput() - if err != nil { - return -1, err - } - - scanner := bufio.NewScanner(bytes.NewBuffer(data)) - classes := sets.String{} - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - // skip empty lines - if len(line) == 0 { - continue - } - parts := strings.Split(line, " ") - // expected tc line: - // class htb 1:1 root prio 0 rate 1000Kbit ceil 1000Kbit burst 1600b cburst 1600b - if len(parts) != 14 { - return -1, fmt.Errorf("unexpected output from tc: %s (%v)", scanner.Text(), parts) - } - classes.Insert(parts[2]) - } - - // Make sure it doesn't go forever - for nextClass := 1; nextClass < 10000; nextClass++ { - if !classes.Has(fmt.Sprintf("1:%d", nextClass)) { - return nextClass, nil - } - } - // This should really never happen - return -1, fmt.Errorf("exhausted class space, please try again") -} - -// Convert a CIDR from text to a hex representation -// Strips any masked parts of the IP, so 1.2.3.4/16 becomes hex(1.2.0.0)/ffffffff -func hexCIDR(cidr string) (string, error) { - ip, ipnet, err := net.ParseCIDR(cidr) - if err != nil { - return "", err - } - ip = ip.Mask(ipnet.Mask) - hexIP := hex.EncodeToString([]byte(ip.To4())) - hexMask := ipnet.Mask.String() - return hexIP + "/" + hexMask, nil -} - -// Convert a CIDR from hex representation to text, opposite of the above. -func asciiCIDR(cidr string) (string, error) { - parts := strings.Split(cidr, "/") - if len(parts) != 2 { - return "", fmt.Errorf("unexpected CIDR format: %s", cidr) - } - ipData, err := hex.DecodeString(parts[0]) - if err != nil { - return "", err - } - ip := net.IP(ipData) - - maskData, err := hex.DecodeString(parts[1]) - mask := net.IPMask(maskData) - size, _ := mask.Size() - - return fmt.Sprintf("%s/%d", ip.String(), size), nil -} - -func (t *tcShaper) findCIDRClass(cidr string) (class, handle string, found bool, err error) { - data, err := t.e.Command("tc", "filter", "show", "dev", t.iface).CombinedOutput() - if err != nil { - return "", "", false, err - } - - hex, err := hexCIDR(cidr) - if err != nil { - return "", "", false, err - } - spec := fmt.Sprintf("match %s", hex) - - scanner := bufio.NewScanner(bytes.NewBuffer(data)) - filter := "" - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if len(line) == 0 { - continue - } - if strings.HasPrefix(line, "filter") { - filter = line - continue - } - if strings.Contains(line, spec) { - parts := strings.Split(filter, " ") - // expected tc line: - // filter parent 1: protocol ip pref 1 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1 - if len(parts) != 19 { - return "", "", false, fmt.Errorf("unexpected output from tc: %s %d (%v)", filter, len(parts), parts) - } - return parts[18], parts[9], true, nil - } - } - return "", "", false, nil -} - -func makeKBitString(rsrc *resource.Quantity) string { - return fmt.Sprintf("%dkbit", (rsrc.Value() / 1000)) -} - -func (t *tcShaper) makeNewClass(rate string) (int, error) { - class, err := t.nextClassID() - if err != nil { - return -1, err - } - if err := t.execAndLog("tc", "class", "add", - "dev", t.iface, - "parent", "1:", - "classid", fmt.Sprintf("1:%d", class), - "htb", "rate", rate); err != nil { - return -1, err - } - return class, nil -} - -func (t *tcShaper) Limit(cidr string, upload, download *resource.Quantity) (err error) { - var downloadClass, uploadClass int - if download != nil { - if downloadClass, err = t.makeNewClass(makeKBitString(download)); err != nil { - return err - } - if err := t.execAndLog("tc", "filter", "add", - "dev", t.iface, - "protocol", "ip", - "parent", "1:0", - "prio", "1", "u32", - "match", "ip", "dst", cidr, - "flowid", fmt.Sprintf("1:%d", downloadClass)); err != nil { - return err - } - } - if upload != nil { - if uploadClass, err = t.makeNewClass(makeKBitString(upload)); err != nil { - return err - } - if err := t.execAndLog("tc", "filter", "add", - "dev", t.iface, - "protocol", "ip", - "parent", "1:0", - "prio", "1", "u32", - "match", "ip", "src", cidr, - "flowid", fmt.Sprintf("1:%d", uploadClass)); err != nil { - return err - } - } - return nil -} - -// tests to see if an interface exists, if it does, return true and the status line for the interface -// returns false, "", if an error occurs. -func (t *tcShaper) interfaceExists() (bool, string, error) { - data, err := t.e.Command("tc", "qdisc", "show", "dev", t.iface).CombinedOutput() - if err != nil { - return false, "", err - } - value := strings.TrimSpace(string(data)) - if len(value) == 0 { - return false, "", nil - } - // Newer versions of tc and/or the kernel return the following instead of nothing: - // qdisc noqueue 0: root refcnt 2 - fields := strings.Fields(value) - if len(fields) > 1 && fields[1] == "noqueue" { - return false, "", nil - } - return true, value, nil -} - -func (t *tcShaper) ReconcileCIDR(cidr string, upload, download *resource.Quantity) error { - _, _, found, err := t.findCIDRClass(cidr) - if err != nil { - return err - } - if !found { - return t.Limit(cidr, upload, download) - } - // TODO: actually check bandwidth limits here - return nil -} - -func (t *tcShaper) ReconcileInterface() error { - exists, output, err := t.interfaceExists() - if err != nil { - return err - } - if !exists { - glog.V(4).Info("Didn't find bandwidth interface, creating") - return t.initializeInterface() - } - fields := strings.Split(output, " ") - if len(fields) != 12 || fields[1] != "htb" || fields[2] != "1:" { - if err := t.deleteInterface(fields[2]); err != nil { - return err - } - return t.initializeInterface() - } - return nil -} - -func (t *tcShaper) initializeInterface() error { - return t.execAndLog("tc", "qdisc", "add", "dev", t.iface, "root", "handle", "1:", "htb", "default", "30") -} - -func (t *tcShaper) Reset(cidr string) error { - class, handle, found, err := t.findCIDRClass(cidr) - if err != nil { - return err - } - if !found { - return fmt.Errorf("Failed to find cidr: %s on interface: %s", cidr, t.iface) - } - if err := t.execAndLog("tc", "filter", "del", - "dev", t.iface, - "parent", "1:", - "proto", "ip", - "prio", "1", - "handle", handle, "u32"); err != nil { - return err - } - return t.execAndLog("tc", "class", "del", "dev", t.iface, "parent", "1:", "classid", class) -} - -func (t *tcShaper) deleteInterface(class string) error { - return t.execAndLog("tc", "qdisc", "delete", "dev", t.iface, "root", "handle", class) -} - -func (t *tcShaper) GetCIDRs() ([]string, error) { - data, err := t.e.Command("tc", "filter", "show", "dev", t.iface).CombinedOutput() - if err != nil { - return nil, err - } - - result := []string{} - scanner := bufio.NewScanner(bytes.NewBuffer(data)) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if len(line) == 0 { - continue - } - if strings.Contains(line, "match") { - parts := strings.Split(line, " ") - // expected tc line: - // match at - if len(parts) != 4 { - return nil, fmt.Errorf("unexpected output: %v", parts) - } - cidr, err := asciiCIDR(parts[1]) - if err != nil { - return nil, err - } - result = append(result, cidr) - } - } - return result, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/linux_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/linux_test.go deleted file mode 100644 index b6d2b559c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/linux_test.go +++ /dev/null @@ -1,634 +0,0 @@ -// +build linux - -/* -Copyright 2015 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. -*/ - -package bandwidth - -import ( - "errors" - "reflect" - "strings" - "testing" - - "k8s.io/kubernetes/pkg/api/resource" - "k8s.io/kubernetes/pkg/util/exec" -) - -var tcClassOutput = `class htb 1:1 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -class htb 1:2 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -class htb 1:3 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -class htb 1:4 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -` - -var tcClassOutput2 = `class htb 1:1 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -class htb 1:2 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -class htb 1:3 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -class htb 1:4 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -class htb 1:5 root prio 0 rate 10000bit ceil 10000bit burst 1600b cburst 1600b -` - -func TestNextClassID(t *testing.T) { - tests := []struct { - output string - expectErr bool - expected int - err error - }{ - { - output: tcClassOutput, - expected: 5, - }, - { - output: "\n", - expected: 1, - }, - { - expected: -1, - expectErr: true, - err: errors.New("test error"), - }, - } - for _, test := range tests { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(test.output), test.err }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { - return exec.InitFakeCmd(&fcmd, cmd, args...) - }, - }, - } - shaper := &tcShaper{e: &fexec} - class, err := shaper.nextClassID() - if test.expectErr { - if err == nil { - t.Errorf("unexpected non-error") - } - } else { - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if class != test.expected { - t.Errorf("expected: %d, found %d", test.expected, class) - } - } - } -} - -func TestHexCIDR(t *testing.T) { - tests := []struct { - input string - output string - expectErr bool - }{ - { - input: "1.2.0.0/16", - output: "01020000/ffff0000", - }, - { - input: "172.17.0.2/32", - output: "ac110002/ffffffff", - }, - { - input: "foo", - expectErr: true, - }, - } - for _, test := range tests { - output, err := hexCIDR(test.input) - if test.expectErr { - if err == nil { - t.Error("unexpected non-error") - } - } else { - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if output != test.output { - t.Errorf("expected: %s, saw: %s", test.output, output) - } - input, err := asciiCIDR(output) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if input != test.input { - t.Errorf("expected: %s, saw: %s", test.input, input) - } - } - } -} - -var tcFilterOutput = `filter parent 1: protocol ip pref 1 u32 -filter parent 1: protocol ip pref 1 u32 fh 800: ht divisor 1 -filter parent 1: protocol ip pref 1 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1 - match ac110002/ffffffff at 16 -filter parent 1: protocol ip pref 1 u32 fh 800::801 order 2049 key ht 800 bkt 0 flowid 1:2 - match 01020000/ffff0000 at 16 -` - -func TestFindCIDRClass(t *testing.T) { - tests := []struct { - cidr string - output string - expectErr bool - expectNotFound bool - expectedClass string - expectedHandle string - err error - }{ - { - cidr: "172.17.0.2/32", - output: tcFilterOutput, - expectedClass: "1:1", - expectedHandle: "800::800", - }, - { - cidr: "1.2.3.4/16", - output: tcFilterOutput, - expectedClass: "1:2", - expectedHandle: "800::801", - }, - { - cidr: "2.2.3.4/16", - output: tcFilterOutput, - expectNotFound: true, - }, - { - err: errors.New("test error"), - expectErr: true, - }, - } - for _, test := range tests { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(test.output), test.err }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { - return exec.InitFakeCmd(&fcmd, cmd, args...) - }, - }, - } - shaper := &tcShaper{e: &fexec} - class, handle, found, err := shaper.findCIDRClass(test.cidr) - if test.expectErr { - if err == nil { - t.Errorf("unexpected non-error") - } - } else { - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if test.expectNotFound { - if found { - t.Errorf("unexpectedly found an interface: %s %s", class, handle) - } - } else { - if class != test.expectedClass { - t.Errorf("expected: %s, found %s", test.expectedClass, class) - } - if handle != test.expectedHandle { - t.Errorf("expected: %s, found %s", test.expectedHandle, handle) - } - } - } - } -} - -func TestGetCIDRs(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(tcFilterOutput), nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { - return exec.InitFakeCmd(&fcmd, cmd, args...) - }, - }, - } - shaper := &tcShaper{e: &fexec} - cidrs, err := shaper.GetCIDRs() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - expectedCidrs := []string{"172.17.0.2/32", "1.2.0.0/16"} - if !reflect.DeepEqual(cidrs, expectedCidrs) { - t.Errorf("expected: %v, saw: %v", expectedCidrs, cidrs) - } -} - -func TestLimit(t *testing.T) { - tests := []struct { - cidr string - ingress *resource.Quantity - egress *resource.Quantity - expectErr bool - expectedCalls int - err error - }{ - { - cidr: "1.2.3.4/32", - ingress: resource.NewQuantity(10, resource.DecimalSI), - egress: resource.NewQuantity(20, resource.DecimalSI), - expectedCalls: 6, - }, - { - cidr: "1.2.3.4/32", - ingress: resource.NewQuantity(10, resource.DecimalSI), - egress: nil, - expectedCalls: 3, - }, - { - cidr: "1.2.3.4/32", - ingress: nil, - egress: resource.NewQuantity(20, resource.DecimalSI), - expectedCalls: 3, - }, - { - cidr: "1.2.3.4/32", - ingress: nil, - egress: nil, - expectedCalls: 0, - }, - { - err: errors.New("test error"), - ingress: resource.NewQuantity(10, resource.DecimalSI), - egress: resource.NewQuantity(20, resource.DecimalSI), - expectErr: true, - }, - } - - for _, test := range tests { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(tcClassOutput), test.err }, - func() ([]byte, error) { return []byte{}, test.err }, - func() ([]byte, error) { return []byte{}, test.err }, - func() ([]byte, error) { return []byte(tcClassOutput2), test.err }, - func() ([]byte, error) { return []byte{}, test.err }, - func() ([]byte, error) { return []byte{}, test.err }, - }, - } - - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - iface := "cbr0" - shaper := &tcShaper{e: &fexec, iface: iface} - if err := shaper.Limit(test.cidr, test.ingress, test.egress); err != nil && !test.expectErr { - t.Errorf("unexpected error: %v", err) - return - } else if err == nil && test.expectErr { - t.Error("unexpected non-error") - return - } - // No more testing in the error case - if test.expectErr { - if fcmd.CombinedOutputCalls != 1 { - t.Errorf("unexpected number of calls: %d, expected: 1", fcmd.CombinedOutputCalls) - } - return - } - - if fcmd.CombinedOutputCalls != test.expectedCalls { - t.Errorf("unexpected number of calls: %d, expected: %d", fcmd.CombinedOutputCalls, test.expectedCalls) - } - - for ix := range fcmd.CombinedOutputLog { - output := fcmd.CombinedOutputLog[ix] - if output[0] != "tc" { - t.Errorf("unexpected command: %s, expected tc", output[0]) - } - if output[4] != iface { - t.Errorf("unexpected interface: %s, expected %s (%v)", output[4], iface, output) - } - if ix == 1 { - var expectedRate string - if test.ingress != nil { - expectedRate = makeKBitString(test.ingress) - } else { - expectedRate = makeKBitString(test.egress) - } - if output[11] != expectedRate { - t.Errorf("unexpected ingress: %s, expected: %s", output[11], expectedRate) - } - if output[8] != "1:5" { - t.Errorf("unexpected class: %s, expected: %s", output[8], "1:5") - } - } - if ix == 2 { - if output[15] != test.cidr { - t.Errorf("unexpected cidr: %s, expected: %s", output[15], test.cidr) - } - if output[17] != "1:5" { - t.Errorf("unexpected class: %s, expected: %s", output[17], "1:5") - } - } - if ix == 4 { - if output[11] != makeKBitString(test.egress) { - t.Errorf("unexpected egress: %s, expected: %s", output[11], makeKBitString(test.egress)) - } - if output[8] != "1:6" { - t.Errorf("unexpected class: %s, expected: %s", output[8], "1:6") - } - } - if ix == 5 { - if output[15] != test.cidr { - t.Errorf("unexpected cidr: %s, expected: %s", output[15], test.cidr) - } - if output[17] != "1:6" { - t.Errorf("unexpected class: %s, expected: %s", output[17], "1:5") - } - } - } - } -} - -func TestReset(t *testing.T) { - tests := []struct { - cidr string - err error - expectErr bool - expectedHandle string - expectedClass string - }{ - { - cidr: "1.2.3.4/16", - expectedHandle: "800::801", - expectedClass: "1:2", - }, - { - cidr: "172.17.0.2/32", - expectedHandle: "800::800", - expectedClass: "1:1", - }, - { - err: errors.New("test error"), - expectErr: true, - }, - } - for _, test := range tests { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(tcFilterOutput), test.err }, - func() ([]byte, error) { return []byte{}, test.err }, - func() ([]byte, error) { return []byte{}, test.err }, - }, - } - - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - iface := "cbr0" - shaper := &tcShaper{e: &fexec, iface: iface} - - if err := shaper.Reset(test.cidr); err != nil && !test.expectErr { - t.Errorf("unexpected error: %v", err) - return - } else if test.expectErr && err == nil { - t.Error("unexpected non-error") - return - } - - // No more testing in the error case - if test.expectErr { - if fcmd.CombinedOutputCalls != 1 { - t.Errorf("unexpected number of calls: %d, expected: 1", fcmd.CombinedOutputCalls) - } - return - } - - if fcmd.CombinedOutputCalls != 3 { - t.Errorf("unexpected number of calls: %d, expected: 3", fcmd.CombinedOutputCalls) - } - - for ix := range fcmd.CombinedOutputLog { - output := fcmd.CombinedOutputLog[ix] - if output[0] != "tc" { - t.Errorf("unexpected command: %s, expected tc", output[0]) - } - if output[4] != iface { - t.Errorf("unexpected interface: %s, expected %s (%v)", output[4], iface, output) - } - if ix == 1 && output[12] != test.expectedHandle { - t.Errorf("unexpected handle: %s, expected: %s", output[12], test.expectedHandle) - } - if ix == 2 && output[8] != test.expectedClass { - t.Errorf("unexpected class: %s, expected: %s", output[8], test.expectedClass) - } - } - } -} - -var tcQdisc = "qdisc htb 1: root refcnt 2 r2q 10 default 30 direct_packets_stat 0\n" - -func TestReconcileInterfaceExists(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(tcQdisc), nil }, - }, - } - - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - iface := "cbr0" - shaper := &tcShaper{e: &fexec, iface: iface} - err := shaper.ReconcileInterface() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if fcmd.CombinedOutputCalls != 1 { - t.Errorf("unexpected number of calls: %d", fcmd.CombinedOutputCalls) - } - - output := fcmd.CombinedOutputLog[0] - if len(output) != 5 { - t.Errorf("unexpected command: %v", output) - } - if output[0] != "tc" { - t.Errorf("unexpected command: %s", output[0]) - } - if output[4] != iface { - t.Errorf("unexpected interface: %s, expected %s", output[4], iface) - } - if output[2] != "show" { - t.Errorf("unexpected action: %s", output[2]) - } -} - -func testReconcileInterfaceHasNoData(t *testing.T, output string) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(output), nil }, - func() ([]byte, error) { return []byte(output), nil }, - }, - } - - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - iface := "cbr0" - shaper := &tcShaper{e: &fexec, iface: iface} - err := shaper.ReconcileInterface() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("unexpected number of calls: %d", fcmd.CombinedOutputCalls) - } - - for ix, output := range fcmd.CombinedOutputLog { - if output[0] != "tc" { - t.Errorf("unexpected command: %s", output[0]) - } - if output[4] != iface { - t.Errorf("unexpected interface: %s, expected %s", output[4], iface) - } - if ix == 0 { - if len(output) != 5 { - t.Errorf("unexpected command: %v", output) - } - if output[2] != "show" { - t.Errorf("unexpected action: %s", output[2]) - } - } - if ix == 1 { - if len(output) != 11 { - t.Errorf("unexpected command: %v", output) - } - if output[2] != "add" { - t.Errorf("unexpected action: %s", output[2]) - } - if output[7] != "1:" { - t.Errorf("unexpected root class: %s", output[7]) - } - if output[8] != "htb" { - t.Errorf("unexpected qdisc algo: %s", output[8]) - } - } - } -} - -func TestReconcileInterfaceDoesntExist(t *testing.T) { - testReconcileInterfaceHasNoData(t, "\n") -} - -var tcQdiscNoqueue = "qdisc noqueue 0: root refcnt 2 \n" - -func TestReconcileInterfaceExistsWithNoqueue(t *testing.T) { - testReconcileInterfaceHasNoData(t, tcQdiscNoqueue) -} - -var tcQdiscWrong = []string{ - "qdisc htb 2: root refcnt 2 r2q 10 default 30 direct_packets_stat 0\n", - "qdisc foo 1: root refcnt 2 r2q 10 default 30 direct_packets_stat 0\n", -} - -func TestReconcileInterfaceIsWrong(t *testing.T) { - for _, test := range tcQdiscWrong { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(test), nil }, - func() ([]byte, error) { return []byte("\n"), nil }, - func() ([]byte, error) { return []byte("\n"), nil }, - }, - } - - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - iface := "cbr0" - shaper := &tcShaper{e: &fexec, iface: iface} - err := shaper.ReconcileInterface() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if fcmd.CombinedOutputCalls != 3 { - t.Errorf("unexpected number of calls: %d", fcmd.CombinedOutputCalls) - } - - for ix, output := range fcmd.CombinedOutputLog { - if output[0] != "tc" { - t.Errorf("unexpected command: %s", output[0]) - } - if output[4] != iface { - t.Errorf("unexpected interface: %s, expected %s", output[4], iface) - } - if ix == 0 { - if len(output) != 5 { - t.Errorf("unexpected command: %v", output) - } - if output[2] != "show" { - t.Errorf("unexpected action: %s", output[2]) - } - } - if ix == 1 { - if len(output) != 8 { - t.Errorf("unexpected command: %v", output) - } - if output[2] != "delete" { - t.Errorf("unexpected action: %s", output[2]) - } - if output[7] != strings.Split(test, " ")[2] { - t.Errorf("unexpected class: %s, expected: %s", output[7], strings.Split(test, " ")[2]) - } - } - if ix == 2 { - if len(output) != 11 { - t.Errorf("unexpected command: %v", output) - } - if output[7] != "1:" { - t.Errorf("unexpected root class: %s", output[7]) - } - if output[8] != "htb" { - t.Errorf("unexpected qdisc algo: %s", output[8]) - } - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/unsupported.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/unsupported.go deleted file mode 100644 index 7f980a265..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/bandwidth/unsupported.go +++ /dev/null @@ -1,52 +0,0 @@ -// +build !linux - -/* -Copyright 2015 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. -*/ - -package bandwidth - -import ( - "errors" - - "k8s.io/kubernetes/pkg/api/resource" -) - -type unsupportedShaper struct { -} - -func NewTCShaper(iface string) BandwidthShaper { - return &unsupportedShaper{} -} - -func (f *unsupportedShaper) Limit(cidr string, egress, ingress *resource.Quantity) error { - return errors.New("unimplemented") -} - -func (f *unsupportedShaper) Reset(cidr string) error { - return nil -} - -func (f *unsupportedShaper) ReconcileInterface() error { - return errors.New("unimplemented") -} - -func (f *unsupportedShaper) ReconcileCIDR(cidr string, egress, ingress *resource.Quantity) error { - return errors.New("unimplemented") -} - -func (f *unsupportedShaper) GetCIDRs() ([]string, error) { - return []string{}, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/cache_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/cache_test.go deleted file mode 100644 index a54f9e609..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/cache_test.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package util - -import ( - "testing" -) - -const ( - maxTestCacheSize int = shardsCount * 2 -) - -func ExpectEntry(t *testing.T, cache Cache, index uint64, expectedValue interface{}) { - elem, found := cache.Get(index) - if !found { - t.Error("Expected to find entry with key 1") - } else if elem != expectedValue { - t.Errorf("Expected to find %v, got %v", expectedValue, elem) - } -} - -func TestBasic(t *testing.T) { - cache := NewCache(maxTestCacheSize) - cache.Add(1, "xxx") - ExpectEntry(t, cache, 1, "xxx") -} - -func TestOverflow(t *testing.T) { - cache := NewCache(maxTestCacheSize) - for i := 0; i < maxTestCacheSize+1; i++ { - cache.Add(uint64(i), "xxx") - } - foundIndexes := make([]uint64, 0) - for i := 0; i < maxTestCacheSize+1; i++ { - _, found := cache.Get(uint64(i)) - if found { - foundIndexes = append(foundIndexes, uint64(i)) - } - } - if len(foundIndexes) != maxTestCacheSize { - t.Errorf("Expect to find %d elements, got %d %v", maxTestCacheSize, len(foundIndexes), foundIndexes) - } -} - -func TestOverwrite(t *testing.T) { - cache := NewCache(maxTestCacheSize) - cache.Add(1, "xxx") - ExpectEntry(t, cache, 1, "xxx") - cache.Add(1, "yyy") - ExpectEntry(t, cache, 1, "yyy") -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chmod/chmod.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chmod/chmod.go deleted file mode 100644 index 5b646c95b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chmod/chmod.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package chmod - -import ( - "os" -) - -// Interface is something that knows how to run the chmod system call. -// It is non-recursive. -type Interface interface { - // Chmod changes the mode of the given file, implementing the same - // semantics as os.Chmod. - Chmod(path string, filemode os.FileMode) error -} - -func New() Interface { - return &chmodRunner{} -} - -type chmodRunner struct{} - -func (_ *chmodRunner) Chmod(path string, mode os.FileMode) error { - return os.Chmod(path, mode) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chmod/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chmod/doc.go deleted file mode 100644 index a230e98fd..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chmod/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package chown provides an interface and implementations -// for things that run run the chmod system call. -package chmod diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chown/chown.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chown/chown.go deleted file mode 100644 index 0d90629de..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/chown/chown.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package chown - -import ( - "os" -) - -// Interface is something that knows how to run the chown system call. -// It is non-recursive. -type Interface interface { - // Chown changes the owning UID and GID of a file, implementing - // the exact same semantics as os.Chown. - Chown(path string, uid, gid int) error -} - -func New() Interface { - return &chownRunner{} -} - -type chownRunner struct{} - -func (_ *chownRunner) Chown(path string, uid, gid int) error { - return os.Chown(path, uid, gid) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock.go index 56ea16c69..ac2d738d6 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock.go @@ -27,6 +27,7 @@ type Clock interface { Now() time.Time Since(time.Time) time.Duration After(d time.Duration) <-chan time.Time + Sleep(d time.Duration) } var ( @@ -53,6 +54,10 @@ func (RealClock) After(d time.Duration) <-chan time.Time { return time.After(d) } +func (RealClock) Sleep(d time.Duration) { + time.Sleep(d) +} + // FakeClock implements Clock, but returns an arbitrary time. type FakeClock struct { lock sync.RWMutex @@ -137,6 +142,10 @@ func (f *FakeClock) HasWaiters() bool { return len(f.waiters) > 0 } +func (f *FakeClock) Sleep(d time.Duration) { + f.Step(d) +} + // IntervalClock implements Clock, but each invocation of Now steps the clock forward the specified duration type IntervalClock struct { Time time.Time @@ -159,3 +168,7 @@ func (i *IntervalClock) Since(ts time.Time) time.Duration { func (*IntervalClock) After(d time.Duration) <-chan time.Time { panic("IntervalClock doesn't implement After") } + +func (*IntervalClock) Sleep(d time.Duration) { + panic("IntervalClock doesn't implement Sleep") +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock_test.go deleted file mode 100644 index db0cce40a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/clock_test.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package util - -import ( - "testing" - "time" -) - -func TestFakeClock(t *testing.T) { - startTime := time.Now() - tc := NewFakeClock(startTime) - tc.Step(time.Second) - now := tc.Now() - if now.Sub(startTime) != time.Second { - t.Errorf("input: %s now=%s gap=%s expected=%s", startTime, now, now.Sub(startTime), time.Second) - } - - tt := tc.Now() - tc.SetTime(tt.Add(time.Hour)) - if tc.Now().Sub(tt) != time.Hour { - t.Errorf("input: %s now=%s gap=%s expected=%s", tt, tc.Now(), tc.Now().Sub(tt), time.Hour) - } -} - -func TestFakeAfter(t *testing.T) { - tc := NewFakeClock(time.Now()) - if tc.HasWaiters() { - t.Errorf("unexpected waiter?") - } - oneSec := tc.After(time.Second) - if !tc.HasWaiters() { - t.Errorf("unexpected lack of waiter?") - } - - oneOhOneSec := tc.After(time.Second + time.Millisecond) - twoSec := tc.After(2 * time.Second) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(999 * time.Millisecond) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(time.Millisecond) - select { - case <-oneSec: - // Expected! - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } - tc.Step(time.Millisecond) - select { - case <-oneSec: - // should not double-trigger! - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - // Expected! - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/config.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/config.go deleted file mode 100644 index 37f6f6ab1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/config.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "sync" - - "k8s.io/kubernetes/pkg/util/wait" -) - -type Merger interface { - // Invoked when a change from a source is received. May also function as an incremental - // merger if you wish to consume changes incrementally. Must be reentrant when more than - // one source is defined. - Merge(source string, update interface{}) error -} - -// MergeFunc implements the Merger interface -type MergeFunc func(source string, update interface{}) error - -func (f MergeFunc) Merge(source string, update interface{}) error { - return f(source, update) -} - -// Mux is a class for merging configuration from multiple sources. Changes are -// pushed via channels and sent to the merge function. -type Mux struct { - // Invoked when an update is sent to a source. - merger Merger - - // Sources and their lock. - sourceLock sync.RWMutex - // Maps source names to channels - sources map[string]chan interface{} -} - -// NewMux creates a new mux that can merge changes from multiple sources. -func NewMux(merger Merger) *Mux { - mux := &Mux{ - sources: make(map[string]chan interface{}), - merger: merger, - } - return mux -} - -// Channel returns a channel where a configuration source -// can send updates of new configurations. Multiple calls with the same -// source will return the same channel. This allows change and state based sources -// to use the same channel. Different source names however will be treated as a -// union. -func (m *Mux) Channel(source string) chan interface{} { - if len(source) == 0 { - panic("Channel given an empty name") - } - m.sourceLock.Lock() - defer m.sourceLock.Unlock() - channel, exists := m.sources[source] - if exists { - return channel - } - newChannel := make(chan interface{}) - m.sources[source] = newChannel - go wait.Until(func() { m.listen(source, newChannel) }, 0, wait.NeverStop) - return newChannel -} - -func (m *Mux) listen(source string, listenChannel <-chan interface{}) { - for update := range listenChannel { - m.merger.Merge(source, update) - } -} - -// Accessor is an interface for retrieving the current merge state. -type Accessor interface { - // MergedState returns a representation of the current merge state. - // Must be reentrant when more than one source is defined. - MergedState() interface{} -} - -// AccessorFunc implements the Accessor interface. -type AccessorFunc func() interface{} - -func (f AccessorFunc) MergedState() interface{} { - return f() -} - -type Listener interface { - // OnUpdate is invoked when a change is made to an object. - OnUpdate(instance interface{}) -} - -// ListenerFunc receives a representation of the change or object. -type ListenerFunc func(instance interface{}) - -func (f ListenerFunc) OnUpdate(instance interface{}) { - f(instance) -} - -type Broadcaster struct { - // Listeners for changes and their lock. - listenerLock sync.RWMutex - listeners []Listener -} - -// NewBroadcaster registers a set of listeners that support the Listener interface -// and notifies them all on changes. -func NewBroadcaster() *Broadcaster { - return &Broadcaster{} -} - -// Add registers listener to receive updates of changes. -func (b *Broadcaster) Add(listener Listener) { - b.listenerLock.Lock() - defer b.listenerLock.Unlock() - b.listeners = append(b.listeners, listener) -} - -// Notify notifies all listeners. -func (b *Broadcaster) Notify(instance interface{}) { - b.listenerLock.RLock() - listeners := b.listeners - b.listenerLock.RUnlock() - for _, listener := range listeners { - listener.OnUpdate(instance) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/config_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/config_test.go deleted file mode 100644 index 4ebab7bf9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/config_test.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package config - -import ( - "reflect" - "testing" -) - -func TestConfigurationChannels(t *testing.T) { - mux := NewMux(nil) - channelOne := mux.Channel("one") - if channelOne != mux.Channel("one") { - t.Error("Didn't get the same muxuration channel back with the same name") - } - channelTwo := mux.Channel("two") - if channelOne == channelTwo { - t.Error("Got back the same muxuration channel for different names") - } -} - -type MergeMock struct { - source string - update interface{} - t *testing.T -} - -func (m MergeMock) Merge(source string, update interface{}) error { - if m.source != source { - m.t.Errorf("Expected %s, Got %s", m.source, source) - } - if !reflect.DeepEqual(m.update, update) { - m.t.Errorf("Expected %s, Got %s", m.update, update) - } - return nil -} - -func TestMergeInvoked(t *testing.T) { - merger := MergeMock{"one", "test", t} - mux := NewMux(&merger) - mux.Channel("one") <- "test" -} - -func TestMergeFuncInvoked(t *testing.T) { - ch := make(chan bool) - mux := NewMux(MergeFunc(func(source string, update interface{}) error { - if source != "one" { - t.Errorf("Expected %s, Got %s", "one", source) - } - if update.(string) != "test" { - t.Errorf("Expected %s, Got %s", "test", update) - } - ch <- true - return nil - })) - mux.Channel("one") <- "test" - <-ch -} - -func TestSimultaneousMerge(t *testing.T) { - ch := make(chan bool, 2) - mux := NewMux(MergeFunc(func(source string, update interface{}) error { - switch source { - case "one": - if update.(string) != "test" { - t.Errorf("Expected %s, Got %s", "test", update) - } - case "two": - if update.(string) != "test2" { - t.Errorf("Expected %s, Got %s", "test2", update) - } - default: - t.Errorf("Unexpected source, Got %s", update) - } - ch <- true - return nil - })) - source := mux.Channel("one") - source2 := mux.Channel("two") - source <- "test" - source2 <- "test2" - <-ch - <-ch -} - -func TestBroadcaster(t *testing.T) { - b := NewBroadcaster() - b.Notify(struct{}{}) - - ch := make(chan bool, 2) - b.Add(ListenerFunc(func(object interface{}) { - if object != "test" { - t.Errorf("Expected %s, Got %s", "test", object) - } - ch <- true - })) - b.Add(ListenerFunc(func(object interface{}) { - if object != "test" { - t.Errorf("Expected %s, Got %s", "test", object) - } - ch <- true - })) - b.Notify("test") - <-ch - <-ch -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/doc.go deleted file mode 100644 index 697f3ab56..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/config/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package config provides utility objects for decoupling sources of configuration and the -// actual configuration state. Consumers must implement the Merger interface to unify -// the sources of change into an object. -package config diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/dbus.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/dbus.go deleted file mode 100644 index 13da1469e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/dbus.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package dbus - -import ( - godbus "github.com/godbus/dbus" -) - -// Interface is an interface that presents a subset of the godbus/dbus API. Use this -// when you want to inject fakeable/mockable D-Bus behavior. -type Interface interface { - // SystemBus returns a connection to the system bus, connecting to it - // first if necessary - SystemBus() (Connection, error) - // SessionBus returns a connection to the session bus, connecting to it - // first if necessary - SessionBus() (Connection, error) -} - -// Connection represents a D-Bus connection -type Connection interface { - // Returns an Object representing the bus itself - BusObject() Object - - // Object creates a representation of a remote D-Bus object - Object(name, path string) Object - - // Signal registers or unregisters a channel to receive D-Bus signals - Signal(ch chan<- *godbus.Signal) -} - -// Object represents a remote D-Bus object -type Object interface { - // Call synchronously calls a D-Bus method - Call(method string, flags godbus.Flags, args ...interface{}) Call -} - -// Call represents a pending or completed D-Bus method call -type Call interface { - // Store returns a completed call's return values, or an error - Store(retvalues ...interface{}) error -} - -// Implements Interface in terms of actually talking to D-Bus -type dbusImpl struct { - systemBus *connImpl - sessionBus *connImpl -} - -// Implements Connection as a godbus.Conn -type connImpl struct { - conn *godbus.Conn -} - -// Implements Object as a godbus.Object -type objectImpl struct { - object godbus.BusObject -} - -// Implements Call as a godbus.Call -type callImpl struct { - call *godbus.Call -} - -// New returns a new Interface which will use godbus to talk to D-Bus -func New() Interface { - return &dbusImpl{} -} - -// SystemBus is part of Interface -func (db *dbusImpl) SystemBus() (Connection, error) { - if db.systemBus == nil { - bus, err := godbus.SystemBus() - if err != nil { - return nil, err - } - db.systemBus = &connImpl{bus} - } - - return db.systemBus, nil -} - -// SessionBus is part of Interface -func (db *dbusImpl) SessionBus() (Connection, error) { - if db.sessionBus == nil { - bus, err := godbus.SessionBus() - if err != nil { - return nil, err - } - db.sessionBus = &connImpl{bus} - } - - return db.sessionBus, nil -} - -// BusObject is part of the Connection interface -func (conn *connImpl) BusObject() Object { - return &objectImpl{conn.conn.BusObject()} -} - -// Object is part of the Connection interface -func (conn *connImpl) Object(name, path string) Object { - return &objectImpl{conn.conn.Object(name, godbus.ObjectPath(path))} -} - -// Signal is part of the Connection interface -func (conn *connImpl) Signal(ch chan<- *godbus.Signal) { - conn.conn.Signal(ch) -} - -// Call is part of the Object interface -func (obj *objectImpl) Call(method string, flags godbus.Flags, args ...interface{}) Call { - return &callImpl{obj.object.Call(method, flags, args...)} -} - -// Store is part of the Call interface -func (call *callImpl) Store(retvalues ...interface{}) error { - return call.call.Store(retvalues...) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/dbus_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/dbus_test.go deleted file mode 100644 index 3cf52263a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/dbus_test.go +++ /dev/null @@ -1,249 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package dbus - -import ( - "fmt" - "os" - "testing" - - godbus "github.com/godbus/dbus" -) - -const ( - DBusNameFlagAllowReplacement uint32 = 1 << (iota + 1) - DBusNameFlagReplaceExisting - DBusNameFlagDoNotQueue -) - -const ( - DBusRequestNameReplyPrimaryOwner uint32 = iota + 1 - DBusRequestNameReplyInQueue - DBusRequestNameReplyExists - DBusRequestNameReplyAlreadyOwner -) - -const ( - DBusReleaseNameReplyReleased uint32 = iota + 1 - DBusReleaseNameReplyNonExistent - DBusReleaseNameReplyNotOwner -) - -func doDBusTest(t *testing.T, dbus Interface, real bool) { - bus, err := dbus.SystemBus() - if err != nil { - if !real { - t.Errorf("dbus.SystemBus() failed with fake Interface") - } - t.Skipf("D-Bus is not running: %v", err) - } - busObj := bus.BusObject() - - id := "" - err = busObj.Call("org.freedesktop.DBus.GetId", 0).Store(&id) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if len(id) == 0 { - t.Errorf("expected non-empty Id, got \"\"") - } - - // Switch to the session bus for the rest, since the system bus is more - // locked down (and thus harder to trick into emitting signals). - - bus, err = dbus.SessionBus() - if err != nil { - if !real { - t.Errorf("dbus.SystemBus() failed with fake Interface") - } - t.Skipf("D-Bus session bus is not available: %v", err) - } - busObj = bus.BusObject() - - name := fmt.Sprintf("io.kubernetes.dbus_test_%d", os.Getpid()) - owner := "" - err = busObj.Call("org.freedesktop.DBus.GetNameOwner", 0, name).Store(&owner) - if err == nil { - t.Errorf("expected '%s' to be un-owned, but found owner %s", name, owner) - } - dbuserr, ok := err.(godbus.Error) - if !ok { - t.Errorf("expected godbus.Error, but got %#v", err) - } - if dbuserr.Name != "org.freedesktop.DBus.Error.NameHasNoOwner" { - t.Errorf("expected NameHasNoOwner error but got %v", err) - } - - sigchan := make(chan *godbus.Signal, 10) - bus.Signal(sigchan) - - rule := fmt.Sprintf("type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus',arg0='%s'", name) - err = busObj.Call("org.freedesktop.DBus.AddMatch", 0, rule).Store() - if err != nil { - t.Errorf("expected success, got %v", err) - } - - var ret uint32 - err = busObj.Call("org.freedesktop.DBus.RequestName", 0, name, DBusNameFlagDoNotQueue).Store(&ret) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if ret != DBusRequestNameReplyPrimaryOwner { - t.Errorf("expected %v, got %v", DBusRequestNameReplyPrimaryOwner, ret) - } - - err = busObj.Call("org.freedesktop.DBus.GetNameOwner", 0, name).Store(&owner) - if err != nil { - t.Errorf("expected success, got %v", err) - } - - var changedSignal, acquiredSignal, lostSignal *godbus.Signal - - sig1 := <-sigchan - sig2 := <-sigchan - // We get two signals, but the order isn't guaranteed - if sig1.Name == "org.freedesktop.DBus.NameOwnerChanged" { - changedSignal = sig1 - acquiredSignal = sig2 - } else { - acquiredSignal = sig1 - changedSignal = sig2 - } - - if acquiredSignal.Sender != "org.freedesktop.DBus" || acquiredSignal.Name != "org.freedesktop.DBus.NameAcquired" { - t.Errorf("expected NameAcquired signal, got %v", acquiredSignal) - } - acquiredName := acquiredSignal.Body[0].(string) - if acquiredName != name { - t.Errorf("unexpected NameAcquired arguments: %v", acquiredSignal) - } - - if changedSignal.Sender != "org.freedesktop.DBus" || changedSignal.Name != "org.freedesktop.DBus.NameOwnerChanged" { - t.Errorf("expected NameOwnerChanged signal, got %v", changedSignal) - } - - changedName := changedSignal.Body[0].(string) - oldOwner := changedSignal.Body[1].(string) - newOwner := changedSignal.Body[2].(string) - if changedName != name || oldOwner != "" || newOwner != owner { - t.Errorf("unexpected NameOwnerChanged arguments: %v", changedSignal) - } - - err = busObj.Call("org.freedesktop.DBus.ReleaseName", 0, name).Store(&ret) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if ret != DBusReleaseNameReplyReleased { - t.Errorf("expected %v, got %v", DBusReleaseNameReplyReleased, ret) - } - - sig1 = <-sigchan - sig2 = <-sigchan - if sig1.Name == "org.freedesktop.DBus.NameOwnerChanged" { - changedSignal = sig1 - lostSignal = sig2 - } else { - lostSignal = sig1 - changedSignal = sig2 - } - - if lostSignal.Sender != "org.freedesktop.DBus" || lostSignal.Name != "org.freedesktop.DBus.NameLost" { - t.Errorf("expected NameLost signal, got %v", lostSignal) - } - lostName := lostSignal.Body[0].(string) - if lostName != name { - t.Errorf("unexpected NameLost arguments: %v", lostSignal) - } - - if changedSignal.Sender != "org.freedesktop.DBus" || changedSignal.Name != "org.freedesktop.DBus.NameOwnerChanged" { - t.Errorf("expected NameOwnerChanged signal, got %v", changedSignal) - } - - changedName = changedSignal.Body[0].(string) - oldOwner = changedSignal.Body[1].(string) - newOwner = changedSignal.Body[2].(string) - if changedName != name || oldOwner != owner || newOwner != "" { - t.Errorf("unexpected NameOwnerChanged arguments: %v", changedSignal) - } - - if len(sigchan) != 0 { - t.Errorf("unexpected extra signals (%d)", len(sigchan)) - } - - // Unregister sigchan - bus.Signal(sigchan) -} - -func TestRealDBus(t *testing.T) { - dbus := New() - doDBusTest(t, dbus, true) -} - -func TestFakeDBus(t *testing.T) { - uniqueName := ":1.1" - ownedName := "" - - fakeSystem := NewFakeConnection() - fakeSystem.SetBusObject( - func(method string, args ...interface{}) ([]interface{}, error) { - if method == "org.freedesktop.DBus.GetId" { - return []interface{}{"foo"}, nil - } - return nil, fmt.Errorf("unexpected method call '%s'", method) - }, - ) - - fakeSession := NewFakeConnection() - fakeSession.SetBusObject( - func(method string, args ...interface{}) ([]interface{}, error) { - if method == "org.freedesktop.DBus.GetNameOwner" { - checkName := args[0].(string) - if checkName != ownedName { - return nil, godbus.Error{"org.freedesktop.DBus.Error.NameHasNoOwner", nil} - } else { - return []interface{}{uniqueName}, nil - } - } else if method == "org.freedesktop.DBus.RequestName" { - reqName := args[0].(string) - _ = args[1].(uint32) - if ownedName != "" { - return []interface{}{DBusRequestNameReplyAlreadyOwner}, nil - } - ownedName = reqName - fakeSession.EmitSignal("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameAcquired", reqName) - fakeSession.EmitSignal("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged", reqName, "", uniqueName) - return []interface{}{DBusRequestNameReplyPrimaryOwner}, nil - } else if method == "org.freedesktop.DBus.ReleaseName" { - reqName := args[0].(string) - if reqName != ownedName { - return []interface{}{DBusReleaseNameReplyNotOwner}, nil - } - ownedName = "" - fakeSession.EmitSignal("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged", reqName, uniqueName, "") - fakeSession.EmitSignal("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameLost", reqName) - return []interface{}{DBusReleaseNameReplyReleased}, nil - } else if method == "org.freedesktop.DBus.AddMatch" { - return nil, nil - } else { - return nil, fmt.Errorf("unexpected method call '%s'", method) - } - }, - ) - - dbus := NewFake(fakeSystem, fakeSession) - doDBusTest(t, dbus, false) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/doc.go deleted file mode 100644 index 59bec0e56..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package dbus provides an injectable interface and implementations for D-Bus communication -package dbus diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/fake_dbus.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/fake_dbus.go deleted file mode 100644 index eb97febae..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/dbus/fake_dbus.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package dbus - -import ( - "fmt" - - godbus "github.com/godbus/dbus" -) - -// DBusFake is a simple fake Interface type. -type DBusFake struct { - systemBus *DBusFakeConnection - sessionBus *DBusFakeConnection -} - -// DBusFakeConnection represents a fake D-Bus connection -type DBusFakeConnection struct { - busObject *fakeObject - objects map[string]*fakeObject - signalHandlers []chan<- *godbus.Signal -} - -// DBusFakeHandler is used to handle fake D-Bus method calls -type DBusFakeHandler func(method string, args ...interface{}) ([]interface{}, error) - -type fakeObject struct { - handler DBusFakeHandler -} - -type fakeCall struct { - ret []interface{} - err error -} - -// NewFake returns a new Interface which will fake talking to D-Bus -func NewFake(systemBus *DBusFakeConnection, sessionBus *DBusFakeConnection) *DBusFake { - return &DBusFake{systemBus, sessionBus} -} - -func NewFakeConnection() *DBusFakeConnection { - return &DBusFakeConnection{ - objects: make(map[string]*fakeObject), - } -} - -// SystemBus is part of Interface -func (db *DBusFake) SystemBus() (Connection, error) { - if db.systemBus != nil { - return db.systemBus, nil - } else { - return nil, fmt.Errorf("DBus is not running") - } -} - -// SessionBus is part of Interface -func (db *DBusFake) SessionBus() (Connection, error) { - if db.sessionBus != nil { - return db.sessionBus, nil - } else { - return nil, fmt.Errorf("DBus is not running") - } -} - -// BusObject is part of the Connection interface -func (conn *DBusFakeConnection) BusObject() Object { - return conn.busObject -} - -// Object is part of the Connection interface -func (conn *DBusFakeConnection) Object(name, path string) Object { - return conn.objects[name+path] -} - -// Signal is part of the Connection interface -func (conn *DBusFakeConnection) Signal(ch chan<- *godbus.Signal) { - for i := range conn.signalHandlers { - if conn.signalHandlers[i] == ch { - conn.signalHandlers = append(conn.signalHandlers[:i], conn.signalHandlers[i+1:]...) - return - } - } - conn.signalHandlers = append(conn.signalHandlers, ch) -} - -// SetBusObject sets the handler for the BusObject of conn -func (conn *DBusFakeConnection) SetBusObject(handler DBusFakeHandler) { - conn.busObject = &fakeObject{handler} -} - -// AddObject adds a handler for the Object at name and path -func (conn *DBusFakeConnection) AddObject(name, path string, handler DBusFakeHandler) { - conn.objects[name+path] = &fakeObject{handler} -} - -// EmitSignal emits a signal on conn -func (conn *DBusFakeConnection) EmitSignal(name, path, iface, signal string, args ...interface{}) { - sig := &godbus.Signal{ - Sender: name, - Path: godbus.ObjectPath(path), - Name: iface + "." + signal, - Body: args, - } - for _, ch := range conn.signalHandlers { - ch <- sig - } -} - -// Call is part of the Object interface -func (obj *fakeObject) Call(method string, flags godbus.Flags, args ...interface{}) Call { - ret, err := obj.handler(method, args...) - return &fakeCall{ret, err} -} - -// Store is part of the Call interface -func (call *fakeCall) Store(retvalues ...interface{}) error { - if call.err != nil { - return call.err - } - return godbus.Store(call.ret, retvalues...) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deadlock-detector_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deadlock-detector_test.go deleted file mode 100644 index 51d111245..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deadlock-detector_test.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package util - -import ( - "sync" - "testing" - "time" -) - -type fakeExiter struct { - format string - args []interface{} - exited bool -} - -func (f *fakeExiter) Exitf(format string, args ...interface{}) { - f.format = format - f.args = args - f.exited = true -} - -func TestMaxLockPeriod(t *testing.T) { - lock := &sync.RWMutex{} - panicked := false - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - DeadlockWatchdogReadLock(lock, "test lock", 0) - }() - if !panicked { - t.Errorf("expected a panic for a zero max lock period") - } -} - -func TestDeadlockWatchdogLocked(t *testing.T) { - lock := &sync.RWMutex{} - lock.Lock() - - exitCh := make(chan time.Time, 1) - fake := fakeExiter{} - - detector := &deadlockDetector{ - lock: &rwMutexToLockableAdapter{lock}, - name: "test deadlock", - exitChannelFn: func() <-chan time.Time { return exitCh }, - exiter: &fake, - } - - exitCh <- time.Time{} - - detector.run() - - if !fake.exited { - t.Errorf("expected to have exited") - } - - if len(fake.args) != 1 || fake.args[0].(string) != detector.name { - t.Errorf("unexpected args: %v", fake.args) - } -} - -func TestDeadlockWatchdogUnlocked(t *testing.T) { - lock := &sync.RWMutex{} - - fake := fakeExiter{} - - detector := &deadlockDetector{ - lock: &rwMutexToLockableAdapter{lock}, - name: "test deadlock", - exitChannelFn: func() <-chan time.Time { return time.After(time.Second * 5) }, - exiter: &fake, - } - - for i := 0; i < 100; i++ { - detector.runOnce() - } - - if fake.exited { - t.Errorf("expected to have not exited") - } -} - -func TestDeadlockWatchdogLocking(t *testing.T) { - lock := &sync.RWMutex{} - - fake := fakeExiter{} - - go func() { - for { - lock.Lock() - lock.Unlock() - } - }() - - detector := &deadlockDetector{ - lock: &rwMutexToLockableAdapter{lock}, - name: "test deadlock", - exitChannelFn: func() <-chan time.Time { return time.After(time.Second * 5) }, - exiter: &fake, - } - - for i := 0; i < 100; i++ { - detector.runOnce() - } - - if fake.exited { - t.Errorf("expected to have not exited") - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deployment/deployment.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deployment/deployment.go index 5f5baa782..6160f5d13 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deployment/deployment.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deployment/deployment.go @@ -21,15 +21,20 @@ import ( "strconv" "time" + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/integer" intstrutil "k8s.io/kubernetes/pkg/util/intstr" labelsutil "k8s.io/kubernetes/pkg/util/labels" podutil "k8s.io/kubernetes/pkg/util/pod" + "k8s.io/kubernetes/pkg/util/wait" ) const ( @@ -44,40 +49,88 @@ const ( // GetOldReplicaSets returns the old replica sets targeted by the given Deployment; get 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. -func GetOldReplicaSets(deployment extensions.Deployment, c clientset.Interface) ([]*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { - return GetOldReplicaSetsFromLists(deployment, c, - func(namespace string, options api.ListOptions) (*api.PodList, error) { - return c.Core().Pods(namespace).List(options) - }, +func GetOldReplicaSets(deployment *extensions.Deployment, c clientset.Interface) ([]*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { + rsList, err := ListReplicaSets(deployment, func(namespace string, options api.ListOptions) ([]extensions.ReplicaSet, error) { rsList, err := c.Extensions().ReplicaSets(namespace).List(options) return rsList.Items, err }) + if err != nil { + return nil, nil, fmt.Errorf("error listing ReplicaSets: %v", err) + } + podList, err := ListPods(deployment, + func(namespace string, options api.ListOptions) (*api.PodList, error) { + return c.Core().Pods(namespace).List(options) + }) + if err != nil { + return nil, nil, fmt.Errorf("error listing Pods: %v", err) + } + return FindOldReplicaSets(deployment, rsList, podList) } -// GetOldReplicaSetsFromLists returns two sets of old replica sets targeted by the given Deployment; get PodList and ReplicaSetList with input functions. -// 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. -func GetOldReplicaSetsFromLists(deployment extensions.Deployment, c clientset.Interface, getPodList func(string, api.ListOptions) (*api.PodList, error), getRSList func(string, api.ListOptions) ([]extensions.ReplicaSet, error)) ([]*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { - namespace := deployment.ObjectMeta.Namespace +// GetNewReplicaSet returns a replica set that matches the intent of the given deployment; get ReplicaSetList from client interface. +// Returns nil if the new replica set doesn't exist yet. +func GetNewReplicaSet(deployment *extensions.Deployment, c clientset.Interface) (*extensions.ReplicaSet, error) { + rsList, err := ListReplicaSets(deployment, + func(namespace string, options api.ListOptions) ([]extensions.ReplicaSet, error) { + rsList, err := c.Extensions().ReplicaSets(namespace).List(options) + return rsList.Items, err + }) + if err != nil { + return nil, fmt.Errorf("error listing ReplicaSets: %v", err) + } + return FindNewReplicaSet(deployment, rsList) +} + +// TODO: switch this to full namespacers +type rsListFunc func(string, api.ListOptions) ([]extensions.ReplicaSet, error) +type podListFunc func(string, api.ListOptions) (*api.PodList, error) + +// ListReplicaSets returns a slice of RSes the given deployment targets. +func ListReplicaSets(deployment *extensions.Deployment, getRSList rsListFunc) ([]extensions.ReplicaSet, error) { + // TODO: Right now we list replica sets by their labels. We should list them by selector, i.e. the replica set's selector + // should be a superset of the deployment's selector, see https://github.com/kubernetes/kubernetes/issues/19830; + // or use controllerRef, see https://github.com/kubernetes/kubernetes/issues/2210 + namespace := deployment.Namespace selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { - return nil, nil, fmt.Errorf("invalid label selector: %v", err) + return nil, err } - - // 1. Find all pods whose labels match deployment.Spec.Selector options := api.ListOptions{LabelSelector: selector} - podList, err := getPodList(namespace, options) + return getRSList(namespace, options) +} + +// ListPods returns a list of pods the given deployment targets. +func ListPods(deployment *extensions.Deployment, getPodList podListFunc) (*api.PodList, error) { + namespace := deployment.Namespace + selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) if err != nil { - return nil, nil, fmt.Errorf("error listing pods: %v", err) + return nil, err } - // 2. Find the corresponding replica sets for pods in podList. - // TODO: Right now we list all replica sets and then filter. We should add an API for this. + options := api.ListOptions{LabelSelector: selector} + return getPodList(namespace, options) +} + +// FindNewReplicaSet returns the new RS this given deployment targets (the one with the same pod template). +func FindNewReplicaSet(deployment *extensions.Deployment, rsList []extensions.ReplicaSet) (*extensions.ReplicaSet, error) { + newRSTemplate := GetNewReplicaSetTemplate(deployment) + for i := range rsList { + if api.Semantic.DeepEqual(rsList[i].Spec.Template, newRSTemplate) { + // This is the new ReplicaSet. + return &rsList[i], nil + } + } + // new ReplicaSet does not exist. + return nil, nil +} + +// FindOldReplicaSets returns the old replica sets targeted by the given Deployment, with the given PodList and slice of RSes. +// 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. +func FindOldReplicaSets(deployment *extensions.Deployment, rsList []extensions.ReplicaSet, podList *api.PodList) ([]*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { + // Find all pods whose labels match deployment.Spec.Selector, and corresponding replica sets for pods in podList. + // All pods and replica sets are labeled with pod-template-hash to prevent overlapping oldRSs := map[string]extensions.ReplicaSet{} allOldRSs := map[string]extensions.ReplicaSet{} - rsList, err := getRSList(namespace, options) - if err != nil { - return nil, nil, fmt.Errorf("error listing replica sets: %v", err) - } newRSTemplate := GetNewReplicaSetTemplate(deployment) for _, pod := range podList.Items { podLabelsSelector := labels.Set(pod.ObjectMeta.Labels) @@ -87,7 +140,7 @@ func GetOldReplicaSetsFromLists(deployment extensions.Deployment, c clientset.In return nil, nil, fmt.Errorf("invalid label selector: %v", err) } // Filter out replica set that has the same pod template spec as the deployment - that is the new replica set. - if api.Semantic.DeepEqual(rs.Spec.Template, &newRSTemplate) { + if api.Semantic.DeepEqual(rs.Spec.Template, newRSTemplate) { continue } allOldRSs[rs.ObjectMeta.Name] = rs @@ -109,43 +162,58 @@ func GetOldReplicaSetsFromLists(deployment extensions.Deployment, c clientset.In return requiredRSs, allRSs, nil } -// GetNewReplicaSet returns a replica set that matches the intent of the given deployment; get ReplicaSetList from client interface. -// Returns nil if the new replica set doesn't exist yet. -func GetNewReplicaSet(deployment extensions.Deployment, c clientset.Interface) (*extensions.ReplicaSet, error) { - return GetNewReplicaSetFromList(deployment, c, - func(namespace string, options api.ListOptions) ([]extensions.ReplicaSet, error) { - rsList, err := c.Extensions().ReplicaSets(namespace).List(options) - return rsList.Items, err - }) +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) + if err != nil { + return false, err + } + return rs.Status.ObservedGeneration >= desiredGeneration, nil + }) } -// GetNewReplicaSetFromList returns a replica set that matches the intent of the given deployment; get ReplicaSetList with the input function. -// Returns nil if the new replica set doesn't exist yet. -func GetNewReplicaSetFromList(deployment extensions.Deployment, c clientset.Interface, getRSList func(string, api.ListOptions) ([]extensions.ReplicaSet, error)) (*extensions.ReplicaSet, error) { - namespace := deployment.ObjectMeta.Namespace - selector, err := unversioned.LabelSelectorAsSelector(deployment.Spec.Selector) - if err != nil { - return nil, fmt.Errorf("invalid label selector: %v", err) - } +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) + if err != nil { + return false, err + } + return rs.Status.ObservedGeneration >= desiredGeneration && + rs.Status.FullyLabeledReplicas == rs.Spec.Replicas, nil + }) +} - rsList, err := getRSList(namespace, api.ListOptions{LabelSelector: selector}) - if err != nil { - return nil, fmt.Errorf("error listing ReplicaSets: %v", err) - } - newRSTemplate := GetNewReplicaSetTemplate(deployment) - - for i := range rsList { - if api.Semantic.DeepEqual(rsList[i].Spec.Template, &newRSTemplate) { - // This is the new ReplicaSet. - return &rsList[i], nil +// LabelPodsWithHash labels all pods in the given podList with the new hash label. +// The returned bool value can be used to tell if all pods are actually labeled. +func LabelPodsWithHash(podList *api.PodList, rs *extensions.ReplicaSet, c clientset.Interface, namespace, hash string) (bool, error) { + allPodsLabeled := true + for _, pod := range podList.Items { + // Only label the pod that doesn't already have the new hash + if pod.Labels[extensions.DefaultDeploymentUniqueLabelKey] != hash { + if _, podUpdated, err := podutil.UpdatePodWithRetries(c.Core().Pods(namespace), &pod, + func(podToUpdate *api.Pod) error { + // Precondition: the pod doesn't contain the new hash in its label. + if podToUpdate.Labels[extensions.DefaultDeploymentUniqueLabelKey] == hash { + return errors.ErrPreconditionViolated + } + podToUpdate.Labels = labelsutil.AddLabel(podToUpdate.Labels, extensions.DefaultDeploymentUniqueLabelKey, hash) + return nil + }); err != nil { + return false, fmt.Errorf("error in adding template hash label %s to pod %+v: %s", hash, pod, err) + } else if podUpdated { + glog.V(4).Infof("Labeled %s %s/%s of %s %s/%s with hash %s.", pod.Kind, pod.Namespace, pod.Name, rs.Kind, rs.Namespace, rs.Name, hash) + } else { + // If the pod wasn't updated but didn't return error when we try to update it, we've hit "pod not found" or "precondition violated" error. + // Then we can't say all pods are labeled + allPodsLabeled = false + } } } - // new ReplicaSet does not exist. - return nil, nil + return allPodsLabeled, nil } // Returns the desired PodTemplateSpec for the new ReplicaSet corresponding to the given ReplicaSet. -func GetNewReplicaSetTemplate(deployment extensions.Deployment) api.PodTemplateSpec { +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{ ObjectMeta: deployment.Spec.Template.ObjectMeta, @@ -172,7 +240,20 @@ func SetFromReplicaSetTemplate(deployment *extensions.Deployment, template api.P func GetReplicaCountForReplicaSets(replicaSets []*extensions.ReplicaSet) int { totalReplicaCount := 0 for _, rs := range replicaSets { - totalReplicaCount += rs.Spec.Replicas + if rs != nil { + totalReplicaCount += rs.Spec.Replicas + } + } + return totalReplicaCount +} + +// GetActualReplicaCountForReplicaSets returns the sum of actual replicas of the given replica sets. +func GetActualReplicaCountForReplicaSets(replicaSets []*extensions.ReplicaSet) int { + totalReplicaCount := 0 + for _, rs := range replicaSets { + if rs != nil { + totalReplicaCount += rs.Status.Replicas + } } return totalReplicaCount } @@ -197,6 +278,9 @@ func getReadyPodsCount(pods []api.Pod, minReadySeconds int) int { } func IsPodAvailable(pod *api.Pod, minReadySeconds int) bool { + if !controller.IsPodActive(*pod) { + return false + } // Check if we've passed minReadySeconds since LastTransitionTime // If so, this pod is ready for _, c := range pod.Status.Conditions { @@ -215,20 +299,28 @@ func IsPodAvailable(pod *api.Pod, minReadySeconds int) bool { } func GetPodsForReplicaSets(c clientset.Interface, replicaSets []*extensions.ReplicaSet) ([]api.Pod, error) { - allPods := []api.Pod{} + allPods := map[string]api.Pod{} for _, rs := range replicaSets { - selector, err := unversioned.LabelSelectorAsSelector(rs.Spec.Selector) - if err != nil { - return nil, fmt.Errorf("invalid label selector: %v", err) + if rs != nil { + selector, err := unversioned.LabelSelectorAsSelector(rs.Spec.Selector) + if err != nil { + return nil, fmt.Errorf("invalid label selector: %v", err) + } + options := api.ListOptions{LabelSelector: selector} + podList, err := c.Core().Pods(rs.ObjectMeta.Namespace).List(options) + if err != nil { + return nil, fmt.Errorf("error listing pods: %v", err) + } + for _, pod := range podList.Items { + allPods[pod.Name] = pod + } } - options := api.ListOptions{LabelSelector: selector} - podList, err := c.Core().Pods(rs.ObjectMeta.Namespace).List(options) - if err != nil { - return allPods, fmt.Errorf("error listing pods: %v", err) - } - allPods = append(allPods, podList.Items...) } - return allPods, nil + requiredPods := []api.Pod{} + for _, pod := range allPods { + requiredPods = append(requiredPods, pod) + } + return requiredPods, nil } // Revision returns the revision number of the input replica set @@ -252,7 +344,7 @@ func NewRSNewReplicas(deployment *extensions.Deployment, allRSs []*extensions.Re switch deployment.Spec.Strategy.Type { case extensions.RollingUpdateDeploymentStrategyType: // Check if we can scale up. - maxSurge, err := intstrutil.GetValueFromIntOrPercent(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Replicas) + maxSurge, err := intstrutil.GetValueFromIntOrPercent(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Replicas, true) if err != nil { return 0, err } @@ -274,3 +366,46 @@ func NewRSNewReplicas(deployment *extensions.Deployment, allRSs []*extensions.Re return 0, fmt.Errorf("deployment type %v isn't supported", deployment.Spec.Strategy.Type) } } + +// 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. + return wait.Poll(interval, timeout, func() (bool, error) { + deployment, err := getDeploymentFunc() + if err != nil { + return false, err + } + return deployment.Status.ObservedGeneration >= desiredGeneration, nil + }) +} + +// ResolveFenceposts resolves both maxSurge and maxUnavailable. This needs to happen in one +// step. For example: +// +// 2 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1), then old(-1), then new(+1) +// 1 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1) +// 2 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1) +// 1 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1) +// 2 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1) +// 1 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1) +func ResolveFenceposts(maxSurge, maxUnavailable *intstrutil.IntOrString, desired int) (int, int, error) { + surge, err := intstrutil.GetValueFromIntOrPercent(maxSurge, desired, true) + if err != nil { + return 0, 0, err + } + unavailable, err := intstrutil.GetValueFromIntOrPercent(maxUnavailable, desired, false) + if err != nil { + return 0, 0, err + } + + if surge == 0 && unavailable == 0 { + // Validation should never allow the user to explicitly use zero values for both maxSurge + // maxUnavailable. Due to rounding down maxUnavailable though, it may resolve to zero. + // If both fenceposts resolve to zero, then we should set maxUnavailable to 1 on the + // theory that surge might not work due to quota. + unavailable = 1 + } + + return surge, unavailable, nil +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deployment/deployment_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deployment/deployment_test.go deleted file mode 100644 index 4383bda02..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/deployment/deployment_test.go +++ /dev/null @@ -1,344 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package deployment - -import ( - "reflect" - "testing" - "time" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - "k8s.io/kubernetes/pkg/client/unversioned/testclient/simple" - "k8s.io/kubernetes/pkg/runtime" -) - -func newPod(now time.Time, ready bool, beforeSec int) api.Pod { - conditionStatus := api.ConditionFalse - if ready { - conditionStatus = api.ConditionTrue - } - return api.Pod{ - Status: api.PodStatus{ - Conditions: []api.PodCondition{ - { - Type: api.PodReady, - LastTransitionTime: unversioned.NewTime(now.Add(-1 * time.Duration(beforeSec) * time.Second)), - Status: conditionStatus, - }, - }, - }, - } -} - -func TestGetReadyPodsCount(t *testing.T) { - now := time.Now() - tests := []struct { - pods []api.Pod - minReadySeconds int - expected int - }{ - { - []api.Pod{ - newPod(now, true, 0), - newPod(now, true, 2), - newPod(now, false, 1), - }, - 1, - 1, - }, - { - []api.Pod{ - newPod(now, true, 2), - newPod(now, true, 11), - newPod(now, true, 5), - }, - 10, - 1, - }, - } - - for _, test := range tests { - if count := getReadyPodsCount(test.pods, test.minReadySeconds); count != test.expected { - t.Errorf("Pods = %#v, minReadySeconds = %d, expected %d, got %d", test.pods, test.minReadySeconds, test.expected, count) - } - } -} - -// generatePodFromRS creates a pod, with the input ReplicaSet's selector and its template -func generatePodFromRS(rs extensions.ReplicaSet) api.Pod { - return api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: rs.Labels, - }, - Spec: rs.Spec.Template.Spec, - } -} - -func generatePod(labels map[string]string, image string) api.Pod { - return api.Pod{ - ObjectMeta: api.ObjectMeta{ - Labels: labels, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: image, - Image: image, - ImagePullPolicy: api.PullAlways, - TerminationMessagePath: api.TerminationMessagePathDefault, - }, - }, - }, - } -} - -func generateRSWithLabel(labels map[string]string, image string) extensions.ReplicaSet { - return extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: api.SimpleNameGenerator.GenerateName("replicaset"), - Labels: labels, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 1, - Selector: &unversioned.LabelSelector{MatchLabels: labels}, - Template: &api.PodTemplateSpec{ - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: image, - Image: image, - ImagePullPolicy: api.PullAlways, - TerminationMessagePath: api.TerminationMessagePathDefault, - }, - }, - }, - }, - }, - } -} - -// generateRS creates a replica set, with the input deployment's template as its template -func generateRS(deployment extensions.Deployment) extensions.ReplicaSet { - template := GetNewReplicaSetTemplate(deployment) - return extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - Name: api.SimpleNameGenerator.GenerateName("replicaset"), - Labels: template.Labels, - }, - Spec: extensions.ReplicaSetSpec{ - Template: &template, - Selector: &unversioned.LabelSelector{MatchLabels: template.Labels}, - }, - } -} - -// generateDeployment creates a deployment, with the input image as its template -func generateDeployment(image string) extensions.Deployment { - podLabels := map[string]string{"name": image} - terminationSec := int64(30) - return extensions.Deployment{ - ObjectMeta: api.ObjectMeta{ - Name: image, - }, - Spec: extensions.DeploymentSpec{ - Replicas: 1, - Selector: &unversioned.LabelSelector{MatchLabels: podLabels}, - Template: api.PodTemplateSpec{ - ObjectMeta: api.ObjectMeta{ - Labels: podLabels, - }, - Spec: api.PodSpec{ - Containers: []api.Container{ - { - Name: image, - Image: image, - ImagePullPolicy: api.PullAlways, - TerminationMessagePath: api.TerminationMessagePathDefault, - }, - }, - DNSPolicy: api.DNSClusterFirst, - TerminationGracePeriodSeconds: &terminationSec, - RestartPolicy: api.RestartPolicyAlways, - SecurityContext: &api.PodSecurityContext{}, - }, - }, - }, - } -} - -func TestGetNewRC(t *testing.T) { - newDeployment := generateDeployment("nginx") - newRC := generateRS(newDeployment) - - tests := []struct { - test string - rsList extensions.ReplicaSetList - expected *extensions.ReplicaSet - }{ - { - "No new ReplicaSet", - extensions.ReplicaSetList{ - Items: []extensions.ReplicaSet{ - generateRS(generateDeployment("foo")), - generateRS(generateDeployment("bar")), - }, - }, - nil, - }, - { - "Has new ReplicaSet", - extensions.ReplicaSetList{ - Items: []extensions.ReplicaSet{ - generateRS(generateDeployment("foo")), - generateRS(generateDeployment("bar")), - generateRS(generateDeployment("abc")), - newRC, - generateRS(generateDeployment("xyz")), - }, - }, - &newRC, - }, - } - - ns := api.NamespaceDefault - for _, test := range tests { - c := &simple.Client{ - Request: simple.Request{ - Method: "GET", - Path: testapi.Default.ResourcePath("replicaSets", ns, ""), - }, - Response: simple.Response{ - StatusCode: 200, - Body: &test.rsList, - }, - } - rs, err := GetNewReplicaSet(newDeployment, c.Setup(t).Clientset) - if err != nil { - t.Errorf("In test case %s, got unexpected error %v", test.test, err) - } - if !api.Semantic.DeepEqual(rs, test.expected) { - t.Errorf("In test case %s, expected %+v, got %+v", test.test, test.expected, rs) - } - } -} - -func TestGetOldRCs(t *testing.T) { - newDeployment := generateDeployment("nginx") - newRS := generateRS(newDeployment) - newPod := generatePodFromRS(newRS) - - // create 2 old deployments and related replica sets/pods, with the same labels but different template - oldDeployment := generateDeployment("nginx") - oldDeployment.Spec.Template.Spec.Containers[0].Name = "nginx-old-1" - oldRS := generateRS(oldDeployment) - oldPod := generatePodFromRS(oldRS) - oldDeployment2 := generateDeployment("nginx") - oldDeployment2.Spec.Template.Spec.Containers[0].Name = "nginx-old-2" - oldRS2 := generateRS(oldDeployment2) - oldPod2 := generatePodFromRS(oldRS2) - - // create 1 ReplicaSet that existed before the deployment, with the same labels as the deployment - existedPod := generatePod(newDeployment.Spec.Template.Labels, "foo") - existedRS := generateRSWithLabel(newDeployment.Spec.Template.Labels, "foo") - - tests := []struct { - test string - objs []runtime.Object - expected []*extensions.ReplicaSet - }{ - { - "No old ReplicaSets", - []runtime.Object{ - &api.PodList{ - Items: []api.Pod{ - generatePod(newDeployment.Spec.Template.Labels, "foo"), - generatePod(newDeployment.Spec.Template.Labels, "bar"), - newPod, - }, - }, - &extensions.ReplicaSetList{ - Items: []extensions.ReplicaSet{ - generateRS(generateDeployment("foo")), - newRS, - generateRS(generateDeployment("bar")), - }, - }, - }, - []*extensions.ReplicaSet{}, - }, - { - "Has old ReplicaSet", - []runtime.Object{ - &api.PodList{ - Items: []api.Pod{ - oldPod, - oldPod2, - generatePod(map[string]string{"name": "bar"}, "bar"), - generatePod(map[string]string{"name": "xyz"}, "xyz"), - existedPod, - generatePod(newDeployment.Spec.Template.Labels, "abc"), - }, - }, - &extensions.ReplicaSetList{ - Items: []extensions.ReplicaSet{ - oldRS2, - oldRS, - existedRS, - newRS, - generateRSWithLabel(map[string]string{"name": "xyz"}, "xyz"), - generateRSWithLabel(map[string]string{"name": "bar"}, "bar"), - }, - }, - }, - []*extensions.ReplicaSet{&oldRS, &oldRS2, &existedRS}, - }, - } - - for _, test := range tests { - rss, _, err := GetOldReplicaSets(newDeployment, fake.NewSimpleClientset(test.objs...)) - if err != nil { - t.Errorf("In test case %s, got unexpected error %v", test.test, err) - } - if !equal(rss, test.expected) { - t.Errorf("In test case %q, expected %v, got %v", test.test, test.expected, rss) - } - } -} - -// equal compares the equality of two ReplicaSet slices regardless of their ordering -func equal(rss1, rss2 []*extensions.ReplicaSet) bool { - if reflect.DeepEqual(rss1, rss2) { - return true - } - if rss1 == nil || rss2 == nil || len(rss1) != len(rss2) { - return false - } - count := 0 - for _, rs1 := range rss1 { - for _, rs2 := range rss2 { - if reflect.DeepEqual(rs1, rs2) { - count++ - break - } - } - } - return count == len(rss1) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/env_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/env_test.go deleted file mode 100644 index a640fbe2a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/env_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package util - -import ( - "os" - "strconv" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetEnvAsStringOrFallback(t *testing.T) { - const expected = "foo" - - assert := assert.New(t) - - key := "FLOCKER_SET_VAR" - os.Setenv(key, expected) - assert.Equal(expected, GetEnvAsStringOrFallback(key, "~"+expected)) - - key = "FLOCKER_UNSET_VAR" - assert.Equal(expected, GetEnvAsStringOrFallback(key, expected)) -} - -func TestGetEnvAsIntOrFallback(t *testing.T) { - const expected = 1 - - assert := assert.New(t) - - key := "FLOCKER_SET_VAR" - os.Setenv(key, strconv.Itoa(expected)) - returnVal, _ := GetEnvAsIntOrFallback(key, 1) - assert.Equal(expected, returnVal) - - key = "FLOCKER_UNSET_VAR" - returnVal, _ = GetEnvAsIntOrFallback(key, expected) - assert.Equal(expected, returnVal) -} - -func TestGetEnvAsFloat64OrFallback(t *testing.T) { - const expected = 1.0 - - assert := assert.New(t) - - key := "FLOCKER_SET_VAR" - os.Setenv(key, "1.0") - returnVal, _ := GetEnvAsFloat64OrFallback(key, 2.0) - assert.Equal(expected, returnVal) - - key = "FLOCKER_UNSET_VAR" - returnVal, _ = GetEnvAsFloat64OrFallback(key, 1.0) - assert.Equal(expected, returnVal) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/errors/errors.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/errors/errors.go index a1a8e7aa2..df3adaf3e 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/errors/errors.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/errors/errors.go @@ -16,7 +16,10 @@ limitations under the License. package errors -import "fmt" +import ( + "errors" + "fmt" +) // Aggregate represents an object that contains multiple errors, but does not // necessarily have singular semantic meaning. @@ -148,3 +151,6 @@ func AggregateGoroutines(funcs ...func() error) Aggregate { } return NewAggregate(errs) } + +// ErrPreconditionViolated is returned when the precondition is violated +var ErrPreconditionViolated = errors.New("precondition is violated") diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/errors/errors_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/errors/errors_test.go deleted file mode 100644 index 7ecf919ff..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/errors/errors_test.go +++ /dev/null @@ -1,286 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package errors - -import ( - "fmt" - "reflect" - "testing" -) - -func TestEmptyAggregate(t *testing.T) { - var slice []error - var agg Aggregate - var err error - - agg = NewAggregate(slice) - if agg != nil { - t.Errorf("expected nil, got %#v", agg) - } - err = NewAggregate(slice) - if err != nil { - t.Errorf("expected nil, got %#v", err) - } - - // This is not normally possible, but pedantry demands I test it. - agg = aggregate(slice) // empty aggregate - if s := agg.Error(); s != "" { - t.Errorf("expected empty string, got %q", s) - } - if s := agg.Errors(); len(s) != 0 { - t.Errorf("expected empty slice, got %#v", s) - } - err = agg.(error) - if s := err.Error(); s != "" { - t.Errorf("expected empty string, got %q", s) - } -} - -func TestSingularAggregate(t *testing.T) { - var slice []error = []error{fmt.Errorf("err")} - var agg Aggregate - var err error - - agg = NewAggregate(slice) - if agg == nil { - t.Errorf("expected non-nil") - } - if s := agg.Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } - if s := agg.Errors(); len(s) != 1 { - t.Errorf("expected one-element slice, got %#v", s) - } - if s := agg.Errors()[0].Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } - - err = agg.(error) - if err == nil { - t.Errorf("expected non-nil") - } - if s := err.Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } -} - -func TestPluralAggregate(t *testing.T) { - var slice []error = []error{fmt.Errorf("abc"), fmt.Errorf("123")} - var agg Aggregate - var err error - - agg = NewAggregate(slice) - if agg == nil { - t.Errorf("expected non-nil") - } - if s := agg.Error(); s != "[abc, 123]" { - t.Errorf("expected '[abc, 123]', got %q", s) - } - if s := agg.Errors(); len(s) != 2 { - t.Errorf("expected two-elements slice, got %#v", s) - } - if s := agg.Errors()[0].Error(); s != "abc" { - t.Errorf("expected '[abc, 123]', got %q", s) - } - - err = agg.(error) - if err == nil { - t.Errorf("expected non-nil") - } - if s := err.Error(); s != "[abc, 123]" { - t.Errorf("expected '[abc, 123]', got %q", s) - } -} - -func TestFilterOut(t *testing.T) { - testCases := []struct { - err error - filter []Matcher - expected error - }{ - { - nil, - []Matcher{}, - nil, - }, - { - aggregate{}, - []Matcher{}, - nil, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return false }}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return true }}, - nil, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return false }, func(err error) bool { return false }}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return false }, func(err error) bool { return true }}, - nil, - }, - { - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - []Matcher{func(err error) bool { return err.Error() == "def" }}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("ghi")}, - }, - { - aggregate{aggregate{fmt.Errorf("abc")}}, - []Matcher{}, - aggregate{aggregate{fmt.Errorf("abc")}}, - }, - { - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - []Matcher{}, - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - }, - { - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - []Matcher{func(err error) bool { return err.Error() == "def" }}, - aggregate{aggregate{fmt.Errorf("abc")}}, - }, - } - for i, testCase := range testCases { - err := FilterOut(testCase.err, testCase.filter...) - if !reflect.DeepEqual(testCase.expected, err) { - t.Errorf("%d: expected %v, got %v", i, testCase.expected, err) - } - } -} - -func TestFlatten(t *testing.T) { - testCases := []struct { - agg Aggregate - expected Aggregate - }{ - { - nil, - nil, - }, - { - aggregate{}, - nil, - }, - { - aggregate{fmt.Errorf("abc")}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - }, - { - aggregate{aggregate{fmt.Errorf("abc")}}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{aggregate{aggregate{fmt.Errorf("abc")}}}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("def")}, - }, - { - aggregate{aggregate{aggregate{fmt.Errorf("abc")}, fmt.Errorf("def"), aggregate{fmt.Errorf("ghi")}}}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - }, - } - for i, testCase := range testCases { - agg := Flatten(testCase.agg) - if !reflect.DeepEqual(testCase.expected, agg) { - t.Errorf("%d: expected %v, got %v", i, testCase.expected, agg) - } - } -} - -func TestAggregateGoroutines(t *testing.T) { - testCases := []struct { - errs []error - expected map[string]bool // can't compare directly to Aggregate due to non-deterministic ordering - }{ - { - []error{}, - nil, - }, - { - []error{nil}, - nil, - }, - { - []error{nil, nil}, - nil, - }, - { - []error{fmt.Errorf("1")}, - map[string]bool{"1": true}, - }, - { - []error{fmt.Errorf("1"), nil}, - map[string]bool{"1": true}, - }, - { - []error{fmt.Errorf("1"), fmt.Errorf("267")}, - map[string]bool{"1": true, "267": true}, - }, - { - []error{fmt.Errorf("1"), nil, fmt.Errorf("1234")}, - map[string]bool{"1": true, "1234": true}, - }, - { - []error{nil, fmt.Errorf("1"), nil, fmt.Errorf("1234"), fmt.Errorf("22")}, - map[string]bool{"1": true, "1234": true, "22": true}, - }, - } - for i, testCase := range testCases { - funcs := make([]func() error, len(testCase.errs)) - for i := range testCase.errs { - err := testCase.errs[i] - funcs[i] = func() error { return err } - } - agg := AggregateGoroutines(funcs...) - if agg == nil { - if len(testCase.expected) > 0 { - t.Errorf("%d: expected %v, got nil", i, testCase.expected) - } - continue - } - if len(agg.Errors()) != len(testCase.expected) { - t.Errorf("%d: expected %d errors in aggregate, got %v", i, len(testCase.expected), agg) - continue - } - for _, err := range agg.Errors() { - if !testCase.expected[err.Error()] { - t.Errorf("%d: expected %v, got aggregate containing %v", i, testCase.expected, err) - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/doc.go deleted file mode 100644 index 64c1541bf..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package exec provides an injectable interface and implementations for running commands. -package exec diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/exec.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/exec.go deleted file mode 100644 index 80444a9d8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/exec.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package exec - -import ( - osexec "os/exec" - "syscall" -) - -// ErrExecutableNotFound is returned if the executable is not found. -var ErrExecutableNotFound = osexec.ErrNotFound - -// Interface is an interface that presents a subset of the os/exec API. Use this -// when you want to inject fakeable/mockable exec behavior. -type Interface interface { - // Command returns a Cmd instance which can be used to run a single command. - // This follows the pattern of package os/exec. - Command(cmd string, args ...string) Cmd - - // LookPath wraps os/exec.LookPath - LookPath(file string) (string, error) -} - -// Cmd is an interface that presents an API that is very similar to Cmd from os/exec. -// As more functionality is needed, this can grow. Since Cmd is a struct, we will have -// to replace fields with get/set method pairs. -type Cmd interface { - // CombinedOutput runs the command and returns its combined standard output - // and standard error. This follows the pattern of package os/exec. - CombinedOutput() ([]byte, error) - // Output runs the command and returns standard output, but not standard err - Output() ([]byte, error) - SetDir(dir string) -} - -// ExitError is an interface that presents an API similar to os.ProcessState, which is -// what ExitError from os/exec is. This is designed to make testing a bit easier and -// probably loses some of the cross-platform properties of the underlying library. -type ExitError interface { - String() string - Error() string - Exited() bool - ExitStatus() int -} - -// Implements Interface in terms of really exec()ing. -type executor struct{} - -// New returns a new Interface which will os/exec to run commands. -func New() Interface { - return &executor{} -} - -// Command is part of the Interface interface. -func (executor *executor) Command(cmd string, args ...string) Cmd { - return (*cmdWrapper)(osexec.Command(cmd, args...)) -} - -// LookPath is part of the Interface interface -func (executor *executor) LookPath(file string) (string, error) { - return osexec.LookPath(file) -} - -// Wraps exec.Cmd so we can capture errors. -type cmdWrapper osexec.Cmd - -func (cmd *cmdWrapper) SetDir(dir string) { - cmd.Dir = dir -} - -// CombinedOutput is part of the Cmd interface. -func (cmd *cmdWrapper) CombinedOutput() ([]byte, error) { - out, err := (*osexec.Cmd)(cmd).CombinedOutput() - if err != nil { - return out, handleError(err) - } - return out, nil -} - -func (cmd *cmdWrapper) Output() ([]byte, error) { - out, err := (*osexec.Cmd)(cmd).Output() - if err != nil { - return out, handleError(err) - } - return out, nil -} - -func handleError(err error) error { - if ee, ok := err.(*osexec.ExitError); ok { - // Force a compile fail if exitErrorWrapper can't convert to ExitError. - var x ExitError = &exitErrorWrapper{ee} - return x - } - if ee, ok := err.(*osexec.Error); ok { - if ee.Err == osexec.ErrNotFound { - return ErrExecutableNotFound - } - } - return err -} - -// exitErrorWrapper is an implementation of ExitError in terms of os/exec ExitError. -// Note: standard exec.ExitError is type *os.ProcessState, which already implements Exited(). -type exitErrorWrapper struct { - *osexec.ExitError -} - -// ExitStatus is part of the ExitError interface. -func (eew exitErrorWrapper) ExitStatus() int { - ws, ok := eew.Sys().(syscall.WaitStatus) - if !ok { - panic("can't call ExitStatus() on a non-WaitStatus exitErrorWrapper") - } - return ws.ExitStatus() -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/exec_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/exec_test.go deleted file mode 100644 index d24f9cc19..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/exec_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package exec - -import ( - osexec "os/exec" - "testing" -) - -func TestExecutorNoArgs(t *testing.T) { - ex := New() - - cmd := ex.Command("true") - out, err := cmd.CombinedOutput() - if err != nil { - t.Errorf("expected success, got %v", err) - } - if len(out) != 0 { - t.Errorf("expected no output, got %q", string(out)) - } - - cmd = ex.Command("false") - out, err = cmd.CombinedOutput() - if err == nil { - t.Errorf("expected failure, got nil error") - } - if len(out) != 0 { - t.Errorf("expected no output, got %q", string(out)) - } - ee, ok := err.(ExitError) - if !ok { - t.Errorf("expected an ExitError, got %+v", err) - } - if ee.Exited() { - if code := ee.ExitStatus(); code != 1 { - t.Errorf("expected exit status 1, got %d", code) - } - } - - cmd = ex.Command("/does/not/exist") - out, err = cmd.CombinedOutput() - if err == nil { - t.Errorf("expected failure, got nil error") - } - if ee, ok := err.(ExitError); ok { - t.Errorf("expected non-ExitError, got %+v", ee) - } -} - -func TestExecutorWithArgs(t *testing.T) { - ex := New() - - cmd := ex.Command("/bin/echo", "stdout") - out, err := cmd.CombinedOutput() - if err != nil { - t.Errorf("expected success, got %+v", err) - } - if string(out) != "stdout\n" { - t.Errorf("unexpected output: %q", string(out)) - } - - cmd = ex.Command("/bin/sh", "-c", "echo stderr > /dev/stderr") - out, err = cmd.CombinedOutput() - if err != nil { - t.Errorf("expected success, got %+v", err) - } - if string(out) != "stderr\n" { - t.Errorf("unexpected output: %q", string(out)) - } -} - -func TestLookPath(t *testing.T) { - ex := New() - - shExpected, _ := osexec.LookPath("sh") - sh, _ := ex.LookPath("sh") - if sh != shExpected { - t.Errorf("unexpected result for LookPath: got %s, expected %s", sh, shExpected) - } -} - -func TestExecutableNotFound(t *testing.T) { - exec := New() - cmd := exec.Command("fake_executable_name") - _, err := cmd.CombinedOutput() - if err != ErrExecutableNotFound { - t.Errorf("Expected error ErrExecutableNotFound but got %v", err) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/fake_exec.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/fake_exec.go deleted file mode 100644 index 40df52921..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/exec/fake_exec.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package exec - -import ( - "fmt" -) - -// A simple scripted Interface type. -type FakeExec struct { - CommandScript []FakeCommandAction - CommandCalls int - LookPathFunc func(string) (string, error) -} - -type FakeCommandAction func(cmd string, args ...string) Cmd - -func (fake *FakeExec) Command(cmd string, args ...string) Cmd { - if fake.CommandCalls > len(fake.CommandScript)-1 { - panic(fmt.Sprintf("ran out of Command() actions. Could not handle command [%d]: %s args: %v", fake.CommandCalls, cmd, args)) - } - i := fake.CommandCalls - fake.CommandCalls++ - return fake.CommandScript[i](cmd, args...) -} - -func (fake *FakeExec) LookPath(file string) (string, error) { - return fake.LookPathFunc(file) -} - -// A simple scripted Cmd type. -type FakeCmd struct { - Argv []string - CombinedOutputScript []FakeCombinedOutputAction - CombinedOutputCalls int - CombinedOutputLog [][]string - Dirs []string -} - -func InitFakeCmd(fake *FakeCmd, cmd string, args ...string) Cmd { - fake.Argv = append([]string{cmd}, args...) - return fake -} - -type FakeCombinedOutputAction func() ([]byte, error) - -func (fake *FakeCmd) SetDir(dir string) { - fake.Dirs = append(fake.Dirs, dir) -} - -func (fake *FakeCmd) CombinedOutput() ([]byte, error) { - if fake.CombinedOutputCalls > len(fake.CombinedOutputScript)-1 { - panic("ran out of CombinedOutput() actions") - } - if fake.CombinedOutputLog == nil { - fake.CombinedOutputLog = [][]string{} - } - i := fake.CombinedOutputCalls - fake.CombinedOutputLog = append(fake.CombinedOutputLog, append([]string{}, fake.Argv...)) - fake.CombinedOutputCalls++ - return fake.CombinedOutputScript[i]() -} - -func (fake *FakeCmd) Output() ([]byte, error) { - return nil, fmt.Errorf("unimplemented") -} - -// A simple fake ExitError type. -type FakeExitError struct { - Status int -} - -func (fake *FakeExitError) String() string { - return fmt.Sprintf("exit %d", fake.Status) -} - -func (fake *FakeExitError) Error() string { - return fake.String() -} - -func (fake *FakeExitError) Exited() bool { - return true -} - -func (fake *FakeExitError) ExitStatus() int { - return fake.Status -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flock/flock_unix.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flock/flock_unix.go deleted file mode 100644 index 88ca8d700..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flock/flock_unix.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build linux darwin freebsd openbsd netbsd dragonfly - -/* -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. -*/ - -package flock - -import ( - "os" - "sync" - - "golang.org/x/sys/unix" -) - -var ( - // lock guards lockfile. Assignment is not atomic. - lock sync.Mutex - // os.File has a runtime.Finalizer so the fd will be closed if the struct - // is garbage collected. Let's hold onto a reference so that doesn't happen. - lockfile *os.File -) - -// Acquire acquires a lock on a file for the duration of the process. This method -// is reentrant. -func Acquire(path string) error { - lock.Lock() - defer lock.Unlock() - var err error - if lockfile, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600); err != nil { - return err - } - - opts := unix.Flock_t{Type: unix.F_WRLCK} - if err := unix.FcntlFlock(lockfile.Fd(), unix.F_SETLKW, &opts); err != nil { - return err - } - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/doc.go deleted file mode 100644 index 485b99926..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package flushwriter implements a wrapper for a writer that flushes on every -// write if that writer implements the io.Flusher interface -package flushwriter diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/writer.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/writer.go deleted file mode 100644 index 0a9d88a78..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/writer.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package flushwriter - -import ( - "io" - "net/http" -) - -// Wrap wraps an io.Writer into a writer that flushes after every write if -// the writer implements the Flusher interface. -func Wrap(w io.Writer) io.Writer { - fw := &flushWriter{ - writer: w, - } - if flusher, ok := w.(http.Flusher); ok { - fw.flusher = flusher - } - return fw -} - -// flushWriter provides wrapper for responseWriter with HTTP streaming capabilities -type flushWriter struct { - flusher http.Flusher - writer io.Writer -} - -// Write is a FlushWriter implementation of the io.Writer that sends any buffered -// data to the client. -func (fw *flushWriter) Write(p []byte) (n int, err error) { - n, err = fw.writer.Write(p) - if err != nil { - return - } - if fw.flusher != nil { - fw.flusher.Flush() - } - return -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/writer_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/writer_test.go deleted file mode 100644 index d40b0bb00..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/flushwriter/writer_test.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package flushwriter - -import ( - "fmt" - "testing" -) - -type writerWithFlush struct { - writeCount, flushCount int - err error -} - -func (w *writerWithFlush) Flush() { - w.flushCount++ -} - -func (w *writerWithFlush) Write(p []byte) (n int, err error) { - w.writeCount++ - return len(p), w.err -} - -type writerWithNoFlush struct { - writeCount int -} - -func (w *writerWithNoFlush) Write(p []byte) (n int, err error) { - w.writeCount++ - return len(p), nil -} - -func TestWriteWithFlush(t *testing.T) { - w := &writerWithFlush{} - fw := Wrap(w) - for i := 0; i < 10; i++ { - _, err := fw.Write([]byte("Test write")) - if err != nil { - t.Errorf("Unexpected error while writing with flush writer: %v", err) - } - } - if w.flushCount != 10 { - t.Errorf("Flush not called the expected number of times. Actual: %d", w.flushCount) - } - if w.writeCount != 10 { - t.Errorf("Write not called the expected number of times. Actual: %d", w.writeCount) - } -} - -func TestWriteWithoutFlush(t *testing.T) { - w := &writerWithNoFlush{} - fw := Wrap(w) - for i := 0; i < 10; i++ { - _, err := fw.Write([]byte("Test write")) - if err != nil { - t.Errorf("Unexpected error while writing with flush writer: %v", err) - } - } - if w.writeCount != 10 { - t.Errorf("Write not called the expected number of times. Actual: %d", w.writeCount) - } -} - -func TestWriteError(t *testing.T) { - e := fmt.Errorf("Error") - w := &writerWithFlush{err: e} - fw := Wrap(w) - _, err := fw.Write([]byte("Test write")) - if err != e { - t.Errorf("Did not get expected error. Got: %#v", err) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/hash/hash_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/hash/hash_test.go deleted file mode 100644 index 3bba3b074..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/hash/hash_test.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package hash - -import ( - "fmt" - "hash/adler32" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -type A struct { - x int - y string -} - -type B struct { - x []int - y map[string]bool -} - -type C struct { - x int - y string -} - -func (c C) String() string { - return fmt.Sprintf("%d:%s", c.x, c.y) -} - -func TestDeepHashObject(t *testing.T) { - successCases := []func() interface{}{ - func() interface{} { return 8675309 }, - func() interface{} { return "Jenny, I got your number" }, - func() interface{} { return []string{"eight", "six", "seven"} }, - func() interface{} { return [...]int{5, 3, 0, 9} }, - func() interface{} { return map[int]string{8: "8", 6: "6", 7: "7"} }, - func() interface{} { return map[string]int{"5": 5, "3": 3, "0": 0, "9": 9} }, - func() interface{} { return A{867, "5309"} }, - func() interface{} { return &A{867, "5309"} }, - func() interface{} { - return B{[]int{8, 6, 7}, map[string]bool{"5": true, "3": true, "0": true, "9": true}} - }, - func() interface{} { return map[A]bool{A{8675309, "Jenny"}: true, A{9765683, "!Jenny"}: false} }, - func() interface{} { return map[C]bool{C{8675309, "Jenny"}: true, C{9765683, "!Jenny"}: false} }, - func() interface{} { return map[*A]bool{&A{8675309, "Jenny"}: true, &A{9765683, "!Jenny"}: false} }, - func() interface{} { return map[*C]bool{&C{8675309, "Jenny"}: true, &C{9765683, "!Jenny"}: false} }, - } - - for _, tc := range successCases { - hasher1 := adler32.New() - DeepHashObject(hasher1, tc()) - hash1 := hasher1.Sum32() - DeepHashObject(hasher1, tc()) - hash2 := hasher1.Sum32() - if hash1 != hash2 { - t.Fatalf("hash of the same object (%q) produced different results: %d vs %d", toString(tc()), hash1, hash2) - } - for i := 0; i < 100; i++ { - hasher2 := adler32.New() - - DeepHashObject(hasher1, tc()) - hash1a := hasher1.Sum32() - DeepHashObject(hasher2, tc()) - hash2a := hasher2.Sum32() - - if hash1a != hash1 { - t.Errorf("repeated hash of the same object (%q) produced different results: %d vs %d", toString(tc()), hash1, hash1a) - } - if hash2a != hash2 { - t.Errorf("repeated hash of the same object (%q) produced different results: %d vs %d", toString(tc()), hash2, hash2a) - } - if hash1a != hash2a { - t.Errorf("hash of the same object produced (%q) different results: %d vs %d", toString(tc()), hash1a, hash2a) - } - } - } -} - -func toString(obj interface{}) string { - return spew.Sprintf("%#v", obj) -} - -type wheel struct { - radius uint32 -} - -type unicycle struct { - primaryWheel *wheel - licencePlateID string - tags map[string]string -} - -func TestDeepObjectPointer(t *testing.T) { - // Arrange - wheel1 := wheel{radius: 17} - wheel2 := wheel{radius: 22} - wheel3 := wheel{radius: 17} - - myUni1 := unicycle{licencePlateID: "blah", primaryWheel: &wheel1, tags: map[string]string{"color": "blue", "name": "john"}} - myUni2 := unicycle{licencePlateID: "blah", primaryWheel: &wheel2, tags: map[string]string{"color": "blue", "name": "john"}} - myUni3 := unicycle{licencePlateID: "blah", primaryWheel: &wheel3, tags: map[string]string{"color": "blue", "name": "john"}} - - // Run it more than once to verify determinism of hasher. - for i := 0; i < 100; i++ { - hasher1 := adler32.New() - hasher2 := adler32.New() - hasher3 := adler32.New() - // Act - DeepHashObject(hasher1, myUni1) - hash1 := hasher1.Sum32() - DeepHashObject(hasher1, myUni1) - hash1a := hasher1.Sum32() - DeepHashObject(hasher2, myUni2) - hash2 := hasher2.Sum32() - DeepHashObject(hasher3, myUni3) - hash3 := hasher3.Sum32() - - // Assert - if hash1 != hash1a { - t.Errorf("repeated hash of the same object produced different results: %d vs %d", hash1, hash1a) - } - - if hash1 == hash2 { - t.Errorf("hash1 (%d) and hash2(%d) must be different because they have different values for wheel size", hash1, hash2) - } - - if hash1 != hash3 { - t.Errorf("hash1 (%d) and hash3(%d) must be the same because although they point to different objects, they have the same values for wheel size", hash1, hash3) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/doc.go deleted file mode 100644 index b474fc572..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package httpstream adds multiplexed streaming support to HTTP requests and -// responses via connection upgrades. -package httpstream diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/httpstream.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/httpstream.go deleted file mode 100644 index 4f6b608ce..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/httpstream.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package httpstream - -import ( - "fmt" - "io" - "net/http" - "strings" - "time" -) - -const ( - HeaderConnection = "Connection" - HeaderUpgrade = "Upgrade" - HeaderProtocolVersion = "X-Stream-Protocol-Version" - HeaderAcceptedProtocolVersions = "X-Accepted-Stream-Protocol-Versions" -) - -// NewStreamHandler defines a function that is called when a new Stream is -// received. If no error is returned, the Stream is accepted; otherwise, -// the stream is rejected. After the reply frame has been sent, replySent is closed. -type NewStreamHandler func(stream Stream, replySent <-chan struct{}) error - -// NoOpNewStreamHandler is a stream handler that accepts a new stream and -// performs no other logic. -func NoOpNewStreamHandler(stream Stream, replySent <-chan struct{}) error { return nil } - -// Dialer knows how to open a streaming connection to a server. -type Dialer interface { - - // Dial opens a streaming connection to a server using one of the protocols - // specified (in order of most preferred to least preferred). - Dial(protocols ...string) (Connection, string, error) -} - -// UpgradeRoundTripper is a type of http.RoundTripper that is able to upgrade -// HTTP requests to support multiplexed bidirectional streams. After RoundTrip() -// is invoked, if the upgrade is successful, clients may retrieve the upgraded -// connection by calling UpgradeRoundTripper.Connection(). -type UpgradeRoundTripper interface { - http.RoundTripper - // NewConnection validates the response and creates a new Connection. - NewConnection(resp *http.Response) (Connection, error) -} - -// ResponseUpgrader knows how to upgrade HTTP requests and responses to -// add streaming support to them. -type ResponseUpgrader interface { - // UpgradeResponse upgrades an HTTP response to one that supports multiplexed - // streams. newStreamHandler will be called asynchronously whenever the - // other end of the upgraded connection creates a new stream. - UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler NewStreamHandler) Connection -} - -// Connection represents an upgraded HTTP connection. -type Connection interface { - // CreateStream creates a new Stream with the supplied headers. - CreateStream(headers http.Header) (Stream, error) - // Close resets all streams and closes the connection. - Close() error - // CloseChan returns a channel that is closed when the underlying connection is closed. - CloseChan() <-chan bool - // SetIdleTimeout sets the amount of time the connection may remain idle before - // it is automatically closed. - SetIdleTimeout(timeout time.Duration) -} - -// Stream represents a bidirectional communications channel that is part of an -// upgraded connection. -type Stream interface { - io.ReadWriteCloser - // Reset closes both directions of the stream, indicating that neither client - // or server can use it any more. - Reset() error - // Headers returns the headers used to create the stream. - Headers() http.Header - // Identifier returns the stream's ID. - Identifier() uint32 -} - -// IsUpgradeRequest returns true if the given request is a connection upgrade request -func IsUpgradeRequest(req *http.Request) bool { - for _, h := range req.Header[http.CanonicalHeaderKey(HeaderConnection)] { - if strings.Contains(strings.ToLower(h), strings.ToLower(HeaderUpgrade)) { - return true - } - } - return false -} - -func negotiateProtocol(clientProtocols, serverProtocols []string) string { - for i := range clientProtocols { - for j := range serverProtocols { - if clientProtocols[i] == serverProtocols[j] { - return clientProtocols[i] - } - } - } - return "" -} - -// Handshake performs a subprotocol negotiation. If the client did not request -// a specific subprotocol, defaultProtocol is used. If the client did request a -// subprotocol, Handshake will select the first common value found in -// serverProtocols. If a match is found, Handshake adds a response header -// indicating the chosen subprotocol. If no match is found, HTTP forbidden is -// returned, along with a response header containing the list of protocols the -// server can accept. -func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []string, defaultProtocol string) (string, error) { - clientProtocols := req.Header[http.CanonicalHeaderKey(HeaderProtocolVersion)] - if len(clientProtocols) == 0 { - // Kube 1.0 client that didn't support subprotocol negotiation - // TODO remove this defaulting logic once Kube 1.0 is no longer supported - w.Header().Add(HeaderProtocolVersion, defaultProtocol) - return defaultProtocol, nil - } - - negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols) - if len(negotiatedProtocol) == 0 { - w.WriteHeader(http.StatusForbidden) - for i := range serverProtocols { - w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i]) - } - fmt.Fprintf(w, "unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols) - return "", fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server supports %v", clientProtocols, serverProtocols) - } - - w.Header().Add(HeaderProtocolVersion, negotiatedProtocol) - return negotiatedProtocol, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/httpstream_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/httpstream_test.go deleted file mode 100644 index 7a1bbaefb..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/httpstream_test.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package httpstream - -import ( - "net/http" - "reflect" - "testing" -) - -type responseWriter struct { - header http.Header - statusCode *int -} - -func newResponseWriter() *responseWriter { - return &responseWriter{ - header: make(http.Header), - } -} - -func (r *responseWriter) Header() http.Header { - return r.header -} - -func (r *responseWriter) WriteHeader(code int) { - r.statusCode = &code -} - -func (r *responseWriter) Write([]byte) (int, error) { - return 0, nil -} - -func TestHandshake(t *testing.T) { - defaultProtocol := "default" - - tests := map[string]struct { - clientProtocols []string - serverProtocols []string - expectedProtocol string - expectError bool - }{ - "no client protocols": { - clientProtocols: []string{}, - serverProtocols: []string{"a", "b"}, - expectedProtocol: defaultProtocol, - }, - "no common protocol": { - clientProtocols: []string{"c"}, - serverProtocols: []string{"a", "b"}, - expectedProtocol: "", - expectError: true, - }, - "common protocol": { - clientProtocols: []string{"b"}, - serverProtocols: []string{"a", "b"}, - expectedProtocol: "b", - }, - } - - for name, test := range tests { - req, err := http.NewRequest("GET", "http://www.example.com/", nil) - if err != nil { - t.Fatalf("%s: error creating request: %v", name, err) - } - - for _, p := range test.clientProtocols { - req.Header.Add(HeaderProtocolVersion, p) - } - - w := newResponseWriter() - negotiated, err := Handshake(req, w, test.serverProtocols, defaultProtocol) - - // verify negotiated protocol - if e, a := test.expectedProtocol, negotiated; e != a { - t.Errorf("%s: protocol: expected %q, got %q", name, e, a) - } - - if test.expectError { - if err == nil { - t.Errorf("%s: expected error but did not get one", name) - } - if w.statusCode == nil { - t.Errorf("%s: expected w.statusCode to be set", name) - } else if e, a := http.StatusForbidden, *w.statusCode; e != a { - t.Errorf("%s: w.statusCode: expected %d, got %d", name, e, a) - } - if e, a := test.serverProtocols, w.Header()[HeaderAcceptedProtocolVersions]; !reflect.DeepEqual(e, a) { - t.Errorf("%s: accepted server protocols: expected %v, got %v", name, e, a) - } - continue - } - if !test.expectError && err != nil { - t.Errorf("%s: unexpected error: %v", name, err) - continue - } - if w.statusCode != nil { - t.Errorf("%s: unexpected non-nil w.statusCode: %d", w.statusCode) - } - - // verify response headers - if e, a := []string{test.expectedProtocol}, w.Header()[HeaderProtocolVersion]; !reflect.DeepEqual(e, a) { - t.Errorf("%s: protocol response header: expected %v, got %v", name, e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/connection.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/connection.go deleted file mode 100644 index 884c6e203..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/connection.go +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package spdy - -import ( - "net" - "net/http" - "sync" - "time" - - "github.com/docker/spdystream" - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/util/httpstream" -) - -// connection maintains state about a spdystream.Connection and its associated -// streams. -type connection struct { - conn *spdystream.Connection - streams []httpstream.Stream - streamLock sync.Mutex - newStreamHandler httpstream.NewStreamHandler -} - -// NewClientConnection creates a new SPDY client connection. -func NewClientConnection(conn net.Conn) (httpstream.Connection, error) { - spdyConn, err := spdystream.NewConnection(conn, false) - if err != nil { - defer conn.Close() - return nil, err - } - - return newConnection(spdyConn, httpstream.NoOpNewStreamHandler), nil -} - -// NewServerConnection creates a new SPDY server connection. newStreamHandler -// will be invoked when the server receives a newly created stream from the -// client. -func NewServerConnection(conn net.Conn, newStreamHandler httpstream.NewStreamHandler) (httpstream.Connection, error) { - spdyConn, err := spdystream.NewConnection(conn, true) - if err != nil { - defer conn.Close() - return nil, err - } - - return newConnection(spdyConn, newStreamHandler), nil -} - -// newConnection returns a new connection wrapping conn. newStreamHandler -// will be invoked when the server receives a newly created stream from the -// client. -func newConnection(conn *spdystream.Connection, newStreamHandler httpstream.NewStreamHandler) httpstream.Connection { - c := &connection{conn: conn, newStreamHandler: newStreamHandler} - go conn.Serve(c.newSpdyStream) - return c -} - -// createStreamResponseTimeout indicates how long to wait for the other side to -// acknowledge the new stream before timing out. -const createStreamResponseTimeout = 30 * time.Second - -// Close first sends a reset for all of the connection's streams, and then -// closes the underlying spdystream.Connection. -func (c *connection) Close() error { - c.streamLock.Lock() - for _, s := range c.streams { - s.Close() - } - c.streams = make([]httpstream.Stream, 0) - c.streamLock.Unlock() - - return c.conn.Close() -} - -// CreateStream creates a new stream with the specified headers and registers -// it with the connection. -func (c *connection) CreateStream(headers http.Header) (httpstream.Stream, error) { - stream, err := c.conn.CreateStream(headers, nil, false) - if err != nil { - return nil, err - } - if err = stream.WaitTimeout(createStreamResponseTimeout); err != nil { - return nil, err - } - - c.registerStream(stream) - return stream, nil -} - -// registerStream adds the stream s to the connection's list of streams that -// it owns. -func (c *connection) registerStream(s httpstream.Stream) { - c.streamLock.Lock() - c.streams = append(c.streams, s) - c.streamLock.Unlock() -} - -// CloseChan returns a channel that, when closed, indicates that the underlying -// spdystream.Connection has been closed. -func (c *connection) CloseChan() <-chan bool { - return c.conn.CloseChan() -} - -// newSpdyStream is the internal new stream handler used by spdystream.Connection.Serve. -// It calls connection's newStreamHandler, giving it the opportunity to accept or reject -// the stream. If newStreamHandler returns an error, the stream is rejected. If not, the -// stream is accepted and registered with the connection. -func (c *connection) newSpdyStream(stream *spdystream.Stream) { - replySent := make(chan struct{}) - err := c.newStreamHandler(stream, replySent) - rejectStream := (err != nil) - if rejectStream { - glog.Warningf("Stream rejected: %v", err) - stream.Reset() - return - } - - c.registerStream(stream) - stream.SendReply(http.Header{}, rejectStream) - close(replySent) -} - -// SetIdleTimeout sets the amount of time the connection may remain idle before -// it is automatically closed. -func (c *connection) SetIdleTimeout(timeout time.Duration) { - c.conn.SetIdleTimeout(timeout) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper.go deleted file mode 100644 index a054d30c2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper.go +++ /dev/null @@ -1,229 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package spdy - -import ( - "bufio" - "crypto/tls" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/http/httputil" - "net/url" - "strings" - - "k8s.io/kubernetes/pkg/api" - 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" -) - -// SpdyRoundTripper knows how to upgrade an HTTP request to one that supports -// multiplexed streams. After RoundTrip() is invoked, Conn will be set -// and usable. SpdyRoundTripper implements the UpgradeRoundTripper interface. -type SpdyRoundTripper struct { - //tlsConfig holds the TLS configuration settings to use when connecting - //to the remote server. - tlsConfig *tls.Config - - /* TODO according to http://golang.org/pkg/net/http/#RoundTripper, a RoundTripper - must be safe for use by multiple concurrent goroutines. If this is absolutely - necessary, we could keep a map from http.Request to net.Conn. In practice, - a client will create an http.Client, set the transport to a new insteace of - SpdyRoundTripper, and use it a single time, so this hopefully won't be an issue. - */ - // conn is the underlying network connection to the remote server. - conn net.Conn - - // Dialer is the dialer used to connect. Used if non-nil. - Dialer *net.Dialer -} - -// NewRoundTripper creates a new SpdyRoundTripper that will use -// the specified tlsConfig. -func NewRoundTripper(tlsConfig *tls.Config) httpstream.UpgradeRoundTripper { - return NewSpdyRoundTripper(tlsConfig) -} - -// NewSpdyRoundTripper creates a new SpdyRoundTripper that will use -// the specified tlsConfig. This function is mostly meant for unit tests. -func NewSpdyRoundTripper(tlsConfig *tls.Config) *SpdyRoundTripper { - return &SpdyRoundTripper{tlsConfig: tlsConfig} -} - -// dial dials the host specified by req, using TLS if appropriate, optionally -// using a proxy server if one is configured via environment variables. -func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) { - proxyURL, err := http.ProxyFromEnvironment(req) - if err != nil { - return nil, err - } - - if proxyURL == nil { - return s.dialWithoutProxy(req.URL) - } - - // ensure we use a canonical host with proxyReq - targetHost := netutil.CanonicalAddr(req.URL) - - // proxying logic adapted from http://blog.h6t.eu/post/74098062923/golang-websocket-with-http-proxy-support - proxyReq := http.Request{ - Method: "CONNECT", - URL: &url.URL{}, - Host: targetHost, - } - - proxyDialConn, err := s.dialWithoutProxy(proxyURL) - if err != nil { - return nil, err - } - - proxyClientConn := httputil.NewProxyClientConn(proxyDialConn, nil) - _, err = proxyClientConn.Do(&proxyReq) - if err != nil && err != httputil.ErrPersistEOF { - return nil, err - } - - rwc, _ := proxyClientConn.Hijack() - - if req.URL.Scheme != "https" { - return rwc, nil - } - - host, _, err := net.SplitHostPort(req.URL.Host) - if err != nil { - return nil, err - } - - if len(s.tlsConfig.ServerName) == 0 { - s.tlsConfig.ServerName = host - } - - tlsConn := tls.Client(rwc, s.tlsConfig) - - // need to manually call Handshake() so we can call VerifyHostname() below - if err := tlsConn.Handshake(); err != nil { - return nil, err - } - - if err := tlsConn.VerifyHostname(host); err != nil { - return nil, err - } - - return tlsConn, nil -} - -// dialWithoutProxy dials the host specified by url, using TLS if appropriate. -func (s *SpdyRoundTripper) dialWithoutProxy(url *url.URL) (net.Conn, error) { - dialAddr := netutil.CanonicalAddr(url) - - if url.Scheme == "http" { - if s.Dialer == nil { - return net.Dial("tcp", dialAddr) - } else { - return s.Dialer.Dial("tcp", dialAddr) - } - } - - // TODO validate the TLSClientConfig is set up? - var conn *tls.Conn - var err error - if s.Dialer == nil { - conn, err = tls.Dial("tcp", dialAddr, s.tlsConfig) - } else { - conn, err = tls.DialWithDialer(s.Dialer, "tcp", dialAddr, s.tlsConfig) - } - if err != nil { - return nil, err - } - - // Return if we were configured to skip validation - if s.tlsConfig != nil && s.tlsConfig.InsecureSkipVerify { - return conn, nil - } - - host, _, err := net.SplitHostPort(dialAddr) - if err != nil { - return nil, err - } - err = conn.VerifyHostname(host) - if err != nil { - return nil, err - } - - return conn, nil -} - -// RoundTrip executes the Request and upgrades it. After a successful upgrade, -// clients may call SpdyRoundTripper.Connection() to retrieve the upgraded -// connection. -func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - // TODO what's the best way to clone the request? - r := *req - req = &r - req.Header.Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade) - req.Header.Add(httpstream.HeaderUpgrade, HeaderSpdy31) - - conn, err := s.dial(req) - if err != nil { - return nil, err - } - - err = req.Write(conn) - if err != nil { - return nil, err - } - - resp, err := http.ReadResponse(bufio.NewReader(conn), req) - if err != nil { - return nil, err - } - - s.conn = conn - - return resp, nil -} - -// NewConnection validates the upgrade response, creating and returning a new -// httpstream.Connection if there were no errors. -func (s *SpdyRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) { - connectionHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderConnection)) - upgradeHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderUpgrade)) - if (resp.StatusCode != http.StatusSwitchingProtocols) || !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) { - defer resp.Body.Close() - responseError := "" - responseErrorBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - responseError = "unable to read error from server response" - } else { - // TODO: I don't belong here, I should be abstracted from this class - if obj, _, err := api.Codecs.UniversalDecoder().Decode(responseErrorBytes, nil, &unversioned.Status{}); err == nil { - if status, ok := obj.(*unversioned.Status); ok { - return nil, &apierrors.StatusError{ErrStatus: *status} - } - } - responseError = string(responseErrorBytes) - responseError = strings.TrimSpace(responseError) - } - - return nil, fmt.Errorf("unable to upgrade connection: %s", responseError) - } - - return NewClientConnection(s.conn) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper_test.go deleted file mode 100644 index 7ca1d42ad..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper_test.go +++ /dev/null @@ -1,251 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package spdy - -import ( - "crypto/tls" - "crypto/x509" - "io" - "net/http" - "net/http/httptest" - "testing" - - "k8s.io/kubernetes/pkg/util/httpstream" -) - -func TestRoundTripAndNewConnection(t *testing.T) { - - localhostPool := x509.NewCertPool() - if !localhostPool.AppendCertsFromPEM(localhostCert) { - t.Errorf("error setting up localhostCert pool") - } - - testCases := map[string]struct { - serverFunc func(http.Handler) *httptest.Server - clientTLS *tls.Config - serverConnectionHeader string - serverUpgradeHeader string - serverStatusCode int - shouldError bool - }{ - "no headers": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "", - serverUpgradeHeader: "", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, - }, - "no upgrade header": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, - }, - "no connection header": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, - }, - "no switching protocol status code": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusForbidden, - shouldError: true, - }, - "http": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "https (invalid hostname + InsecureSkipVerify)": { - serverFunc: func(h http.Handler) *httptest.Server { - cert, err := tls.X509KeyPair(exampleCert, exampleKey) - if err != nil { - t.Errorf("https (invalid hostname): proxy_test: %v", err) - } - ts := httptest.NewUnstartedServer(h) - ts.TLS = &tls.Config{ - Certificates: []tls.Certificate{cert}, - } - ts.StartTLS() - return ts - }, - clientTLS: &tls.Config{InsecureSkipVerify: true}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "https (valid hostname + RootCAs)": { - serverFunc: func(h http.Handler) *httptest.Server { - cert, err := tls.X509KeyPair(localhostCert, localhostKey) - if err != nil { - t.Errorf("https (valid hostname): proxy_test: %v", err) - } - ts := httptest.NewUnstartedServer(h) - ts.TLS = &tls.Config{ - Certificates: []tls.Certificate{cert}, - } - ts.StartTLS() - return ts - }, - clientTLS: &tls.Config{RootCAs: localhostPool}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - } - - for k, testCase := range testCases { - server := testCase.serverFunc(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if testCase.shouldError { - if e, a := httpstream.HeaderUpgrade, req.Header.Get(httpstream.HeaderConnection); e != a { - t.Fatalf("%s: Expected connection=upgrade header, got '%s", k, a) - } - - w.Header().Set(httpstream.HeaderConnection, testCase.serverConnectionHeader) - w.Header().Set(httpstream.HeaderUpgrade, testCase.serverUpgradeHeader) - w.WriteHeader(testCase.serverStatusCode) - - return - } - - streamCh := make(chan httpstream.Stream) - - responseUpgrader := NewResponseUpgrader() - spdyConn := responseUpgrader.UpgradeResponse(w, req, func(s httpstream.Stream, replySent <-chan struct{}) error { - streamCh <- s - return nil - }) - if spdyConn == nil { - t.Fatalf("%s: unexpected nil spdyConn", k) - } - defer spdyConn.Close() - - stream := <-streamCh - io.Copy(stream, stream) - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - req, err := http.NewRequest("GET", server.URL, nil) - if err != nil { - t.Fatalf("%s: Error creating request: %s", k, err) - } - - spdyTransport := NewRoundTripper(testCase.clientTLS) - client := &http.Client{Transport: spdyTransport} - - resp, err := client.Do(req) - if err != nil { - t.Fatalf("%s: unexpected error from client.Do: %s", k, err) - } - - conn, err := spdyTransport.NewConnection(resp) - haveErr := err != nil - if e, a := testCase.shouldError, haveErr; e != a { - t.Fatalf("%s: shouldError=%t, got %t: %v", k, e, a, err) - } - if testCase.shouldError { - continue - } - defer conn.Close() - - if resp.StatusCode != http.StatusSwitchingProtocols { - t.Fatalf("%s: expected http 101 switching protocols, got %d", k, resp.StatusCode) - } - - stream, err := conn.CreateStream(http.Header{}) - if err != nil { - t.Fatalf("%s: error creating client stream: %s", k, err) - } - - n, err := stream.Write([]byte("hello")) - if err != nil { - t.Fatalf("%s: error writing to stream: %s", k, err) - } - if n != 5 { - t.Fatalf("%s: Expected to write 5 bytes, but actually wrote %d", k, n) - } - - b := make([]byte, 5) - n, err = stream.Read(b) - if err != nil { - t.Fatalf("%s: error reading from stream: %s", k, err) - } - if n != 5 { - t.Fatalf("%s: Expected to read 5 bytes, but actually read %d", k, n) - } - if e, a := "hello", string(b[0:n]); e != a { - t.Fatalf("%s: expected '%s', got '%s'", k, e, a) - } - } -} - -// exampleCert was generated from crypto/tls/generate_cert.go with the following command: -// go run generate_cert.go --rsa-bits 512 --host example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h -var exampleCert = []byte(`-----BEGIN CERTIFICATE----- -MIIBcjCCAR6gAwIBAgIQBOUTYowZaENkZi0faI9DgTALBgkqhkiG9w0BAQswEjEQ -MA4GA1UEChMHQWNtZSBDbzAgFw03MDAxMDEwMDAwMDBaGA8yMDg0MDEyOTE2MDAw -MFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCZ -xfR3sgeHBraGFfF/24tTn4PRVAHOf2UOOxSQRs+aYjNqimFqf/SRIblQgeXdBJDR -gVK5F1Js2zwlehw0bHxRAgMBAAGjUDBOMA4GA1UdDwEB/wQEAwIApDATBgNVHSUE -DDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MBYGA1UdEQQPMA2CC2V4YW1w -bGUuY29tMAsGCSqGSIb3DQEBCwNBAI/mfBB8dm33IpUl+acSyWfL6gX5Wc0FFyVj -dKeesE1XBuPX1My/rzU6Oy/YwX7LOL4FaeNUS6bbL4axSLPKYSs= ------END CERTIFICATE-----`) - -var exampleKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIBOgIBAAJBAJnF9HeyB4cGtoYV8X/bi1Ofg9FUAc5/ZQ47FJBGz5piM2qKYWp/ -9JEhuVCB5d0EkNGBUrkXUmzbPCV6HDRsfFECAwEAAQJBAJLH9yPuButniACTn5L5 -IJQw1mWQt6zBw9eCo41YWkA0866EgjC53aPZaRjXMp0uNJGdIsys2V5rCOOLWN2C -ODECIQDICHsi8QQQ9wpuJy8X5l8MAfxHL+DIqI84wQTeVM91FQIhAMTME8A18/7h -1Ad6drdnxAkuC0tX6Sx0LDozrmen+HFNAiAlcEDrt0RVkIcpOrg7tuhPLQf0oudl -Zvb3Xlj069awSQIgcT15E/43w2+RASifzVNhQ2MCTr1sSA8lL+xzK+REmnUCIBhQ -j4139pf8Re1J50zBxS/JlQfgDQi9sO9pYeiHIxNs ------END RSA PRIVATE KEY-----`) - -// localhostCert was generated from crypto/tls/generate_cert.go with the following command: -// go run generate_cert.go --rsa-bits 512 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h -var localhostCert = []byte(`-----BEGIN CERTIFICATE----- -MIIBdzCCASOgAwIBAgIBADALBgkqhkiG9w0BAQUwEjEQMA4GA1UEChMHQWNtZSBD -bzAeFw03MDAxMDEwMDAwMDBaFw00OTEyMzEyMzU5NTlaMBIxEDAOBgNVBAoTB0Fj -bWUgQ28wWjALBgkqhkiG9w0BAQEDSwAwSAJBAN55NcYKZeInyTuhcCwFMhDHCmwa -IUSdtXdcbItRB/yfXGBhiex00IaLXQnSU+QZPRZWYqeTEbFSgihqi1PUDy8CAwEA -AaNoMGYwDgYDVR0PAQH/BAQDAgCkMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1Ud -EwEB/wQFMAMBAf8wLgYDVR0RBCcwJYILZXhhbXBsZS5jb22HBH8AAAGHEAAAAAAA -AAAAAAAAAAAAAAEwCwYJKoZIhvcNAQEFA0EAAoQn/ytgqpiLcZu9XKbCJsJcvkgk -Se6AbGXgSlq+ZCEVo0qIwSgeBqmsJxUu7NCSOwVJLYNEBO2DtIxoYVk+MA== ------END CERTIFICATE-----`) - -// localhostKey is the private key for localhostCert. -var localhostKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIBPAIBAAJBAN55NcYKZeInyTuhcCwFMhDHCmwaIUSdtXdcbItRB/yfXGBhiex0 -0IaLXQnSU+QZPRZWYqeTEbFSgihqi1PUDy8CAwEAAQJBAQdUx66rfh8sYsgfdcvV -NoafYpnEcB5s4m/vSVe6SU7dCK6eYec9f9wpT353ljhDUHq3EbmE4foNzJngh35d -AekCIQDhRQG5Li0Wj8TM4obOnnXUXf1jRv0UkzE9AHWLG5q3AwIhAPzSjpYUDjVW -MCUXgckTpKCuGwbJk7424Nb8bLzf3kllAiA5mUBgjfr/WtFSJdWcPQ4Zt9KTMNKD -EUO0ukpTwEIl6wIhAMbGqZK3zAAFdq8DD2jPx+UJXnh0rnOkZBzDtJ6/iN69AiEA -1Aq8MJgTaYsDQWyU/hDq5YkDJc9e9DSCvUIzqxQWMQE= ------END RSA PRIVATE KEY-----`) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade.go deleted file mode 100644 index b7d126a5d..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package spdy - -import ( - "fmt" - "net/http" - "strings" - - "k8s.io/kubernetes/pkg/util/httpstream" - "k8s.io/kubernetes/pkg/util/runtime" -) - -const HeaderSpdy31 = "SPDY/3.1" - -// responseUpgrader knows how to upgrade HTTP responses. It -// implements the httpstream.ResponseUpgrader interface. -type responseUpgrader struct { -} - -// NewResponseUpgrader returns a new httpstream.ResponseUpgrader that is -// capable of upgrading HTTP responses using SPDY/3.1 via the -// spdystream package. -func NewResponseUpgrader() httpstream.ResponseUpgrader { - return responseUpgrader{} -} - -// UpgradeResponse upgrades an HTTP response to one that supports multiplexed -// streams. newStreamHandler will be called synchronously whenever the -// other end of the upgraded connection creates a new stream. -func (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler httpstream.NewStreamHandler) httpstream.Connection { - connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection)) - upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade)) - if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) { - w.WriteHeader(http.StatusBadRequest) - fmt.Fprintf(w, "unable to upgrade: missing upgrade headers in request: %#v", req.Header) - return nil - } - - hijacker, ok := w.(http.Hijacker) - if !ok { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "unable to upgrade: unable to hijack response") - return nil - } - - w.Header().Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade) - w.Header().Add(httpstream.HeaderUpgrade, HeaderSpdy31) - w.WriteHeader(http.StatusSwitchingProtocols) - - conn, _, err := hijacker.Hijack() - if err != nil { - runtime.HandleError(fmt.Errorf("unable to upgrade: error hijacking response: %v", err)) - return nil - } - - spdyConn, err := NewServerConnection(conn, newStreamHandler) - if err != nil { - runtime.HandleError(fmt.Errorf("unable to upgrade: error creating SPDY server connection: %v", err)) - return nil - } - - return spdyConn -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade_test.go deleted file mode 100644 index 2ddfd5a59..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade_test.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package spdy - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -func TestUpgradeResponse(t *testing.T) { - testCases := []struct { - connectionHeader string - upgradeHeader string - shouldError bool - }{ - { - connectionHeader: "", - upgradeHeader: "", - shouldError: true, - }, - { - connectionHeader: "Upgrade", - upgradeHeader: "", - shouldError: true, - }, - { - connectionHeader: "", - upgradeHeader: "SPDY/3.1", - shouldError: true, - }, - { - connectionHeader: "Upgrade", - upgradeHeader: "SPDY/3.1", - shouldError: false, - }, - } - - for i, testCase := range testCases { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - upgrader := NewResponseUpgrader() - conn := upgrader.UpgradeResponse(w, req, nil) - haveErr := conn == nil - if e, a := testCase.shouldError, haveErr; e != a { - t.Fatalf("%d: expected shouldErr=%t, got %t", i, testCase.shouldError, haveErr) - } - if haveErr { - return - } - if conn == nil { - t.Fatalf("%d: unexpected nil conn", i) - } - defer conn.Close() - })) - // TODO: Uncomment when fix #19254 - // defer server.Close() - - req, err := http.NewRequest("GET", server.URL, nil) - if err != nil { - t.Fatalf("%d: error creating request: %s", i, err) - } - - req.Header.Set("Connection", testCase.connectionHeader) - req.Header.Set("Upgrade", testCase.upgradeHeader) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - t.Fatalf("%d: unexpected non-nil err from client.Do: %s", i, err) - } - - if testCase.shouldError { - continue - } - - if resp.StatusCode != http.StatusSwitchingProtocols { - t.Fatalf("%d: expected status 101 switching protocols, got %d", i, resp.StatusCode) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/integer/integer_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/integer/integer_test.go deleted file mode 100644 index 0f8856738..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/integer/integer_test.go +++ /dev/null @@ -1,143 +0,0 @@ -/* -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. -*/ - -package integer - -import "testing" - -func TestIntMax(t *testing.T) { - tests := []struct { - nums []int - expectedMax int - }{ - { - nums: []int{-1, 0}, - expectedMax: 0, - }, - { - nums: []int{-1, -2}, - expectedMax: -1, - }, - { - nums: []int{0, 1}, - expectedMax: 1, - }, - { - nums: []int{1, 2}, - expectedMax: 2, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if max := IntMax(test.nums[0], test.nums[1]); max != test.expectedMax { - t.Errorf("expected %v, got %v", test.expectedMax, max) - } - } -} - -func TestIntMin(t *testing.T) { - tests := []struct { - nums []int - expectedMin int - }{ - { - nums: []int{-1, 0}, - expectedMin: -1, - }, - { - nums: []int{-1, -2}, - expectedMin: -2, - }, - { - nums: []int{0, 1}, - expectedMin: 0, - }, - { - nums: []int{1, 2}, - expectedMin: 1, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if min := IntMin(test.nums[0], test.nums[1]); min != test.expectedMin { - t.Errorf("expected %v, got %v", test.expectedMin, min) - } - } -} - -func TestInt64Max(t *testing.T) { - tests := []struct { - nums []int64 - expectedMax int64 - }{ - { - nums: []int64{-1, 0}, - expectedMax: 0, - }, - { - nums: []int64{-1, -2}, - expectedMax: -1, - }, - { - nums: []int64{0, 1}, - expectedMax: 1, - }, - { - nums: []int64{1, 2}, - expectedMax: 2, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if max := Int64Max(test.nums[0], test.nums[1]); max != test.expectedMax { - t.Errorf("expected %v, got %v", test.expectedMax, max) - } - } -} - -func TestInt64Min(t *testing.T) { - tests := []struct { - nums []int64 - expectedMin int64 - }{ - { - nums: []int64{-1, 0}, - expectedMin: -1, - }, - { - nums: []int64{-1, -2}, - expectedMin: -2, - }, - { - nums: []int64{0, 1}, - expectedMin: 0, - }, - { - nums: []int64{1, 2}, - expectedMin: 1, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if min := Int64Min(test.nums[0], test.nums[1]); min != test.expectedMin { - t.Errorf("expected %v, got %v", test.expectedMin, min) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr.go index 05b572cf5..aa3cde1fa 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr.go @@ -116,13 +116,17 @@ func (intstr *IntOrString) Fuzz(c fuzz.Continue) { } } -func GetValueFromIntOrPercent(intOrPercent *IntOrString, total int) (int, error) { +func GetValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) { value, isPercent, err := getIntOrPercentValue(intOrPercent) if err != nil { return 0, fmt.Errorf("invalid value for IntOrString: %v", err) } if isPercent { - value = int(math.Ceil(float64(value) * (float64(total)) / 100)) + if roundUp { + value = int(math.Ceil(float64(value) * (float64(total)) / 100)) + } else { + value = int(math.Floor(float64(value) * (float64(total)) / 100)) + } } return value, nil } diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr_test.go deleted file mode 100644 index fb36f9d66..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr_test.go +++ /dev/null @@ -1,160 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package intstr - -import ( - "encoding/json" - "reflect" - "testing" - - "github.com/ghodss/yaml" -) - -func TestFromInt(t *testing.T) { - i := FromInt(93) - if i.Type != Int || i.IntVal != 93 { - t.Errorf("Expected IntVal=93, got %+v", i) - } -} - -func TestFromString(t *testing.T) { - i := FromString("76") - if i.Type != String || i.StrVal != "76" { - t.Errorf("Expected StrVal=\"76\", got %+v", i) - } -} - -type IntOrStringHolder struct { - IOrS IntOrString `json:"val"` -} - -func TestIntOrStringUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result IntOrString - }{ - {"{\"val\": 123}", FromInt(123)}, - {"{\"val\": \"123\"}", FromString("123")}, - } - - for _, c := range cases { - var result IntOrStringHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.IOrS != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestIntOrStringMarshalJSON(t *testing.T) { - cases := []struct { - input IntOrString - result string - }{ - {FromInt(123), "{\"val\":123}"}, - {FromString("123"), "{\"val\":\"123\"}"}, - } - - for _, c := range cases { - input := IntOrStringHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input '%v': expected: %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestIntOrStringMarshalJSONUnmarshalYAML(t *testing.T) { - cases := []struct { - input IntOrString - }{ - {FromInt(123)}, - {FromString("123")}, - } - - for _, c := range cases { - input := IntOrStringHolder{c.input} - jsonMarshalled, err := json.Marshal(&input) - if err != nil { - t.Errorf("1: Failed to marshal input: '%v': %v", input, err) - } - - var result IntOrStringHolder - err = yaml.Unmarshal(jsonMarshalled, &result) - if err != nil { - t.Errorf("2: Failed to unmarshal '%+v': %v", string(jsonMarshalled), err) - } - - if !reflect.DeepEqual(input, result) { - t.Errorf("3: Failed to marshal input '%+v': got %+v", input, result) - } - } -} - -func TestGetValueFromIntOrPercent(t *testing.T) { - tests := []struct { - input IntOrString - total int - expectErr bool - expectVal int - }{ - { - input: FromInt(123), - expectErr: false, - expectVal: 123, - }, - { - input: FromString("90%"), - total: 100, - expectErr: false, - expectVal: 90, - }, - { - input: FromString("%"), - expectErr: true, - }, - { - input: FromString("90#"), - expectErr: true, - }, - { - input: FromString("#%"), - expectErr: true, - }, - } - - for i, test := range tests { - t.Logf("test case %d", i) - value, err := GetValueFromIntOrPercent(&test.input, test.total) - if test.expectErr && err == nil { - t.Errorf("expected error, but got none") - continue - } - if !test.expectErr && err != nil { - t.Errorf("unexpected err: %v", err) - continue - } - if test.expectVal != value { - t.Errorf("expected %v, but got %v", test.expectErr, value) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/io.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/io.go deleted file mode 100644 index d600c08c1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/io.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package io - -import ( - "fmt" - "io/ioutil" - "os" - - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/runtime" -) - -// LoadPodFromFile will read, decode, and return a Pod from a file. -func LoadPodFromFile(filePath string) (*api.Pod, error) { - if filePath == "" { - return nil, fmt.Errorf("file path not specified") - } - podDef, err := ioutil.ReadFile(filePath) - if err != nil { - return nil, fmt.Errorf("failed to read file path %s: %+v", filePath, err) - } - if len(podDef) == 0 { - return nil, fmt.Errorf("file was empty: %s", filePath) - } - pod := &api.Pod{} - - codec := api.Codecs.LegacyCodec(registered.GroupOrDie(api.GroupName).GroupVersion) - if err := runtime.DecodeInto(codec, podDef, pod); err != nil { - return nil, fmt.Errorf("failed decoding file: %v", err) - } - return pod, nil -} - -// SavePodToFile will encode and save a pod to a given path & permissions -func SavePodToFile(pod *api.Pod, filePath string, perm os.FileMode) error { - if filePath == "" { - return fmt.Errorf("file path not specified") - } - codec := api.Codecs.LegacyCodec(registered.GroupOrDie(api.GroupName).GroupVersion) - data, err := runtime.Encode(codec, pod) - if err != nil { - return fmt.Errorf("failed encoding pod: %v", err) - } - return ioutil.WriteFile(filePath, data, perm) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/io_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/io_test.go deleted file mode 100644 index 1b9d4c67a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/io_test.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package io_test - -import ( - "fmt" - "os" - "testing" - - "github.com/pborman/uuid" - "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/apimachinery/registered" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/io" - utiltesting "k8s.io/kubernetes/pkg/util/testing" - "k8s.io/kubernetes/pkg/volume" -) - -func TestSavePodToFile(t *testing.T) { - pod := volume.NewPersistentVolumeRecyclerPodTemplate() - - // sets all default values on a pod for equality comparison after decoding from file - codec := api.Codecs.LegacyCodec(registered.GroupOrDie(api.GroupName).GroupVersion) - encoded, err := runtime.Encode(codec, pod) - runtime.DecodeInto(codec, encoded, pod) - - tmpDir := utiltesting.MkTmpdirOrDie("kube-io-test") - defer os.RemoveAll(tmpDir) - path := fmt.Sprintf("/%s/kube-io-test-%s", tmpDir, uuid.New()) - - if err := io.SavePodToFile(pod, path, 777); err != nil { - t.Fatalf("failed to save pod to file: %v", err) - } - - podFromFile, err := io.LoadPodFromFile(path) - if err != nil { - t.Fatalf("failed to load pod from file: %v", err) - } - if !api.Semantic.DeepEqual(pod, podFromFile) { - t.Errorf("\nexpected %#v\ngot %#v\n", pod, podFromFile) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/writer.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/writer.go deleted file mode 100644 index 3046c4d9b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/io/writer.go +++ /dev/null @@ -1,80 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package io - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "os/exec" - - "github.com/golang/glog" -) - -// Writer is an interface which allows to write data to a file. -type Writer interface { - WriteFile(filename string, data []byte, perm os.FileMode) error -} - -// StdWriter implements Writer interface and uses standard libraries -// for writing data to files. -type StdWriter struct { -} - -func (writer *StdWriter) WriteFile(filename string, data []byte, perm os.FileMode) error { - return ioutil.WriteFile(filename, data, perm) -} - -// Alternative implementation of Writer interface that allows writing data to file -// using nsenter command. -// If a program (e.g. kubelet) runs in a container it may want to write data to -// a mounted device. Since in Docker, mount propagation mode is set to private, -// it will not see the mounted device in its own namespace. To work around this -// limitaion one has to first enter hosts namespace (by using 'nsenter') and only -// then write data. -type NsenterWriter struct { -} - -// TODO: should take a writer, not []byte -func (writer *NsenterWriter) WriteFile(filename string, data []byte, perm os.FileMode) error { - cmd := "nsenter" - base_args := []string{ - "--mount=/rootfs/proc/1/ns/mnt", - "--", - } - - echo_args := append(base_args, "sh", "-c", fmt.Sprintf("cat > %s", filename)) - glog.V(5).Infof("Command to write data to file: %v %v", cmd, echo_args) - command := exec.Command(cmd, echo_args...) - command.Stdin = bytes.NewBuffer(data) - outputBytes, err := command.CombinedOutput() - if err != nil { - glog.Errorf("Output from writing to %q: %v", filename, string(outputBytes)) - return err - } - - chmod_args := append(base_args, "chmod", fmt.Sprintf("%o", perm), filename) - glog.V(5).Infof("Command to change permissions to file: %v %v", cmd, chmod_args) - outputBytes, err = exec.Command(cmd, chmod_args...).CombinedOutput() - if err != nil { - glog.Errorf("Output from chmod command: %v", string(outputBytes)) - return err - } - - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/doc.go deleted file mode 100644 index 5824f3b4e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package iptables provides an interface and implementations for running iptables commands. -package iptables diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/iptables.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/iptables.go deleted file mode 100644 index 801cc8bf7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/iptables.go +++ /dev/null @@ -1,595 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package iptables - -import ( - "fmt" - "io/ioutil" - "os" - "regexp" - "strings" - "sync" - - "github.com/coreos/go-semver/semver" - godbus "github.com/godbus/dbus" - "github.com/golang/glog" - utildbus "k8s.io/kubernetes/pkg/util/dbus" - utilexec "k8s.io/kubernetes/pkg/util/exec" - "k8s.io/kubernetes/pkg/util/sets" -) - -type RulePosition string - -const ( - Prepend RulePosition = "-I" - Append RulePosition = "-A" -) - -// An injectable interface for running iptables commands. Implementations must be goroutine-safe. -type Interface interface { - // GetVersion returns the "X.Y.Z" semver string for iptables. - GetVersion() (string, error) - // EnsureChain checks if the specified chain exists and, if not, creates it. If the chain existed, return true. - EnsureChain(table Table, chain Chain) (bool, error) - // FlushChain clears the specified chain. If the chain did not exist, return error. - FlushChain(table Table, chain Chain) error - // DeleteChain deletes the specified chain. If the chain did not exist, return error. - DeleteChain(table Table, chain Chain) error - // EnsureRule checks if the specified rule is present and, if not, creates it. If the rule existed, return true. - EnsureRule(position RulePosition, table Table, chain Chain, args ...string) (bool, error) - // DeleteRule checks if the specified rule is present and, if so, deletes it. - DeleteRule(table Table, chain Chain, args ...string) error - // IsIpv6 returns true if this is managing ipv6 tables - IsIpv6() bool - // TODO: (BenTheElder) Unit-Test Save/SaveAll, Restore/RestoreAll - // Save calls `iptables-save` for table. - Save(table Table) ([]byte, error) - // SaveAll calls `iptables-save`. - SaveAll() ([]byte, error) - // Restore runs `iptables-restore` passing data through a temporary file. - // table is the Table to restore - // data should be formatted like the output of Save() - // flush sets the presence of the "--noflush" flag. see: FlushFlag - // counters sets the "--counters" flag. see: RestoreCountersFlag - Restore(table Table, data []byte, flush FlushFlag, counters RestoreCountersFlag) error - // RestoreAll is the same as Restore except that no table is specified. - RestoreAll(data []byte, flush FlushFlag, counters RestoreCountersFlag) error - // AddReloadFunc adds a function to call on iptables reload - AddReloadFunc(reloadFunc func()) - // Destroy cleans up resources used by the Interface - Destroy() -} - -type Protocol byte - -const ( - ProtocolIpv4 Protocol = iota + 1 - ProtocolIpv6 -) - -type Table string - -const ( - TableNAT Table = "nat" - TableFilter Table = "filter" -) - -type Chain string - -const ( - ChainPostrouting Chain = "POSTROUTING" - ChainPrerouting Chain = "PREROUTING" - ChainOutput Chain = "OUTPUT" - ChainInput Chain = "INPUT" -) - -const ( - cmdIptablesSave string = "iptables-save" - cmdIptablesRestore string = "iptables-restore" - cmdIptables string = "iptables" - cmdIp6tables string = "ip6tables" -) - -// Option flag for Restore -type RestoreCountersFlag bool - -const RestoreCounters RestoreCountersFlag = true -const NoRestoreCounters RestoreCountersFlag = false - -// Option flag for Flush -type FlushFlag bool - -const FlushTables FlushFlag = true -const NoFlushTables FlushFlag = false - -// Versions of iptables less than this do not support the -C / --check flag -// (test whether a rule exists). -const MinCheckVersion = "1.4.11" - -// Minimum iptables versions supporting the -w and -w2 flags -const MinWaitVersion = "1.4.20" -const MinWait2Version = "1.4.22" - -// runner implements Interface in terms of exec("iptables"). -type runner struct { - mu sync.Mutex - exec utilexec.Interface - dbus utildbus.Interface - protocol Protocol - hasCheck bool - waitFlag []string - - reloadFuncs []func() - signal chan *godbus.Signal -} - -// New returns a new Interface which will exec iptables. -func New(exec utilexec.Interface, dbus utildbus.Interface, protocol Protocol) Interface { - vstring, err := getIptablesVersionString(exec) - if err != nil { - glog.Warningf("Error checking iptables version, assuming version at least %s: %v", MinCheckVersion, err) - vstring = MinCheckVersion - } - runner := &runner{ - exec: exec, - dbus: dbus, - protocol: protocol, - hasCheck: getIptablesHasCheckCommand(vstring), - waitFlag: getIptablesWaitFlag(vstring), - } - runner.connectToFirewallD() - return runner -} - -// Destroy is part of Interface. -func (runner *runner) Destroy() { - if runner.signal != nil { - runner.signal <- nil - } -} - -const ( - firewalldName = "org.fedoraproject.FirewallD1" - firewalldPath = "/org/fedoraproject/FirewallD1" - firewalldInterface = "org.fedoraproject.FirewallD1" -) - -// Connects to D-Bus and listens for FirewallD start/restart. (On non-FirewallD-using -// systems, this is effectively a no-op; we listen for the signals, but they will never be -// emitted, so reload() will never be called.) -func (runner *runner) connectToFirewallD() { - bus, err := runner.dbus.SystemBus() - if err != nil { - glog.V(1).Infof("Could not connect to D-Bus system bus: %s", err) - return - } - - rule := fmt.Sprintf("type='signal',sender='%s',path='%s',interface='%s',member='Reloaded'", firewalldName, firewalldPath, firewalldInterface) - bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) - - rule = fmt.Sprintf("type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus',arg0='%s'", firewalldName) - bus.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule) - - runner.signal = make(chan *godbus.Signal, 10) - bus.Signal(runner.signal) - - go runner.dbusSignalHandler(bus) -} - -// GetVersion returns the version string. -func (runner *runner) GetVersion() (string, error) { - return getIptablesVersionString(runner.exec) -} - -// EnsureChain is part of Interface. -func (runner *runner) EnsureChain(table Table, chain Chain) (bool, error) { - fullArgs := makeFullArgs(table, chain) - - runner.mu.Lock() - defer runner.mu.Unlock() - - out, err := runner.run(opCreateChain, fullArgs) - if err != nil { - if ee, ok := err.(utilexec.ExitError); ok { - if ee.Exited() && ee.ExitStatus() == 1 { - return true, nil - } - } - return false, fmt.Errorf("error creating chain %q: %v: %s", chain, err, out) - } - return false, nil -} - -// FlushChain is part of Interface. -func (runner *runner) FlushChain(table Table, chain Chain) error { - fullArgs := makeFullArgs(table, chain) - - runner.mu.Lock() - defer runner.mu.Unlock() - - out, err := runner.run(opFlushChain, fullArgs) - if err != nil { - return fmt.Errorf("error flushing chain %q: %v: %s", chain, err, out) - } - return nil -} - -// DeleteChain is part of Interface. -func (runner *runner) DeleteChain(table Table, chain Chain) error { - fullArgs := makeFullArgs(table, chain) - - runner.mu.Lock() - defer runner.mu.Unlock() - - // TODO: we could call iptables -S first, ignore the output and check for non-zero return (more like DeleteRule) - out, err := runner.run(opDeleteChain, fullArgs) - if err != nil { - return fmt.Errorf("error deleting chain %q: %v: %s", chain, err, out) - } - return nil -} - -// EnsureRule is part of Interface. -func (runner *runner) EnsureRule(position RulePosition, table Table, chain Chain, args ...string) (bool, error) { - fullArgs := makeFullArgs(table, chain, args...) - - runner.mu.Lock() - defer runner.mu.Unlock() - - exists, err := runner.checkRule(table, chain, args...) - if err != nil { - return false, err - } - if exists { - return true, nil - } - out, err := runner.run(operation(position), fullArgs) - if err != nil { - return false, fmt.Errorf("error appending rule: %v: %s", err, out) - } - return false, nil -} - -// DeleteRule is part of Interface. -func (runner *runner) DeleteRule(table Table, chain Chain, args ...string) error { - fullArgs := makeFullArgs(table, chain, args...) - - runner.mu.Lock() - defer runner.mu.Unlock() - - exists, err := runner.checkRule(table, chain, args...) - if err != nil { - return err - } - if !exists { - return nil - } - out, err := runner.run(opDeleteRule, fullArgs) - if err != nil { - return fmt.Errorf("error deleting rule: %v: %s", err, out) - } - return nil -} - -func (runner *runner) IsIpv6() bool { - return runner.protocol == ProtocolIpv6 -} - -// Save is part of Interface. -func (runner *runner) Save(table Table) ([]byte, error) { - runner.mu.Lock() - defer runner.mu.Unlock() - - // run and return - args := []string{"-t", string(table)} - glog.V(4).Infof("running iptables-save %v", args) - return runner.exec.Command(cmdIptablesSave, args...).CombinedOutput() -} - -// SaveAll is part of Interface. -func (runner *runner) SaveAll() ([]byte, error) { - runner.mu.Lock() - defer runner.mu.Unlock() - - // run and return - glog.V(4).Infof("running iptables-save") - return runner.exec.Command(cmdIptablesSave, []string{}...).CombinedOutput() -} - -// Restore is part of Interface. -func (runner *runner) Restore(table Table, data []byte, flush FlushFlag, counters RestoreCountersFlag) error { - // setup args - args := []string{"-T", string(table)} - return runner.restoreInternal(args, data, flush, counters) -} - -// RestoreAll is part of Interface. -func (runner *runner) RestoreAll(data []byte, flush FlushFlag, counters RestoreCountersFlag) error { - // setup args - args := make([]string, 0) - return runner.restoreInternal(args, data, flush, counters) -} - -// restoreInternal is the shared part of Restore/RestoreAll -func (runner *runner) restoreInternal(args []string, data []byte, flush FlushFlag, counters RestoreCountersFlag) error { - runner.mu.Lock() - defer runner.mu.Unlock() - - if !flush { - args = append(args, "--noflush") - } - if counters { - args = append(args, "--counters") - } - // create temp file through which to pass data - temp, err := ioutil.TempFile("", "kube-temp-iptables-restore-") - if err != nil { - return err - } - // make sure we delete the temp file - defer os.Remove(temp.Name()) - // Put the filename at the end of args. - // NOTE: the filename must be at the end. - // See: https://git.netfilter.org/iptables/commit/iptables-restore.c?id=e6869a8f59d779ff4d5a0984c86d80db70784962 - args = append(args, temp.Name()) - if err != nil { - return err - } - // write data to the file - _, err = temp.Write(data) - temp.Close() - if err != nil { - return err - } - // run the command and return the output or an error including the output and error - glog.V(4).Infof("running iptables-restore %v", args) - b, err := runner.exec.Command(cmdIptablesRestore, args...).CombinedOutput() - if err != nil { - return fmt.Errorf("%v (%s)", err, b) - } - return nil -} - -func (runner *runner) iptablesCommand() string { - if runner.IsIpv6() { - return cmdIp6tables - } else { - return cmdIptables - } -} - -func (runner *runner) run(op operation, args []string) ([]byte, error) { - iptablesCmd := runner.iptablesCommand() - - fullArgs := append(runner.waitFlag, string(op)) - fullArgs = append(fullArgs, args...) - glog.V(4).Infof("running iptables %s %v", string(op), args) - return runner.exec.Command(iptablesCmd, fullArgs...).CombinedOutput() - // Don't log err here - callers might not think it is an error. -} - -// Returns (bool, nil) if it was able to check the existence of the rule, or -// (, error) if the process of checking failed. -func (runner *runner) checkRule(table Table, chain Chain, args ...string) (bool, error) { - if runner.hasCheck { - return runner.checkRuleUsingCheck(makeFullArgs(table, chain, args...)) - } else { - return runner.checkRuleWithoutCheck(table, chain, args...) - } -} - -// Executes the rule check without using the "-C" flag, instead parsing iptables-save. -// Present for compatibility with <1.4.11 versions of iptables. This is full -// of hack and half-measures. We should nix this ASAP. -func (runner *runner) checkRuleWithoutCheck(table Table, chain Chain, args ...string) (bool, error) { - glog.V(1).Infof("running iptables-save -t %s", string(table)) - out, err := runner.exec.Command(cmdIptablesSave, "-t", string(table)).CombinedOutput() - if err != nil { - return false, fmt.Errorf("error checking rule: %v", err) - } - - // Sadly, iptables has inconsistent quoting rules for comments. Just remove all quotes. - // Also, quoted multi-word comments (which are counted as a single arg) - // will be unpacked into multiple args, - // in order to compare against iptables-save output (which will be split at whitespace boundary) - // e.g. a single arg('"this must be before the NodePort rules"') will be unquoted and unpacked into 7 args. - var argsCopy []string - for i := range args { - tmpField := strings.Trim(args[i], "\"") - argsCopy = append(argsCopy, strings.Fields(tmpField)...) - } - argset := sets.NewString(argsCopy...) - - for _, line := range strings.Split(string(out), "\n") { - var fields = strings.Fields(line) - - // Check that this is a rule for the correct chain, and that it has - // the correct number of argument (+2 for "-A ") - if !strings.HasPrefix(line, fmt.Sprintf("-A %s", string(chain))) || len(fields) != len(argsCopy)+2 { - continue - } - - // Sadly, iptables has inconsistent quoting rules for comments. - // Just remove all quotes. - for i := range fields { - fields[i] = strings.Trim(fields[i], "\"") - } - - // TODO: This misses reorderings e.g. "-x foo ! -y bar" will match "! -x foo -y bar" - if sets.NewString(fields...).IsSuperset(argset) { - return true, nil - } - glog.V(5).Infof("DBG: fields is not a superset of args: fields=%v args=%v", fields, args) - } - - return false, nil -} - -// Executes the rule check using the "-C" flag -func (runner *runner) checkRuleUsingCheck(args []string) (bool, error) { - out, err := runner.run(opCheckRule, args) - if err == nil { - return true, nil - } - if ee, ok := err.(utilexec.ExitError); ok { - // iptables uses exit(1) to indicate a failure of the operation, - // as compared to a malformed commandline, for example. - if ee.Exited() && ee.ExitStatus() == 1 { - return false, nil - } - } - return false, fmt.Errorf("error checking rule: %v: %s", err, out) -} - -type operation string - -const ( - opCreateChain operation = "-N" - opFlushChain operation = "-F" - opDeleteChain operation = "-X" - opAppendRule operation = "-A" - opCheckRule operation = "-C" - opDeleteRule operation = "-D" -) - -func makeFullArgs(table Table, chain Chain, args ...string) []string { - return append([]string{string(chain), "-t", string(table)}, args...) -} - -// Checks if iptables has the "-C" flag -func getIptablesHasCheckCommand(vstring string) bool { - minVersion, err := semver.NewVersion(MinCheckVersion) - if err != nil { - glog.Errorf("MinCheckVersion (%s) is not a valid version string: %v", MinCheckVersion, err) - return true - } - version, err := semver.NewVersion(vstring) - if err != nil { - glog.Errorf("vstring (%s) is not a valid version string: %v", vstring, err) - return true - } - if version.LessThan(*minVersion) { - return false - } - return true -} - -// Checks if iptables version has a "wait" flag -func getIptablesWaitFlag(vstring string) []string { - version, err := semver.NewVersion(vstring) - if err != nil { - glog.Errorf("vstring (%s) is not a valid version string: %v", vstring, err) - return nil - } - - minVersion, err := semver.NewVersion(MinWaitVersion) - if err != nil { - glog.Errorf("MinWaitVersion (%s) is not a valid version string: %v", MinWaitVersion, err) - return nil - } - if version.LessThan(*minVersion) { - return nil - } - - minVersion, err = semver.NewVersion(MinWait2Version) - if err != nil { - glog.Errorf("MinWait2Version (%s) is not a valid version string: %v", MinWait2Version, err) - return nil - } - if version.LessThan(*minVersion) { - return []string{"-w"} - } else { - return []string{"-w2"} - } -} - -// getIptablesVersionString runs "iptables --version" to get the version string -// in the form "X.X.X" -func getIptablesVersionString(exec utilexec.Interface) (string, error) { - // this doesn't access mutable state so we don't need to use the interface / runner - bytes, err := exec.Command(cmdIptables, "--version").CombinedOutput() - if err != nil { - return "", err - } - versionMatcher := regexp.MustCompile("v([0-9]+\\.[0-9]+\\.[0-9]+)") - match := versionMatcher.FindStringSubmatch(string(bytes)) - if match == nil { - return "", fmt.Errorf("no iptables version found in string: %s", bytes) - } - return match[1], nil -} - -// goroutine to listen for D-Bus signals -func (runner *runner) dbusSignalHandler(bus utildbus.Connection) { - firewalld := bus.Object(firewalldName, firewalldPath) - - for s := range runner.signal { - if s == nil { - // Unregister - bus.Signal(runner.signal) - return - } - - switch s.Name { - case "org.freedesktop.DBus.NameOwnerChanged": - name := s.Body[0].(string) - new_owner := s.Body[2].(string) - - if name != firewalldName || len(new_owner) == 0 { - continue - } - - // FirewallD startup (specifically the part where it deletes - // all existing iptables rules) may not yet be complete when - // we get this signal, so make a dummy request to it to - // synchronize. - firewalld.Call(firewalldInterface+".getDefaultZone", 0) - - runner.reload() - case firewalldInterface + ".Reloaded": - runner.reload() - } - } -} - -// AddReloadFunc is part of Interface -func (runner *runner) AddReloadFunc(reloadFunc func()) { - runner.reloadFuncs = append(runner.reloadFuncs, reloadFunc) -} - -// runs all reload funcs to re-sync iptables rules -func (runner *runner) reload() { - glog.V(1).Infof("reloading iptables rules") - - for _, f := range runner.reloadFuncs { - f() - } -} - -// IsNotFoundError returns true if the error indicates "not found". It parses -// the error string looking for known values, which is imperfect but works in -// practice. -func IsNotFoundError(err error) bool { - es := err.Error() - if strings.Contains(es, "No such file or directory") { - return true - } - if strings.Contains(es, "No chain/target/match by that name") { - return true - } - return false -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/iptables_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/iptables_test.go deleted file mode 100644 index d5bb34691..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/iptables_test.go +++ /dev/null @@ -1,768 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package iptables - -import ( - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/util/dbus" - "k8s.io/kubernetes/pkg/util/exec" - "k8s.io/kubernetes/pkg/util/sets" -) - -func getIptablesCommand(protocol Protocol) string { - if protocol == ProtocolIpv4 { - return cmdIptables - } - if protocol == ProtocolIpv6 { - return cmdIp6tables - } - panic("Unknown protocol") -} - -func testEnsureChain(t *testing.T, protocol Protocol) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Success. - func() ([]byte, error) { return []byte{}, nil }, - // Exists. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - // Failure. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 2} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), protocol) - defer runner.Destroy() - // Success. - exists, err := runner.EnsureChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if exists { - t.Errorf("expected exists = false") - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - cmd := getIptablesCommand(protocol) - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll(cmd, "-t", "nat", "-N", "FOOBAR") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } - // Exists. - exists, err = runner.EnsureChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if !exists { - t.Errorf("expected exists = true") - } - // Failure. - _, err = runner.EnsureChain(TableNAT, Chain("FOOBAR")) - if err == nil { - t.Errorf("expected failure") - } -} - -func TestEnsureChainIpv4(t *testing.T) { - testEnsureChain(t, ProtocolIpv4) -} - -func TestEnsureChainIpv6(t *testing.T) { - testEnsureChain(t, ProtocolIpv6) -} - -func TestFlushChain(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Success. - func() ([]byte, error) { return []byte{}, nil }, - // Failure. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - // Success. - err := runner.FlushChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-t", "nat", "-F", "FOOBAR") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } - // Failure. - err = runner.FlushChain(TableNAT, Chain("FOOBAR")) - if err == nil { - t.Errorf("expected failure") - } -} - -func TestDeleteChain(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Success. - func() ([]byte, error) { return []byte{}, nil }, - // Failure. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - // Success. - err := runner.DeleteChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-t", "nat", "-X", "FOOBAR") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } - // Failure. - err = runner.DeleteChain(TableNAT, Chain("FOOBAR")) - if err == nil { - t.Errorf("expected failure") - } -} - -func TestEnsureRuleAlreadyExists(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Success. - func() ([]byte, error) { return []byte{}, nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Success of that exec means "done". - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - exists, err := runner.EnsureRule(Append, TableNAT, ChainOutput, "abc", "123") - if err != nil { - t.Errorf("expected success, got %v", err) - } - if !exists { - t.Errorf("expected exists = true") - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-t", "nat", "-C", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } -} - -func TestEnsureRuleNew(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Status 1 on the first call. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - // Success on the second call. - func() ([]byte, error) { return []byte{}, nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Failure of that means create it. - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - exists, err := runner.EnsureRule(Append, TableNAT, ChainOutput, "abc", "123") - if err != nil { - t.Errorf("expected success, got %v", err) - } - if exists { - t.Errorf("expected exists = false") - } - if fcmd.CombinedOutputCalls != 3 { - t.Errorf("expected 3 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[2]...).HasAll("iptables", "-t", "nat", "-A", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[2]) - } -} - -func TestEnsureRuleErrorChecking(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Status 2 on the first call. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 2} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Failure of that means create it. - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - _, err := runner.EnsureRule(Append, TableNAT, ChainOutput, "abc", "123") - if err == nil { - t.Errorf("expected failure") - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } -} - -func TestEnsureRuleErrorCreating(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Status 1 on the first call. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - // Status 1 on the second call. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Failure of that means create it. - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - _, err := runner.EnsureRule(Append, TableNAT, ChainOutput, "abc", "123") - if err == nil { - t.Errorf("expected failure") - } - if fcmd.CombinedOutputCalls != 3 { - t.Errorf("expected 3 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } -} - -func TestDeleteRuleAlreadyExists(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Status 1 on the first call. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Failure of that exec means "does not exist". - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - err := runner.DeleteRule(TableNAT, ChainOutput, "abc", "123") - if err != nil { - t.Errorf("expected success, got %v", err) - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-t", "nat", "-C", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } -} - -func TestDeleteRuleNew(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Success on the first call. - func() ([]byte, error) { return []byte{}, nil }, - // Success on the second call. - func() ([]byte, error) { return []byte{}, nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Success of that means delete it. - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - err := runner.DeleteRule(TableNAT, ChainOutput, "abc", "123") - if err != nil { - t.Errorf("expected success, got %v", err) - } - if fcmd.CombinedOutputCalls != 3 { - t.Errorf("expected 3 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[2]...).HasAll("iptables", "-t", "nat", "-D", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[2]) - } -} - -func TestDeleteRuleErrorChecking(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Status 2 on the first call. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 2} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Failure of that means create it. - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - err := runner.DeleteRule(TableNAT, ChainOutput, "abc", "123") - if err == nil { - t.Errorf("expected failure") - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } -} - -func TestDeleteRuleErrorCreating(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.9.22"), nil }, - // Success on the first call. - func() ([]byte, error) { return []byte{}, nil }, - // Status 1 on the second call. - func() ([]byte, error) { return nil, &exec.FakeExitError{Status: 1} }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // iptables version check - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - // The second Command() call is checking the rule. Success of that means delete it. - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - err := runner.DeleteRule(TableNAT, ChainOutput, "abc", "123") - if err == nil { - t.Errorf("expected failure") - } - if fcmd.CombinedOutputCalls != 3 { - t.Errorf("expected 3 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } -} - -func TestGetIptablesHasCheckCommand(t *testing.T) { - testCases := []struct { - Version string - Err bool - Expected bool - }{ - {"iptables v1.4.7", false, false}, - {"iptables v1.4.11", false, true}, - {"iptables v1.4.19.1", false, true}, - {"iptables v2.0.0", false, true}, - {"total junk", true, false}, - } - - for _, testCase := range testCases { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(testCase.Version), nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - version, err := getIptablesVersionString(&fexec) - if (err != nil) != testCase.Err { - t.Errorf("Expected error: %v, Got error: %v", testCase.Err, err) - } - if err == nil { - check := getIptablesHasCheckCommand(version) - if testCase.Expected != check { - t.Errorf("Expected result: %v, Got result: %v", testCase.Expected, check) - } - } - } -} - -func TestCheckRuleWithoutCheckPresent(t *testing.T) { - iptables_save_output := `# Generated by iptables-save v1.4.7 on Wed Oct 29 14:56:01 2014 -*nat -:PREROUTING ACCEPT [2136997:197881818] -:POSTROUTING ACCEPT [4284525:258542680] -:OUTPUT ACCEPT [5901660:357267963] --A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER -COMMIT -# Completed on Wed Oct 29 14:56:01 2014` - - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // Success. - func() ([]byte, error) { return []byte(iptables_save_output), nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // The first Command() call is checking the rule. Success of that exec means "done". - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := &runner{exec: &fexec} - exists, err := runner.checkRuleWithoutCheck(TableNAT, ChainPrerouting, "-m", "addrtype", "-j", "DOCKER", "--dst-type", "LOCAL") - if err != nil { - t.Errorf("expected success, got %v", err) - } - if !exists { - t.Errorf("expected exists = true") - } - if fcmd.CombinedOutputCalls != 1 { - t.Errorf("expected 1 CombinedOutput() call, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[0]...).HasAll("iptables-save", "-t", "nat") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[0]) - } -} - -func TestCheckRuleWithoutCheckAbsent(t *testing.T) { - iptables_save_output := `# Generated by iptables-save v1.4.7 on Wed Oct 29 14:56:01 2014 -*nat -:PREROUTING ACCEPT [2136997:197881818] -:POSTROUTING ACCEPT [4284525:258542680] -:OUTPUT ACCEPT [5901660:357267963] --A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER -COMMIT -# Completed on Wed Oct 29 14:56:01 2014` - - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // Success. - func() ([]byte, error) { return []byte(iptables_save_output), nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - // The first Command() call is checking the rule. Success of that exec means "done". - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := &runner{exec: &fexec} - exists, err := runner.checkRuleWithoutCheck(TableNAT, ChainPrerouting, "-m", "addrtype", "-j", "DOCKER") - if err != nil { - t.Errorf("expected success, got %v", err) - } - if exists { - t.Errorf("expected exists = false") - } - if fcmd.CombinedOutputCalls != 1 { - t.Errorf("expected 1 CombinedOutput() call, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[0]...).HasAll("iptables-save", "-t", "nat") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[0]) - } -} - -func TestIptablesWaitFlag(t *testing.T) { - testCases := []struct { - Version string - Result string - }{ - {"0.55.55", ""}, - {"1.0.55", ""}, - {"1.4.19", ""}, - {"1.4.20", "-w"}, - {"1.4.21", "-w"}, - {"1.4.22", "-w2"}, - {"1.5.0", "-w2"}, - {"2.0.0", "-w2"}, - } - - for _, testCase := range testCases { - result := getIptablesWaitFlag(testCase.Version) - if strings.Join(result, "") != testCase.Result { - t.Errorf("For %s expected %v got %v", testCase.Version, testCase.Result, result) - } - } -} - -func TestWaitFlagUnavailable(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.4.19"), nil }, - // Success. - func() ([]byte, error) { return []byte{}, nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - err := runner.DeleteChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if sets.NewString(fcmd.CombinedOutputLog[1]...).HasAny("-w", "-w2") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } -} - -func TestWaitFlagOld(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.4.20"), nil }, - // Success. - func() ([]byte, error) { return []byte{}, nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - err := runner.DeleteChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-w") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } - if sets.NewString(fcmd.CombinedOutputLog[1]...).HasAny("-w2") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } -} - -func TestWaitFlagNew(t *testing.T) { - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.4.22"), nil }, - // Success. - func() ([]byte, error) { return []byte{}, nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - runner := New(&fexec, dbus.NewFake(nil, nil), ProtocolIpv4) - defer runner.Destroy() - err := runner.DeleteChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if fcmd.CombinedOutputCalls != 2 { - t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-w2") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } - if sets.NewString(fcmd.CombinedOutputLog[1]...).HasAny("-w") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } -} - -func TestReload(t *testing.T) { - dbusConn := dbus.NewFakeConnection() - dbusConn.SetBusObject(func(method string, args ...interface{}) ([]interface{}, error) { return nil, nil }) - dbusConn.AddObject(firewalldName, firewalldPath, func(method string, args ...interface{}) ([]interface{}, error) { return nil, nil }) - fdbus := dbus.NewFake(dbusConn, nil) - - reloaded := make(chan bool, 2) - - fcmd := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - // iptables version check - func() ([]byte, error) { return []byte("iptables v1.4.22"), nil }, - - // first reload - // EnsureChain - func() ([]byte, error) { return []byte{}, nil }, - // EnsureRule abc check - func() ([]byte, error) { return []byte{}, &exec.FakeExitError{Status: 1} }, - // EnsureRule abc - func() ([]byte, error) { return []byte{}, nil }, - - // second reload - // EnsureChain - func() ([]byte, error) { return []byte{}, nil }, - // EnsureRule abc check - func() ([]byte, error) { return []byte{}, &exec.FakeExitError{Status: 1} }, - // EnsureRule abc - func() ([]byte, error) { return []byte{}, nil }, - }, - } - fexec := exec.FakeExec{ - CommandScript: []exec.FakeCommandAction{ - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) }, - }, - } - - runner := New(&fexec, fdbus, ProtocolIpv4) - defer runner.Destroy() - - runner.AddReloadFunc(func() { - exists, err := runner.EnsureChain(TableNAT, Chain("FOOBAR")) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if exists { - t.Errorf("expected exists = false") - } - reloaded <- true - }) - - runner.AddReloadFunc(func() { - exists, err := runner.EnsureRule(Append, TableNAT, ChainOutput, "abc", "123") - if err != nil { - t.Errorf("expected success, got %v", err) - } - if exists { - t.Errorf("expected exists = false") - } - reloaded <- true - }) - - dbusConn.EmitSignal("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged", firewalldName, "", ":1.1") - <-reloaded - <-reloaded - - if fcmd.CombinedOutputCalls != 4 { - t.Errorf("expected 4 CombinedOutput() calls total, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-t", "nat", "-N", "FOOBAR") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1]) - } - if !sets.NewString(fcmd.CombinedOutputLog[2]...).HasAll("iptables", "-t", "nat", "-C", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[2]) - } - if !sets.NewString(fcmd.CombinedOutputLog[3]...).HasAll("iptables", "-t", "nat", "-A", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[3]) - } - - go func() { time.Sleep(time.Second / 100); reloaded <- true }() - dbusConn.EmitSignal(firewalldName, firewalldPath, firewalldInterface, "DefaultZoneChanged", "public") - dbusConn.EmitSignal("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged", "io.k8s.Something", "", ":1.1") - <-reloaded - - if fcmd.CombinedOutputCalls != 4 { - t.Errorf("Incorrect signal caused a reload") - } - - dbusConn.EmitSignal(firewalldName, firewalldPath, firewalldInterface, "Reloaded") - <-reloaded - <-reloaded - - if fcmd.CombinedOutputCalls != 7 { - t.Errorf("expected 7 CombinedOutput() calls total, got %d", fcmd.CombinedOutputCalls) - } - if !sets.NewString(fcmd.CombinedOutputLog[4]...).HasAll("iptables", "-t", "nat", "-N", "FOOBAR") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[4]) - } - if !sets.NewString(fcmd.CombinedOutputLog[5]...).HasAll("iptables", "-t", "nat", "-C", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[5]) - } - if !sets.NewString(fcmd.CombinedOutputLog[6]...).HasAll("iptables", "-t", "nat", "-A", "OUTPUT", "abc", "123") { - t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[6]) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/testing/fake.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/testing/fake.go deleted file mode 100644 index ac9967727..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/iptables/testing/fake.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package testing - -import "k8s.io/kubernetes/pkg/util/iptables" - -// no-op implemenatation of iptables Interface -type fake struct{} - -func NewFake() *fake { - return &fake{} -} - -func (*fake) GetVersion() (string, error) { - return "0.0.0", nil -} - -func (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) { - return true, nil -} - -func (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error { - return nil -} - -func (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error { - return nil -} - -func (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) { - return true, nil -} - -func (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error { - return nil -} - -func (*fake) IsIpv6() bool { - return false -} - -func (*fake) Save(table iptables.Table) ([]byte, error) { - return make([]byte, 0), nil -} - -func (*fake) SaveAll() ([]byte, error) { - return make([]byte, 0), nil -} - -func (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error { - return nil -} - -func (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error { - return nil -} -func (*fake) AddReloadFunc(reloadFunc func()) {} - -func (*fake) Destroy() {} - -var _ = iptables.Interface(&fake{}) diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/jsonpath/jsonpath_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/jsonpath/jsonpath_test.go deleted file mode 100644 index 01f07c908..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/jsonpath/jsonpath_test.go +++ /dev/null @@ -1,255 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package jsonpath - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "sort" - "strings" - "testing" -) - -type jsonpathTest struct { - name string - template string - input interface{} - expect string -} - -func testJSONPath(tests []jsonpathTest, t *testing.T) { - for _, test := range tests { - j := New(test.name) - err := j.Parse(test.template) - if err != nil { - t.Errorf("in %s, parse %s error %v", test.name, test.template, err) - } - buf := new(bytes.Buffer) - err = j.Execute(buf, test.input) - if err != nil { - t.Errorf("in %s, execute error %v", test.name, err) - } - out := buf.String() - if out != test.expect { - t.Errorf(`in %s, expect to get "%s", got "%s"`, test.name, test.expect, out) - } - } -} - -// testJSONPathSortOutput test cases related to map, the results may print in random order -func testJSONPathSortOutput(tests []jsonpathTest, t *testing.T) { - for _, test := range tests { - j := New(test.name) - err := j.Parse(test.template) - if err != nil { - t.Errorf("in %s, parse %s error %v", test.name, test.template, err) - } - buf := new(bytes.Buffer) - err = j.Execute(buf, test.input) - if err != nil { - t.Errorf("in %s, execute error %v", test.name, err) - } - out := buf.String() - //since map is visited in random order, we need to sort the results. - sortedOut := strings.Fields(out) - sort.Strings(sortedOut) - sortedExpect := strings.Fields(test.expect) - sort.Strings(sortedExpect) - if !reflect.DeepEqual(sortedOut, sortedExpect) { - t.Errorf(`in %s, expect to get "%s", got "%s"`, test.name, test.expect, out) - } - } -} - -func testFailJSONPath(tests []jsonpathTest, t *testing.T) { - for _, test := range tests { - j := New(test.name) - err := j.Parse(test.template) - if err != nil { - t.Errorf("in %s, parse %s error %v", test.name, test.template, err) - } - buf := new(bytes.Buffer) - err = j.Execute(buf, test.input) - var out string - if err == nil { - out = "nil" - } else { - out = err.Error() - } - if out != test.expect { - t.Errorf("in %s, expect to get error %q, got %q", test.name, test.expect, out) - } - } -} - -type book struct { - Category string - Author string - Title string - Price float32 -} - -func (b book) String() string { - return fmt.Sprintf("{Category: %s, Author: %s, Title: %s, Price: %v}", b.Category, b.Author, b.Title, b.Price) -} - -type bicycle struct { - Color string - Price float32 -} - -type store struct { - Book []book - Bicycle bicycle - Name string - Labels map[string]int -} - -func TestStructInput(t *testing.T) { - - storeData := store{ - Name: "jsonpath", - Book: []book{ - {"reference", "Nigel Rees", "Sayings of the Centurey", 8.95}, - {"fiction", "Evelyn Waugh", "Sword of Honour", 12.99}, - {"fiction", "Herman Melville", "Moby Dick", 8.99}, - }, - Bicycle: bicycle{"red", 19.95}, - Labels: map[string]int{ - "engieer": 10, - "web/html": 15, - "k8s-app": 20, - }, - } - - storeTests := []jsonpathTest{ - {"plain", "hello jsonpath", nil, "hello jsonpath"}, - {"recursive", "{..}", []int{1, 2, 3}, "[1 2 3]"}, - {"filter", "{[?(@<5)]}", []int{2, 6, 3, 7}, "2 3"}, - {"quote", `{"{"}`, nil, "{"}, - {"union", "{[1,3,4]}", []int{0, 1, 2, 3, 4}, "1 3 4"}, - {"array", "{[0:2]}", []string{"Monday", "Tudesday"}, "Monday Tudesday"}, - {"variable", "hello {.Name}", storeData, "hello jsonpath"}, - {"dict/", "{$.Labels.web/html}", storeData, "15"}, - {"dict-", "{.Labels.k8s-app}", storeData, "20"}, - {"nest", "{.Bicycle.Color}", storeData, "red"}, - {"allarray", "{.Book[*].Author}", storeData, "Nigel Rees Evelyn Waugh Herman Melville"}, - {"allfileds", "{.Bicycle.*}", storeData, "red 19.95"}, - {"recurfileds", "{..Price}", storeData, "8.95 12.99 8.99 19.95"}, - {"lastarray", "{.Book[-1:]}", storeData, - "{Category: fiction, Author: Herman Melville, Title: Moby Dick, Price: 8.99}"}, - {"recurarray", "{..Book[2]}", storeData, - "{Category: fiction, Author: Herman Melville, Title: Moby Dick, Price: 8.99}"}, - } - testJSONPath(storeTests, t) - - failStoreTests := []jsonpathTest{ - {"invalid identfier", "{hello}", storeData, "unrecognized identifier hello"}, - {"nonexistent field", "{.hello}", storeData, "hello is not found"}, - {"invalid array", "{.Labels[0]}", storeData, "map[string]int is not array or slice"}, - {"invalid filter operator", "{.Book[?(@.Price<>10)]}", storeData, "unrecognized filter operator <>"}, - {"redundent end", "{range .Labels.*}{@}{end}{end}", storeData, "not in range, nothing to end"}, - } - testFailJSONPath(failStoreTests, t) -} - -func TestJSONInput(t *testing.T) { - var pointsJSON = []byte(`[ - {"id": "i1", "x":4, "y":-5}, - {"id": "i2", "x":-2, "y":-5, "z":1}, - {"id": "i3", "x": 8, "y": 3 }, - {"id": "i4", "x": -6, "y": -1 }, - {"id": "i5", "x": 0, "y": 2, "z": 1 }, - {"id": "i6", "x": 1, "y": 4 } - ]`) - var pointsData interface{} - err := json.Unmarshal(pointsJSON, &pointsData) - if err != nil { - t.Error(err) - } - pointsTests := []jsonpathTest{ - {"exists filter", "{[?(@.z)].id}", pointsData, "i2 i5"}, - {"bracket key", "{[0]['id']}", pointsData, "i1"}, - } - testJSONPath(pointsTests, t) -} - -// TestKubernetes tests some use cases from kubernetes -func TestKubernetes(t *testing.T) { - var input = []byte(`{ - "kind": "List", - "items":[ - { - "kind":"None", - "metadata":{"name":"127.0.0.1"}, - "status":{ - "capacity":{"cpu":"4"}, - "addresses":[{"type": "LegacyHostIP", "address":"127.0.0.1"}] - } - }, - { - "kind":"None", - "metadata":{"name":"127.0.0.2"}, - "status":{ - "capacity":{"cpu":"8"}, - "addresses":[ - {"type": "LegacyHostIP", "address":"127.0.0.2"}, - {"type": "another", "address":"127.0.0.3"} - ] - } - } - ], - "users":[ - { - "name": "myself", - "user": {} - }, - { - "name": "e2e", - "user": {"username": "admin", "password": "secret"} - } - ] - }`) - var nodesData interface{} - err := json.Unmarshal(input, &nodesData) - if err != nil { - t.Error(err) - } - - nodesTests := []jsonpathTest{ - {"range item", `{range .items[*]}{.metadata.name}, {end}{.kind}`, nodesData, "127.0.0.1, 127.0.0.2, List"}, - {"range item with quote", `{range .items[*]}{.metadata.name}{"\t"}{end}`, nodesData, "127.0.0.1\t127.0.0.2\t"}, - {"range addresss", `{.items[*].status.addresses[*].address}`, nodesData, - "127.0.0.1 127.0.0.2 127.0.0.3"}, - {"double range", `{range .items[*]}{range .status.addresses[*]}{.address}, {end}{end}`, nodesData, - "127.0.0.1, 127.0.0.2, 127.0.0.3, "}, - {"item name", `{.items[*].metadata.name}`, nodesData, "127.0.0.1 127.0.0.2"}, - {"union nodes capacity", `{.items[*]['metadata.name', 'status.capacity']}`, nodesData, - "127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]"}, - {"range nodes capacity", `{range .items[*]}[{.metadata.name}, {.status.capacity}] {end}`, nodesData, - "[127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]] "}, - {"user password", `{.users[?(@.name=="e2e")].user.password}`, &nodesData, "secret"}, - } - testJSONPath(nodesTests, t) - - randomPrintOrderTests := []jsonpathTest{ - {"recursive name", "{..name}", nodesData, `127.0.0.1 127.0.0.2 myself e2e`}, - } - testJSONPathSortOutput(randomPrintOrderTests, t) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/jsonpath/parser_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/jsonpath/parser_test.go deleted file mode 100644 index a061043b8..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/jsonpath/parser_test.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package jsonpath - -import ( - "testing" -) - -type parserTest struct { - name string - text string - nodes []Node - shouldError bool -} - -var parserTests = []parserTest{ - {"plain", `hello jsonpath`, []Node{newText("hello jsonpath")}, false}, - {"variable", `hello {.jsonpath}`, - []Node{newText("hello "), newList(), newField("jsonpath")}, false}, - {"arrayfiled", `hello {['jsonpath']}`, - []Node{newText("hello "), newList(), newField("jsonpath")}, false}, - {"quote", `{"{"}`, []Node{newList(), newText("{")}, false}, - {"array", `{[1:3]}`, []Node{newList(), - newArray([3]ParamsEntry{{1, true}, {3, true}, {0, false}})}, false}, - {"allarray", `{.book[*].author}`, - []Node{newList(), newField("book"), - newArray([3]ParamsEntry{{0, false}, {0, false}, {0, false}}), newField("author")}, false}, - {"wildcard", `{.bicycle.*}`, - []Node{newList(), newField("bicycle"), newWildcard()}, false}, - {"filter", `{[?(@.price<3)]}`, - []Node{newList(), newFilter(newList(), newList(), "<"), - newList(), newField("price"), newList(), newInt(3)}, false}, - {"recursive", `{..}`, []Node{newList(), newRecursive()}, false}, - {"recurField", `{..price}`, - []Node{newList(), newRecursive(), newField("price")}, false}, - {"arraydict", `{['book.price']}`, []Node{newList(), - newField("book"), newField("price"), - }, false}, - {"union", `{['bicycle.price', 3, 'book.price']}`, []Node{newList(), newUnion([]*ListNode{}), - newList(), newField("bicycle"), newField("price"), - newList(), newArray([3]ParamsEntry{{3, true}, {4, true}, {0, false}}), - newList(), newField("book"), newField("price"), - }, false}, - {"range", `{range .items}{.name},{end}`, []Node{ - newList(), newIdentifier("range"), newField("items"), - newList(), newField("name"), newText(","), - newList(), newIdentifier("end"), - }, false}, - {"malformat input", `{\\\}`, []Node{}, true}, -} - -func collectNode(nodes []Node, cur Node) []Node { - nodes = append(nodes, cur) - switch cur.Type() { - case NodeList: - for _, node := range cur.(*ListNode).Nodes { - nodes = collectNode(nodes, node) - } - case NodeFilter: - nodes = collectNode(nodes, cur.(*FilterNode).Left) - nodes = collectNode(nodes, cur.(*FilterNode).Right) - case NodeUnion: - for _, node := range cur.(*UnionNode).Nodes { - nodes = collectNode(nodes, node) - } - } - return nodes -} - -func TestParser(t *testing.T) { - for _, test := range parserTests { - parser, err := Parse(test.name, test.text) - if test.shouldError { - if err == nil { - t.Errorf("unexpected non-error when parsing %s", test.name) - } - continue - } - if err != nil { - t.Errorf("parse %s error %v", test.name, err) - } - result := collectNode([]Node{}, parser.Root)[1:] - if len(result) != len(test.nodes) { - t.Errorf("in %s, expect to get %d nodes, got %d nodes", test.name, len(test.nodes), len(result)) - t.Error(result) - } - for i, expect := range test.nodes { - if result[i].String() != expect.String() { - t.Errorf("in %s, %dth node, expect %v, got %v", test.name, i, expect, result[i]) - } - } - } -} - -type failParserTest struct { - name string - text string - err string -} - -func TestFailParser(t *testing.T) { - failParserTests := []failParserTest{ - {"unclosed action", "{.hello", "unclosed action"}, - {"unrecognized character", "{*}", "unrecognized character in action: U+002A '*'"}, - {"invalid number", "{+12.3.0}", "cannot parse number +12.3.0"}, - {"unterminated array", "{[1}", "unterminated array"}, - {"invalid index", "{[::-1]}", "invalid array index ::-1"}, - {"unterminated filter", "{[?(.price]}", "unterminated filter"}, - } - for _, test := range failParserTests { - _, err := Parse(test.name, test.text) - var out string - if err == nil { - out = "nil" - } else { - out = err.Error() - } - if out != test.err { - t.Errorf("in %s, expect to get error %v, got %v", test.name, test.err, out) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go deleted file mode 100644 index 2bcc95175..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package keymutex - -import ( - "fmt" - "github.com/golang/glog" - "sync" -) - -// KeyMutex is a thread-safe interface for acquiring locks on arbitrary strings. -type KeyMutex interface { - // Acquires a lock associated with the specified ID, creates the lock if one doesn't already exist. - LockKey(id string) - - // Releases the lock associated with the specified ID. - // Returns an error if the specified ID doesn't exist. - UnlockKey(id string) error -} - -// Returns a new instance of a key mutex. -func NewKeyMutex() KeyMutex { - return &keyMutex{ - mutexMap: make(map[string]*sync.Mutex), - } -} - -type keyMutex struct { - sync.RWMutex - mutexMap map[string]*sync.Mutex -} - -// Acquires a lock associated with the specified ID (creates the lock if one doesn't already exist). -func (km *keyMutex) LockKey(id string) { - glog.V(5).Infof("LockKey(...) called for id %q\r\n", id) - mutex := km.getOrCreateLock(id) - mutex.Lock() - glog.V(5).Infof("LockKey(...) for id %q completed.\r\n", id) -} - -// Releases the lock associated with the specified ID. -// Returns an error if the specified ID doesn't exist. -func (km *keyMutex) UnlockKey(id string) error { - glog.V(5).Infof("UnlockKey(...) called for id %q\r\n", id) - km.RLock() - defer km.RUnlock() - mutex, exists := km.mutexMap[id] - if !exists { - return fmt.Errorf("id %q not found", id) - } - glog.V(5).Infof("UnlockKey(...) for id. Mutex found, trying to unlock it. %q\r\n", id) - - mutex.Unlock() - glog.V(5).Infof("UnlockKey(...) for id %q completed.\r\n", id) - return nil -} - -// Returns lock associated with the specified ID, or creates the lock if one doesn't already exist. -func (km *keyMutex) getOrCreateLock(id string) *sync.Mutex { - km.Lock() - defer km.Unlock() - - if _, exists := km.mutexMap[id]; !exists { - km.mutexMap[id] = &sync.Mutex{} - } - - return km.mutexMap[id] -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/keymutex/keymutex_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/keymutex/keymutex_test.go deleted file mode 100644 index faa3be16a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/keymutex/keymutex_test.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package keymutex - -import ( - "testing" - "time" -) - -const ( - callbackTimeout = 1 * time.Second -) - -func Test_SingleLock_NoUnlock(t *testing.T) { - // Arrange - km := NewKeyMutex() - key := "fakeid" - callbackCh := make(chan interface{}) - - // Act - go lockAndCallback(km, key, callbackCh) - - // Assert - verifyCallbackHappens(t, callbackCh) -} - -func Test_SingleLock_SingleUnlock(t *testing.T) { - // Arrange - km := NewKeyMutex() - key := "fakeid" - callbackCh := make(chan interface{}) - - // Act & Assert - go lockAndCallback(km, key, callbackCh) - verifyCallbackHappens(t, callbackCh) - km.UnlockKey(key) -} - -func Test_DoubleLock_DoubleUnlock(t *testing.T) { - // Arrange - km := NewKeyMutex() - key := "fakeid" - callbackCh1stLock := make(chan interface{}) - callbackCh2ndLock := make(chan interface{}) - - // Act & Assert - go lockAndCallback(km, key, callbackCh1stLock) - verifyCallbackHappens(t, callbackCh1stLock) - go lockAndCallback(km, key, callbackCh2ndLock) - verifyCallbackDoesntHappens(t, callbackCh2ndLock) - km.UnlockKey(key) - verifyCallbackHappens(t, callbackCh2ndLock) - km.UnlockKey(key) -} - -func lockAndCallback(km KeyMutex, id string, callbackCh chan<- interface{}) { - km.LockKey(id) - callbackCh <- true -} - -func verifyCallbackHappens(t *testing.T, callbackCh <-chan interface{}) bool { - select { - case <-callbackCh: - return true - case <-time.After(callbackTimeout): - t.Fatalf("Timed out waiting for callback.") - return false - } -} - -func verifyCallbackDoesntHappens(t *testing.T, callbackCh <-chan interface{}) bool { - select { - case <-callbackCh: - t.Fatalf("Unexpected callback.") - return false - case <-time.After(callbackTimeout): - return true - } -} - -func verifyNoError(t *testing.T, err error, name string) { - if err != nil { - t.Fatalf("Unexpected response on %q. Expected: Actual: <%v>", name, err) - } -} - -func verifyError(t *testing.T, err error, name string) { - if err == nil { - t.Fatalf("Unexpected response on %q. Expected: Actual: ", name) - } -} - -func verifyMsg(t *testing.T, expected, actual string) { - if actual != expected { - t.Fatalf("Unexpected testMsg value. Expected: <%v> Actual: <%v>", expected, actual) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/labels/labels.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/labels/labels.go index c32b862cd..624d5ad68 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/labels/labels.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/labels/labels.go @@ -54,6 +54,19 @@ func CloneAndRemoveLabel(labels map[string]string, labelKey string) map[string]s return newLabels } +// AddLabel returns a map with the given key and value added to the given map. +func AddLabel(labels map[string]string, labelKey string, labelValue string) map[string]string { + if labelKey == "" { + // Don't need to add a label. + return labels + } + if labels == nil { + labels = make(map[string]string) + } + labels[labelKey] = labelValue + return labels +} + // Clones the given selector and returns a new selector with the given key and value added. // Returns the given selector, if labelKey is empty. func CloneSelectorAndAddLabel(selector *unversioned.LabelSelector, labelKey string, labelValue uint32) *unversioned.LabelSelector { @@ -93,3 +106,21 @@ func CloneSelectorAndAddLabel(selector *unversioned.LabelSelector, labelKey stri return newSelector } + +// AddLabelToSelector returns a selector with the given key and value added to the given selector's MatchLabels. +func AddLabelToSelector(selector *unversioned.LabelSelector, labelKey string, labelValue string) *unversioned.LabelSelector { + if labelKey == "" { + // Don't need to add a label. + return selector + } + if selector.MatchLabels == nil { + selector.MatchLabels = make(map[string]string) + } + selector.MatchLabels[labelKey] = labelValue + return selector +} + +// SelectorHasLabel checks if the given selector contains the given label key in its MatchLabels +func SelectorHasLabel(selector *unversioned.LabelSelector, labelKey string) bool { + return len(selector.MatchLabels[labelKey]) > 0 +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/labels/labels_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/labels/labels_test.go deleted file mode 100644 index 9adbd4554..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/labels/labels_test.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -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. -*/ - -package labels - -import ( - "reflect" - "testing" -) - -func TestCloneAndAddLabel(t *testing.T) { - labels := map[string]string{ - "foo1": "bar1", - "foo2": "bar2", - "foo3": "bar3", - } - - cases := []struct { - labels map[string]string - labelKey string - labelValue uint32 - want map[string]string - }{ - { - labels: labels, - want: labels, - }, - { - labels: labels, - labelKey: "foo4", - labelValue: uint32(42), - want: map[string]string{ - "foo1": "bar1", - "foo2": "bar2", - "foo3": "bar3", - "foo4": "42", - }, - }, - } - - for _, tc := range cases { - got := CloneAndAddLabel(tc.labels, tc.labelKey, tc.labelValue) - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("got %v, want %v", got, tc.want) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/limitwriter/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/limitwriter/doc.go deleted file mode 100644 index 7daff9c07..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/limitwriter/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package limitwriter provides a writer that only allows a certain number of bytes to be -// written. -package limitwriter diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go deleted file mode 100644 index 88890a9fa..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package limitwriter - -import ( - "errors" - "io" -) - -// New creates a writer that is limited to writing at most n bytes to w. This writer is not -// thread safe. -func New(w io.Writer, n int64) io.Writer { - return &limitWriter{ - w: w, - n: n, - } -} - -// ErrMaximumWrite is returned when all bytes have been written. -var ErrMaximumWrite = errors.New("maximum write") - -type limitWriter struct { - w io.Writer - n int64 -} - -func (w *limitWriter) Write(p []byte) (n int, err error) { - if int64(len(p)) > w.n { - p = p[:w.n] - } - if len(p) > 0 { - n, err = w.w.Write(p) - w.n -= int64(n) - } - if w.n == 0 { - err = ErrMaximumWrite - } - return -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/line_delimiter_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/line_delimiter_test.go deleted file mode 100644 index 8777bb949..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/line_delimiter_test.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package util - -import ( - "fmt" - "os" -) - -func ExampleTrailingNewline() { - ld := NewLineDelimiter(os.Stdout, "|") - defer ld.Flush() - fmt.Fprint(ld, " Hello \n World \n") - // Output: - // | Hello | - // | World | - // || -} -func ExampleNoTrailingNewline() { - ld := NewLineDelimiter(os.Stdout, "|") - defer ld.Flush() - fmt.Fprint(ld, " Hello \n World ") - // Output: - // | Hello | - // | World | -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/doc.go deleted file mode 100644 index 839c0a69a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package mount defines an interface to mounting filesystems. -package mount diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/fake.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/fake.go deleted file mode 100644 index 115293813..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/fake.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package mount - -import ( - "sync" - - "github.com/golang/glog" -) - -// FakeMounter implements mount.Interface for tests. -type FakeMounter struct { - MountPoints []MountPoint - Log []FakeAction - // Some tests run things in parallel, make sure the mounter does not produce - // any golang's DATA RACE warnings. - mutex sync.Mutex -} - -var _ Interface = &FakeMounter{} - -// Values for FakeAction.Action -const FakeActionMount = "mount" -const FakeActionUnmount = "unmount" - -// FakeAction objects are logged every time a fake mount or unmount is called. -type FakeAction struct { - Action string // "mount" or "unmount" - Target string // applies to both mount and unmount actions - Source string // applies only to "mount" actions - FSType string // applies only to "mount" actions -} - -func (f *FakeMounter) ResetLog() { - f.mutex.Lock() - defer f.mutex.Unlock() - - f.Log = []FakeAction{} -} - -func (f *FakeMounter) Mount(source string, target string, fstype string, options []string) error { - f.mutex.Lock() - defer f.mutex.Unlock() - - // find 'bind' option - for _, option := range options { - if option == "bind" { - // This is a bind-mount. In order to mimic linux behaviour, we must - // use the original device of the bind-mount as the real source. - // E.g. when mounted /dev/sda like this: - // $ mount /dev/sda /mnt/test - // $ mount -o bind /mnt/test /mnt/bound - // then /proc/mount contains: - // /dev/sda /mnt/test - // /dev/sda /mnt/bound - // (and not /mnt/test /mnt/bound) - // I.e. we must use /dev/sda as source instead of /mnt/test in the - // bind mount. - for _, mnt := range f.MountPoints { - if source == mnt.Path { - source = mnt.Device - break - } - } - break - } - } - - f.MountPoints = append(f.MountPoints, MountPoint{Device: source, Path: target, Type: fstype}) - glog.V(5).Infof("Fake mounter: mouted %s to %s", source, target) - f.Log = append(f.Log, FakeAction{Action: FakeActionMount, Target: target, Source: source, FSType: fstype}) - return nil -} - -func (f *FakeMounter) Unmount(target string) error { - f.mutex.Lock() - defer f.mutex.Unlock() - - newMountpoints := []MountPoint{} - for _, mp := range f.MountPoints { - if mp.Path == target { - glog.V(5).Infof("Fake mounter: unmouted %s from %s", mp.Device, target) - // Don't copy it to newMountpoints - continue - } - newMountpoints = append(newMountpoints, MountPoint{Device: mp.Device, Path: mp.Path, Type: mp.Type}) - } - f.MountPoints = newMountpoints - f.Log = append(f.Log, FakeAction{Action: FakeActionUnmount, Target: target}) - return nil -} - -func (f *FakeMounter) List() ([]MountPoint, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - return f.MountPoints, nil -} - -func (f *FakeMounter) IsLikelyNotMountPoint(file string) (bool, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - for _, mp := range f.MountPoints { - if mp.Path == file { - glog.V(5).Infof("isLikelyMountPoint for %s: monted %s, false", file, mp.Path) - return false, nil - } - } - glog.V(5).Infof("isLikelyMountPoint for %s: true", file) - return true, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount.go deleted file mode 100644 index 79f3f6ec2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// TODO(thockin): This whole pkg is pretty linux-centric. As soon as we have -// an alternate platform, we will need to abstract further. -package mount - -import ( - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/util/exec" -) - -type Interface interface { - // Mount mounts source to target as fstype with given options. - Mount(source string, target string, fstype string, options []string) error - // Unmount unmounts given target. - Unmount(target string) error - // List returns a list of all mounted filesystems. This can be large. - // On some platforms, reading mounts is not guaranteed consistent (i.e. - // it could change between chunked reads). This is guaranteed to be - // consistent. - List() ([]MountPoint, error) - // IsLikelyNotMountPoint determines if a directory is a mountpoint. - IsLikelyNotMountPoint(file string) (bool, error) -} - -// This represents a single line in /proc/mounts or /etc/fstab. -type MountPoint struct { - Device string - Path string - Type string - Opts []string - Freq int - Pass int -} - -// SafeFormatAndMount probes a device to see if it is formatted. -// Namely it checks to see if a file system is present. If so it -// mounts it otherwise the device is formatted first then mounted. -type SafeFormatAndMount struct { - Interface - Runner exec.Interface -} - -// FormatAndMount formats the given disk, if needed, and mounts it. -// That is if the disk is not formatted and it is not being mounted as -// read-only it will format it first then mount it. Otherwise, if the -// disk is already formatted or it is being mounted as read-only, it -// will be mounted without formatting. -func (mounter *SafeFormatAndMount) FormatAndMount(source string, target string, fstype string, options []string) error { - // Don't attempt to format if mounting as readonly. Go straight to mounting. - for _, option := range options { - if option == "ro" { - return mounter.Interface.Mount(source, target, fstype, options) - } - } - return mounter.formatAndMount(source, target, fstype, options) -} - -// New returns a mount.Interface for the current system. -func New() Interface { - return &Mounter{} -} - -// GetMountRefs finds all other references to the device referenced -// by mountPath; returns a list of paths. -func GetMountRefs(mounter Interface, mountPath string) ([]string, error) { - mps, err := mounter.List() - if err != nil { - return nil, err - } - - // Find the device name. - deviceName := "" - for i := range mps { - if mps[i].Path == mountPath { - deviceName = mps[i].Device - break - } - } - - // Find all references to the device. - var refs []string - if deviceName == "" { - glog.Warningf("could not determine device for path: %q", mountPath) - } else { - for i := range mps { - if mps[i].Device == deviceName && mps[i].Path != mountPath { - refs = append(refs, mps[i].Path) - } - } - } - return refs, nil -} - -// GetDeviceNameFromMount: given a mnt point, find the device from /proc/mounts -// returns the device name, reference count, and error code -func GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error) { - mps, err := mounter.List() - if err != nil { - return "", 0, err - } - - // Find the device name. - // FIXME if multiple devices mounted on the same mount path, only the first one is returned - device := "" - for i := range mps { - if mps[i].Path == mountPath { - device = mps[i].Device - break - } - } - - // Find all references to the device. - refCount := 0 - for i := range mps { - if mps[i].Device == device { - refCount++ - } - } - return device, refCount, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_linux.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_linux.go deleted file mode 100644 index 66959697c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_linux.go +++ /dev/null @@ -1,311 +0,0 @@ -// +build linux - -/* -Copyright 2014 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. -*/ - -package mount - -import ( - "bufio" - "fmt" - "hash/adler32" - "io" - "os" - "os/exec" - "strconv" - "strings" - "syscall" - - "github.com/golang/glog" - utilExec "k8s.io/kubernetes/pkg/util/exec" -) - -const ( - // How many times to retry for a consistent read of /proc/mounts. - maxListTries = 3 - // Number of fields per line in /proc/mounts as per the fstab man page. - expectedNumFieldsPerLine = 6 - // Location of the mount file to use - procMountsPath = "/proc/mounts" -) - -const ( - // 'fsck' found errors and corrected them - fsckErrorsCorrected = 1 - // 'fsck' found errors but exited without correcting them - fsckErrorsUncorrected = 4 -) - -// Mounter provides the default implementation of mount.Interface -// for the linux platform. This implementation assumes that the -// kubelet is running in the host's root mount namespace. -type Mounter struct{} - -var _ = Interface(&Mounter{}) - -// Mount mounts source to target as fstype with given options. 'source' and 'fstype' must -// be an emtpy string in case it's not required, e.g. for remount, or for auto filesystem -// type, where kernel handles fs type for you. The mount 'options' is a list of options, -// currently come from mount(8), e.g. "ro", "remount", "bind", etc. If no more option is -// required, call Mount with an empty string list or nil. -func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error { - bind, bindRemountOpts := isBind(options) - - if bind { - err := doMount(source, target, fstype, []string{"bind"}) - if err != nil { - return err - } - return doMount(source, target, fstype, bindRemountOpts) - } else { - return doMount(source, target, fstype, options) - } -} - -// isBind detects whether a bind mount is being requested and makes the remount options to -// use in case of bind mount, due to the fact that bind mount doesn't respect mount options. -// The list equals: -// options - 'bind' + 'remount' (no duplicate) -func isBind(options []string) (bool, []string) { - bindRemountOpts := []string{"remount"} - bind := false - - if len(options) != 0 { - for _, option := range options { - switch option { - case "bind": - bind = true - break - case "remount": - break - default: - bindRemountOpts = append(bindRemountOpts, option) - } - } - } - - return bind, bindRemountOpts -} - -// doMount runs the mount command. -func doMount(source string, target string, fstype string, options []string) error { - glog.V(5).Infof("Mounting %s %s %s %v", source, target, fstype, options) - mountArgs := makeMountArgs(source, target, fstype, options) - command := exec.Command("mount", mountArgs...) - output, err := command.CombinedOutput() - if err != nil { - return fmt.Errorf("Mount failed: %v\nMounting arguments: %s %s %s %v\nOutput: %s\n", - err, source, target, fstype, options, string(output)) - } - return err -} - -// makeMountArgs makes the arguments to the mount(8) command. -func makeMountArgs(source, target, fstype string, options []string) []string { - // Build mount command as follows: - // mount [-t $fstype] [-o $options] [$source] $target - mountArgs := []string{} - if len(fstype) > 0 { - mountArgs = append(mountArgs, "-t", fstype) - } - if len(options) > 0 { - mountArgs = append(mountArgs, "-o", strings.Join(options, ",")) - } - if len(source) > 0 { - mountArgs = append(mountArgs, source) - } - mountArgs = append(mountArgs, target) - - return mountArgs -} - -// Unmount unmounts the target. -func (mounter *Mounter) Unmount(target string) error { - glog.V(5).Infof("Unmounting %s", target) - command := exec.Command("umount", target) - output, err := command.CombinedOutput() - if err != nil { - return fmt.Errorf("Unmount failed: %v\nUnmounting arguments: %s\nOutput: %s\n", err, target, string(output)) - } - return nil -} - -// List returns a list of all mounted filesystems. -func (*Mounter) List() ([]MountPoint, error) { - return listProcMounts(procMountsPath) -} - -// IsLikelyNotMountPoint determines if a directory is not a mountpoint. -// It is fast but not necessarily ALWAYS correct. If the path is in fact -// a bind mount from one part of a mount to another it will not be detected. -// mkdir /tmp/a /tmp/b; mount --bin /tmp/a /tmp/b; IsLikelyNotMountPoint("/tmp/b") -// will return true. When in fact /tmp/b is a mount point. If this situation -// if of interest to you, don't use this function... -func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) { - stat, err := os.Stat(file) - if err != nil { - return true, err - } - rootStat, err := os.Lstat(file + "/..") - if err != nil { - return true, err - } - // If the directory has a different device as parent, then it is a mountpoint. - if stat.Sys().(*syscall.Stat_t).Dev != rootStat.Sys().(*syscall.Stat_t).Dev { - return false, nil - } - - return true, nil -} - -func listProcMounts(mountFilePath string) ([]MountPoint, error) { - hash1, err := readProcMounts(mountFilePath, nil) - if err != nil { - return nil, err - } - - for i := 0; i < maxListTries; i++ { - mps := []MountPoint{} - hash2, err := readProcMounts(mountFilePath, &mps) - if err != nil { - return nil, err - } - if hash1 == hash2 { - // Success - return mps, nil - } - hash1 = hash2 - } - return nil, fmt.Errorf("failed to get a consistent snapshot of %v after %d tries", mountFilePath, maxListTries) -} - -// readProcMounts reads the given mountFilePath (normally /proc/mounts) and produces a hash -// of the contents. If the out argument is not nil, this fills it with MountPoint structs. -func readProcMounts(mountFilePath string, out *[]MountPoint) (uint32, error) { - file, err := os.Open(mountFilePath) - if err != nil { - return 0, err - } - defer file.Close() - return readProcMountsFrom(file, out) -} - -func readProcMountsFrom(file io.Reader, out *[]MountPoint) (uint32, error) { - hash := adler32.New() - scanner := bufio.NewReader(file) - for { - line, err := scanner.ReadString('\n') - if err == io.EOF { - break - } - fields := strings.Fields(line) - if len(fields) != expectedNumFieldsPerLine { - return 0, fmt.Errorf("wrong number of fields (expected %d, got %d): %s", expectedNumFieldsPerLine, len(fields), line) - } - - fmt.Fprintf(hash, "%s", line) - - if out != nil { - mp := MountPoint{ - Device: fields[0], - Path: fields[1], - Type: fields[2], - Opts: strings.Split(fields[3], ","), - } - - freq, err := strconv.Atoi(fields[4]) - if err != nil { - return 0, err - } - mp.Freq = freq - - pass, err := strconv.Atoi(fields[5]) - if err != nil { - return 0, err - } - mp.Pass = pass - - *out = append(*out, mp) - } - } - return hash.Sum32(), nil -} - -// formatAndMount uses unix utils to format and mount the given disk -func (mounter *SafeFormatAndMount) formatAndMount(source string, target string, fstype string, options []string) error { - options = append(options, "defaults") - - // Run fsck on the disk to fix repairable issues - args := []string{"-a", source} - cmd := mounter.Runner.Command("fsck", args...) - out, err := cmd.CombinedOutput() - if err != nil { - ee, isExitError := err.(utilExec.ExitError) - switch { - case err == utilExec.ErrExecutableNotFound: - glog.Warningf("'fsck' not found on system; continuing mount without running 'fsck'.") - case isExitError && ee.ExitStatus() == fsckErrorsCorrected: - glog.Infof("Device %s has errors which were corrected by fsck.", source) - case isExitError && ee.ExitStatus() == fsckErrorsUncorrected: - return fmt.Errorf("'fsck' found errors on device %s but could not correct them: %s.", source, string(out)) - case isExitError && ee.ExitStatus() > fsckErrorsUncorrected: - glog.Infof("`fsck` error %s", string(out)) - } - } - - // Try to mount the disk - err = mounter.Interface.Mount(source, target, fstype, options) - if err != nil { - // It is possible that this disk is not formatted. Double check using diskLooksUnformatted - notFormatted, err := mounter.diskLooksUnformatted(source) - if err == nil && notFormatted { - args = []string{source} - // Disk is unformatted so format it. - // Use 'ext4' as the default - if len(fstype) == 0 { - fstype = "ext4" - } - if fstype == "ext4" || fstype == "ext3" { - args = []string{"-E", "lazy_itable_init=0,lazy_journal_init=0", "-F", source} - } - cmd := mounter.Runner.Command("mkfs."+fstype, args...) - _, err := cmd.CombinedOutput() - if err == nil { - // the disk has been formatted successfully try to mount it again. - return mounter.Interface.Mount(source, target, fstype, options) - } - return err - } - } - return err -} - -// diskLooksUnformatted uses 'lsblk' to see if the given disk is unformated -func (mounter *SafeFormatAndMount) diskLooksUnformatted(disk string) (bool, error) { - args := []string{"-nd", "-o", "FSTYPE", disk} - cmd := mounter.Runner.Command("lsblk", args...) - dataOut, err := cmd.CombinedOutput() - output := strings.TrimSpace(string(dataOut)) - - // TODO (#13212): check if this disk has partitions and return false, and - // an error if so. - - if err != nil { - return false, err - } - - return output == "", nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_linux_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_linux_test.go deleted file mode 100644 index cd802d774..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_linux_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// +build linux - -/* -Copyright 2014 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. -*/ - -package mount - -import ( - "strings" - "testing" -) - -func TestReadProcMountsFrom(t *testing.T) { - successCase := - `/dev/0 /path/to/0 type0 flags 0 0 - /dev/1 /path/to/1 type1 flags 1 1 - /dev/2 /path/to/2 type2 flags,1,2=3 2 2 - ` - hash, err := readProcMountsFrom(strings.NewReader(successCase), nil) - if err != nil { - t.Errorf("expected success") - } - if hash != 0xa3522051 { - t.Errorf("expected 0xa3522051, got %#x", hash) - } - mounts := []MountPoint{} - hash, err = readProcMountsFrom(strings.NewReader(successCase), &mounts) - if err != nil { - t.Errorf("expected success") - } - if hash != 0xa3522051 { - t.Errorf("expected 0xa3522051, got %#x", hash) - } - if len(mounts) != 3 { - t.Fatalf("expected 3 mounts, got %d", len(mounts)) - } - mp := MountPoint{"/dev/0", "/path/to/0", "type0", []string{"flags"}, 0, 0} - if !mountPointsEqual(&mounts[0], &mp) { - t.Errorf("got unexpected MountPoint[0]: %#v", mounts[0]) - } - mp = MountPoint{"/dev/1", "/path/to/1", "type1", []string{"flags"}, 1, 1} - if !mountPointsEqual(&mounts[1], &mp) { - t.Errorf("got unexpected MountPoint[1]: %#v", mounts[1]) - } - mp = MountPoint{"/dev/2", "/path/to/2", "type2", []string{"flags", "1", "2=3"}, 2, 2} - if !mountPointsEqual(&mounts[2], &mp) { - t.Errorf("got unexpected MountPoint[2]: %#v", mounts[2]) - } - - errorCases := []string{ - "/dev/0 /path/to/mount\n", - "/dev/1 /path/to/mount type flags a 0\n", - "/dev/2 /path/to/mount type flags 0 b\n", - } - for _, ec := range errorCases { - _, err := readProcMountsFrom(strings.NewReader(ec), &mounts) - if err == nil { - t.Errorf("expected error") - } - } -} - -func mountPointsEqual(a, b *MountPoint) bool { - if a.Device != b.Device || a.Path != b.Path || a.Type != b.Type || !slicesEqual(a.Opts, b.Opts) || a.Pass != b.Pass || a.Freq != b.Freq { - return false - } - return true -} - -func slicesEqual(a, b []string) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -func TestGetMountRefs(t *testing.T) { - fm := &FakeMounter{ - MountPoints: []MountPoint{ - {Device: "/dev/sdb", Path: "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd"}, - {Device: "/dev/sdb", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd-in-pod"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd2"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod2"}, - }, - } - - tests := []struct { - mountPath string - expectedRefs []string - }{ - { - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd-in-pod", - []string{ - "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd", - }, - }, - { - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod", - []string{ - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod2", - "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd2", - }, - }, - } - - for i, test := range tests { - if refs, err := GetMountRefs(fm, test.mountPath); err != nil || !setEquivalent(test.expectedRefs, refs) { - t.Errorf("%d. getMountRefs(%q) = %v, %v; expected %v, nil", i, test.mountPath, refs, err, test.expectedRefs) - } - } -} - -func setEquivalent(set1, set2 []string) bool { - map1 := make(map[string]bool) - map2 := make(map[string]bool) - for _, s := range set1 { - map1[s] = true - } - for _, s := range set2 { - map2[s] = true - } - - for s := range map1 { - if !map2[s] { - return false - } - } - for s := range map2 { - if !map1[s] { - return false - } - } - return true -} - -func TestGetDeviceNameFromMount(t *testing.T) { - fm := &FakeMounter{ - MountPoints: []MountPoint{ - {Device: "/dev/disk/by-path/prefix-lun-1", - Path: "/mnt/111"}, - {Device: "/dev/disk/by-path/prefix-lun-1", - Path: "/mnt/222"}, - }, - } - - tests := []struct { - mountPath string - expectedDevice string - expectedRefs int - }{ - { - "/mnt/222", - "/dev/disk/by-path/prefix-lun-1", - 2, - }, - } - - for i, test := range tests { - if device, refs, err := GetDeviceNameFromMount(fm, test.mountPath); err != nil || test.expectedRefs != refs || test.expectedDevice != device { - t.Errorf("%d. GetDeviceNameFromMount(%s) = (%s, %d), %v; expected (%s,%d), nil", i, test.mountPath, device, refs, err, test.expectedDevice, test.expectedRefs) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_unsupported.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_unsupported.go deleted file mode 100644 index 8942c0036..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/mount_unsupported.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build !linux - -/* -Copyright 2014 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. -*/ - -package mount - -type Mounter struct{} - -func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error { - return nil -} - -func (mounter *Mounter) Unmount(target string) error { - return nil -} - -func (mounter *Mounter) List() ([]MountPoint, error) { - return []MountPoint{}, nil -} - -func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) { - return true, nil -} - -func (mounter *SafeFormatAndMount) formatAndMount(source string, target string, fstype string, options []string) error { - return nil -} - -func (mounter *SafeFormatAndMount) diskLooksUnformatted(disk string) (bool, error) { - return true, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go deleted file mode 100644 index 6735c024c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go +++ /dev/null @@ -1,200 +0,0 @@ -// +build linux - -/* -Copyright 2014 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. -*/ - -package mount - -import ( - "os" - "path/filepath" - "strings" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/util/exec" -) - -// NsenterMounter is part of experimental support for running the kubelet -// in a container. Currently, all docker containers receive their own mount -// namespaces. NsenterMounter works by executing nsenter to run commands in -// the host's mount namespace. -// -// NsenterMounter requires: -// -// 1. Docker >= 1.6 due to the dependency on the slave propagation mode -// of the bind-mount of the kubelet root directory in the container. -// Docker 1.5 used a private propagation mode for bind-mounts, so mounts -// performed in the host's mount namespace do not propagate out to the -// bind-mount in this docker version. -// 2. The host's root filesystem must be available at /rootfs -// 3. The nsenter binary must be on the Kubelet process' PATH in the container's -// filesystem. -// 4. The Kubelet process must have CAP_SYS_ADMIN (required by nsenter); at -// the present, this effectively means that the kubelet is running in a -// privileged container. -// 5. The volume path used by the Kubelet must be the same inside and outside -// the container and be writable by the container (to initialize volume) -// contents. TODO: remove this requirement. -// 6. The host image must have mount, findmnt, and umount binaries in /bin, -// /usr/sbin, or /usr/bin -// -// For more information about mount propagation modes, see: -// https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt -type NsenterMounter struct { - // a map of commands to their paths on the host filesystem - paths map[string]string -} - -func NewNsenterMounter() *NsenterMounter { - m := &NsenterMounter{ - paths: map[string]string{ - "mount": "", - "findmnt": "", - "umount": "", - }, - } - // search for the mount command in other locations besides /usr/bin - for binary := range m.paths { - // default to root - m.paths[binary] = filepath.Join("/", binary) - for _, path := range []string{"/bin", "/usr/sbin", "/usr/bin"} { - binPath := filepath.Join(path, binary) - if _, err := os.Stat(filepath.Join(hostRootFsPath, binPath)); err != nil { - continue - } - m.paths[binary] = binPath - break - } - // TODO: error, so that the kubelet can stop if the mounts don't exist - } - return m -} - -// NsenterMounter implements mount.Interface -var _ = Interface(&NsenterMounter{}) - -const ( - hostRootFsPath = "/rootfs" - hostProcMountsPath = "/rootfs/proc/mounts" - nsenterPath = "nsenter" -) - -// Mount runs mount(8) in the host's root mount namespace. Aside from this -// aspect, Mount has the same semantics as the mounter returned by mount.New() -func (n *NsenterMounter) Mount(source string, target string, fstype string, options []string) error { - bind, bindRemountOpts := isBind(options) - - if bind { - err := n.doNsenterMount(source, target, fstype, []string{"bind"}) - if err != nil { - return err - } - return n.doNsenterMount(source, target, fstype, bindRemountOpts) - } - - return n.doNsenterMount(source, target, fstype, options) -} - -// doNsenterMount nsenters the host's mount namespace and performs the -// requested mount. -func (n *NsenterMounter) doNsenterMount(source, target, fstype string, options []string) error { - glog.V(5).Infof("nsenter Mounting %s %s %s %v", source, target, fstype, options) - args := n.makeNsenterArgs(source, target, fstype, options) - - glog.V(5).Infof("Mount command: %v %v", nsenterPath, args) - exec := exec.New() - outputBytes, err := exec.Command(nsenterPath, args...).CombinedOutput() - if len(outputBytes) != 0 { - glog.V(5).Infof("Output from mount command: %v", string(outputBytes)) - } - - return err -} - -// makeNsenterArgs makes a list of argument to nsenter in order to do the -// requested mount. -func (n *NsenterMounter) makeNsenterArgs(source, target, fstype string, options []string) []string { - nsenterArgs := []string{ - "--mount=/rootfs/proc/1/ns/mnt", - "--", - n.absHostPath("mount"), - } - - args := makeMountArgs(source, target, fstype, options) - - return append(nsenterArgs, args...) -} - -// Unmount runs umount(8) in the host's mount namespace. -func (n *NsenterMounter) Unmount(target string) error { - args := []string{ - "--mount=/rootfs/proc/1/ns/mnt", - "--", - n.absHostPath("umount"), - target, - } - - glog.V(5).Infof("Unmount command: %v %v", nsenterPath, args) - exec := exec.New() - outputBytes, err := exec.Command(nsenterPath, args...).CombinedOutput() - if len(outputBytes) != 0 { - glog.V(5).Infof("Output from mount command: %v", string(outputBytes)) - } - - return err -} - -// List returns a list of all mounted filesystems in the host's mount namespace. -func (*NsenterMounter) List() ([]MountPoint, error) { - return listProcMounts(hostProcMountsPath) -} - -// IsLikelyNotMountPoint determines whether a path is a mountpoint by calling findmnt -// in the host's root mount namespace. -func (n *NsenterMounter) IsLikelyNotMountPoint(file string) (bool, error) { - file, err := filepath.Abs(file) - if err != nil { - return true, err - } - - args := []string{"--mount=/rootfs/proc/1/ns/mnt", "--", n.absHostPath("findmnt"), "-o", "target", "--noheadings", "--target", file} - glog.V(5).Infof("findmnt command: %v %v", nsenterPath, args) - - exec := exec.New() - out, err := exec.Command(nsenterPath, args...).CombinedOutput() - if err != nil { - glog.Errorf("Failed to nsenter mount, return file doesn't exist: %v", err) - // If the command itself is correct, then if we encountered error - // then most likely this means that the directory does not exist. - return true, os.ErrNotExist - } - strOut := strings.TrimSuffix(string(out), "\n") - - glog.V(5).Infof("IsLikelyNotMountPoint findmnt output: %v", strOut) - if strOut == file { - return false, nil - } - - return true, nil -} - -func (n *NsenterMounter) absHostPath(command string) string { - path, ok := n.paths[command] - if !ok { - return command - } - return path -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_unsupported.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_unsupported.go deleted file mode 100644 index 210fab851..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_unsupported.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build !linux - -/* -Copyright 2014 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. -*/ - -package mount - -type NsenterMounter struct{} - -func NewNsenterMounter() *NsenterMounter { - return &NsenterMounter{} -} - -var _ = Interface(&NsenterMounter{}) - -func (*NsenterMounter) Mount(source string, target string, fstype string, options []string) error { - return nil -} - -func (*NsenterMounter) Unmount(target string) error { - return nil -} - -func (*NsenterMounter) List() ([]MountPoint, error) { - return []MountPoint{}, nil -} - -func (*NsenterMounter) IsLikelyNotMountPoint(file string) (bool, error) { - return true, nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/safe_format_and_mount_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/safe_format_and_mount_test.go deleted file mode 100644 index 03c0b8442..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/mount/safe_format_and_mount_test.go +++ /dev/null @@ -1,224 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package mount - -import ( - "fmt" - "runtime" - "testing" - - "k8s.io/kubernetes/pkg/util/exec" -) - -type ErrorMounter struct { - *FakeMounter - errIndex int - err []error -} - -func (mounter *ErrorMounter) Mount(source string, target string, fstype string, options []string) error { - i := mounter.errIndex - mounter.errIndex++ - if mounter.err != nil && mounter.err[i] != nil { - return mounter.err[i] - } - return mounter.FakeMounter.Mount(source, target, fstype, options) -} - -type ExecArgs struct { - command string - args []string - output string - err error -} - -func TestSafeFormatAndMount(t *testing.T) { - if runtime.GOOS == "darwin" || runtime.GOOS == "windows" { - t.Skipf("not supported on GOOS=%s", runtime.GOOS) - } - tests := []struct { - description string - fstype string - mountOptions []string - execScripts []ExecArgs - mountErrs []error - expectedError error - }{ - { - description: "Test a read only mount", - fstype: "ext4", - mountOptions: []string{"ro"}, - }, - { - description: "Test a normal mount", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - }, - }, - { - description: "Test 'fsck' fails with exit status 4", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", &exec.FakeExitError{Status: 4}}, - }, - expectedError: fmt.Errorf("'fsck' found errors on device /dev/foo but could not correct them: ."), - }, - { - description: "Test 'fsck' fails with exit status 1 (errors found and corrected)", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", &exec.FakeExitError{Status: 1}}, - }, - }, - { - description: "Test 'fsck' fails with exit status other than 1 and 4 (likely unformatted device)", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", &exec.FakeExitError{Status: 8}}, - }, - }, - { - description: "Test that 'lsblk' is called and fails", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'")}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"lsblk", []string{"-nd", "-o", "FSTYPE", "/dev/foo"}, "ext4", nil}, - }, - expectedError: fmt.Errorf("unknown filesystem type '(null)'"), - }, - { - description: "Test that 'lsblk' is called and confirms unformatted disk, format fails", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'")}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"lsblk", []string{"-nd", "-o", "FSTYPE", "/dev/foo"}, "", nil}, - {"mkfs.ext4", []string{"-E", "lazy_itable_init=0,lazy_journal_init=0", "-F", "/dev/foo"}, "", fmt.Errorf("formatting failed")}, - }, - expectedError: fmt.Errorf("formatting failed"), - }, - { - description: "Test that 'lsblk' is called and confirms unformatted disk, format passes, second mount fails", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), fmt.Errorf("Still cannot mount")}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"lsblk", []string{"-nd", "-o", "FSTYPE", "/dev/foo"}, "", nil}, - {"mkfs.ext4", []string{"-E", "lazy_itable_init=0,lazy_journal_init=0", "-F", "/dev/foo"}, "", nil}, - }, - expectedError: fmt.Errorf("Still cannot mount"), - }, - { - description: "Test that 'lsblk' is called and confirms unformatted disk, format passes, second mount passes", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), nil}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"lsblk", []string{"-nd", "-o", "FSTYPE", "/dev/foo"}, "", nil}, - {"mkfs.ext4", []string{"-E", "lazy_itable_init=0,lazy_journal_init=0", "-F", "/dev/foo"}, "", nil}, - }, - expectedError: nil, - }, - { - description: "Test that 'lsblk' is called and confirms unformatted disk, format passes, second mount passes with ext3", - fstype: "ext3", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), nil}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"lsblk", []string{"-nd", "-o", "FSTYPE", "/dev/foo"}, "", nil}, - {"mkfs.ext3", []string{"-E", "lazy_itable_init=0,lazy_journal_init=0", "-F", "/dev/foo"}, "", nil}, - }, - expectedError: nil, - }, - { - description: "test that none ext4 fs does not get called with ext4 options.", - fstype: "xfs", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), nil}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"lsblk", []string{"-nd", "-o", "FSTYPE", "/dev/foo"}, "", nil}, - {"mkfs.xfs", []string{"/dev/foo"}, "", nil}, - }, - expectedError: nil, - }, - } - - for _, test := range tests { - commandScripts := []exec.FakeCommandAction{} - for _, expected := range test.execScripts { - ecmd := expected.command - eargs := expected.args - output := expected.output - err := expected.err - commandScript := func(cmd string, args ...string) exec.Cmd { - if cmd != ecmd { - t.Errorf("Unexpected command %s. Expecting %s", cmd, ecmd) - } - - for j := range args { - if args[j] != eargs[j] { - t.Errorf("Unexpected args %v. Expecting %v", args, eargs) - } - } - fake := exec.FakeCmd{ - CombinedOutputScript: []exec.FakeCombinedOutputAction{ - func() ([]byte, error) { return []byte(output), err }, - }, - } - return exec.InitFakeCmd(&fake, cmd, args...) - } - commandScripts = append(commandScripts, commandScript) - } - - fake := exec.FakeExec{ - CommandScript: commandScripts, - } - - fakeMounter := ErrorMounter{&FakeMounter{}, 0, test.mountErrs} - mounter := SafeFormatAndMount{ - Interface: &fakeMounter, - Runner: &fake, - } - - device := "/dev/foo" - dest := "/mnt/bar" - err := mounter.FormatAndMount(device, dest, test.fstype, test.mountOptions) - if test.expectedError == nil { - if err != nil { - t.Errorf("test \"%s\" unexpected non-error: %v", test.description, err) - } - - // Check that something was mounted on the directory - isNotMountPoint, err := fakeMounter.IsLikelyNotMountPoint(dest) - if err != nil || isNotMountPoint { - t.Errorf("test \"%s\" the directory was not mounted", test.description) - } - - //check that the correct device was mounted - mountedDevice, _, err := GetDeviceNameFromMount(fakeMounter.FakeMounter, dest) - if err != nil || mountedDevice != device { - t.Errorf("test \"%s\" the correct device was not mounted", test.description) - } - } else { - if err == nil || test.expectedError.Error() != err.Error() { - t.Errorf("test \"%s\" unexpected error: \n [%v]. \nExpecting [%v]", test.description, err, test.expectedError) - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/http_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/http_test.go deleted file mode 100644 index 7990a51d1..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/http_test.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -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. -*/ - -package net - -import ( - "net" - "net/http" - "reflect" - "testing" -) - -func TestGetClientIP(t *testing.T) { - ipString := "10.0.0.1" - ip := net.ParseIP(ipString) - invalidIPString := "invalidIPString" - testCases := []struct { - Request http.Request - ExpectedIP net.IP - }{ - { - Request: http.Request{}, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Real-Ip": {ipString}, - }, - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Real-Ip": {invalidIPString}, - }, - }, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {ipString}, - }, - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {invalidIPString}, - }, - }, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {invalidIPString + "," + ipString}, - }, - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - RemoteAddr: ipString, - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - RemoteAddr: invalidIPString, - }, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {invalidIPString}, - }, - RemoteAddr: ipString, - }, - ExpectedIP: ip, - }, - } - - for i, test := range testCases { - if a, e := GetClientIP(&test.Request), test.ExpectedIP; reflect.DeepEqual(e, a) != true { - t.Fatalf("test case %d failed. expected: %v, actual: %v", i+1, e, a) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/interface_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/interface_test.go deleted file mode 100644 index 9571e5b48..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/interface_test.go +++ /dev/null @@ -1,300 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package net - -import ( - "fmt" - "io" - "net" - "strings" - "testing" -) - -const gatewayfirst = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const gatewaylast = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -` -const gatewaymiddle = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const noInternetConnection = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const nothing = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -` -const gatewayfirstIpv6_1 = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0AA1 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const gatewayfirstIpv6_2 = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0AA1 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const route_Invalidhex = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0AA 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` - -// Based on DigitalOcean COREOS -const gatewayfirstLinkLocal = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth0 00000000 0120372D 0001 0 0 0 00000000 0 0 0 -eth0 00000000 00000000 0001 0 0 2048 00000000 0 0 0 -` - -func TestGetRoutes(t *testing.T) { - testCases := []struct { - tcase string - route string - expected int - }{ - {"gatewayfirst", gatewayfirst, 4}, - {"gatewaymiddle", gatewaymiddle, 4}, - {"gatewaylast", gatewaylast, 4}, - {"nothing", nothing, 0}, - {"gatewayfirstIpv6_1", gatewayfirstIpv6_1, 0}, - {"gatewayfirstIpv6_2", gatewayfirstIpv6_2, 0}, - {"route_Invalidhex", route_Invalidhex, 0}, - } - for _, tc := range testCases { - r := strings.NewReader(tc.route) - routes, err := getRoutes(r) - if len(routes) != tc.expected { - t.Errorf("case[%v]: expected %v, got %v .err : %v", tc.tcase, tc.expected, len(routes), err) - } - } -} - -func TestParseIP(t *testing.T) { - testCases := []struct { - tcase string - ip string - success bool - expected net.IP - }{ - {"empty", "", false, nil}, - {"too short", "AA", false, nil}, - {"too long", "0011223344", false, nil}, - {"invalid", "invalid!", false, nil}, - {"zero", "00000000", true, net.IP{0, 0, 0, 0}}, - {"ffff", "FFFFFFFF", true, net.IP{0xff, 0xff, 0xff, 0xff}}, - {"valid", "12345678", true, net.IP{120, 86, 52, 18}}, - } - for _, tc := range testCases { - ip, err := parseIP(tc.ip) - if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %q, got %q . err : %v", tc.tcase, tc.expected, ip, err) - } - } -} - -func TestIsInterfaceUp(t *testing.T) { - testCases := []struct { - tcase string - intf net.Interface - expected bool - }{ - {"up", net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp}, true}, - {"down", net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: 0}, false}, - {"nothing", net.Interface{}, false}, - } - for _, tc := range testCases { - it := isInterfaceUp(&tc.intf) - if it != tc.expected { - t.Errorf("case[%v]: expected %v, got %v .", tc.tcase, tc.expected, it) - } - } -} - -type addrStruct struct{ val string } - -func (a addrStruct) Network() string { - return a.val -} -func (a addrStruct) String() string { - return a.val -} - -func TestFinalIP(t *testing.T) { - testCases := []struct { - tcase string - addr []net.Addr - expected net.IP - }{ - {"ipv6", []net.Addr{addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}}, nil}, - {"invalidCIDR", []net.Addr{addrStruct{val: "fe80::2f7:67fff:fe6e:2956/64"}}, nil}, - {"loopback", []net.Addr{addrStruct{val: "127.0.0.1/24"}}, nil}, - {"ip4", []net.Addr{addrStruct{val: "10.254.12.132/17"}}, net.ParseIP("10.254.12.132")}, - - {"nothing", []net.Addr{}, nil}, - } - for _, tc := range testCases { - ip, err := getFinalIP(tc.addr) - if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %v, got %v .err : %v", tc.tcase, tc.expected, ip, err) - } - } -} - -func TestAddrs(t *testing.T) { - var nw networkInterfacer = validNetworkInterface{} - intf := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: 0} - addrs, err := nw.Addrs(&intf) - if err != nil { - t.Errorf("expected no error got : %v", err) - } - if len(addrs) != 2 { - t.Errorf("expected addrs: 2 got null") - } -} - -type validNetworkInterface struct { -} - -func (_ validNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp} - return &c, nil -} -func (_ validNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}} - return ifat, nil -} - -type validNetworkInterfaceWithLinkLocal struct { -} - -func (_ validNetworkInterfaceWithLinkLocal) InterfaceByName(intfName string) (*net.Interface, error) { - c := net.Interface{Index: 0, MTU: 0, Name: "eth0", HardwareAddr: nil, Flags: net.FlagUp} - return &c, nil -} -func (_ validNetworkInterfaceWithLinkLocal) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "169.254.162.166/16"}, addrStruct{val: "45.55.47.146/19"}} - return ifat, nil -} - -type validNetworkInterfacewithIpv6Only struct { -} - -func (_ validNetworkInterfacewithIpv6Only) InterfaceByName(intfName string) (*net.Interface, error) { - c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp} - return &c, nil -} -func (_ validNetworkInterfacewithIpv6Only) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}} - return ifat, nil -} - -type noNetworkInterface struct { -} - -func (_ noNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return nil, fmt.Errorf("unable get Interface") -} -func (_ noNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - return nil, nil -} - -type networkInterfacewithNoAddrs struct { -} - -func (_ networkInterfacewithNoAddrs) InterfaceByName(intfName string) (*net.Interface, error) { - c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp} - return &c, nil -} -func (_ networkInterfacewithNoAddrs) Addrs(intf *net.Interface) ([]net.Addr, error) { - return nil, fmt.Errorf("unable get Addrs") -} - -type networkInterfacewithIpv6addrs struct { -} - -func (_ networkInterfacewithIpv6addrs) InterfaceByName(intfName string) (*net.Interface, error) { - c := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp} - return &c, nil -} -func (_ networkInterfacewithIpv6addrs) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "fe80::2f7:6ffff:fe6e:2956/64"}} - return ifat, nil -} - -func TestGetIPFromInterface(t *testing.T) { - testCases := []struct { - tcase string - nwname string - nw networkInterfacer - expected net.IP - }{ - {"valid", "eth3", validNetworkInterface{}, net.ParseIP("10.254.71.145")}, - {"ipv6", "eth3", validNetworkInterfacewithIpv6Only{}, nil}, - {"nothing", "eth3", noNetworkInterface{}, nil}, - } - for _, tc := range testCases { - ip, err := getIPFromInterface(tc.nwname, tc.nw) - if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %v, got %+v .err : %v", tc.tcase, tc.expected, ip, err) - } - } -} - -func TestChooseHostInterfaceFromRoute(t *testing.T) { - testCases := []struct { - tcase string - inFile io.Reader - nw networkInterfacer - expected net.IP - }{ - {"valid_routefirst", strings.NewReader(gatewayfirst), validNetworkInterface{}, net.ParseIP("10.254.71.145")}, - {"valid_routelast", strings.NewReader(gatewaylast), validNetworkInterface{}, net.ParseIP("10.254.71.145")}, - {"valid_routemiddle", strings.NewReader(gatewaymiddle), validNetworkInterface{}, net.ParseIP("10.254.71.145")}, - {"valid_routemiddle_ipv6", strings.NewReader(gatewaymiddle), validNetworkInterfacewithIpv6Only{}, nil}, - {"no internet connection", strings.NewReader(noInternetConnection), validNetworkInterface{}, nil}, - {"no non-link-local ip", strings.NewReader(gatewayfirstLinkLocal), validNetworkInterfaceWithLinkLocal{}, net.ParseIP("45.55.47.146")}, - {"no route", strings.NewReader(nothing), validNetworkInterface{}, nil}, - {"no route file", nil, validNetworkInterface{}, nil}, - {"no interfaces", nil, noNetworkInterface{}, nil}, - {"no interface Addrs", strings.NewReader(gatewaymiddle), networkInterfacewithNoAddrs{}, nil}, - {"Invalid Addrs", strings.NewReader(gatewaymiddle), networkInterfacewithIpv6addrs{}, nil}, - } - for _, tc := range testCases { - ip, err := chooseHostInterfaceFromRoute(tc.inFile, tc.nw) - if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %v, got %+v .err : %v", tc.tcase, tc.expected, ip, err) - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/port_range_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/port_range_test.go deleted file mode 100644 index 9eb081aa7..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/port_range_test.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package net - -import ( - "testing" - - flag "github.com/spf13/pflag" -) - -func TestPortRange(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - included int - excluded int - }{ - {"100-200", true, "100-200", 200, 201}, - {" 100-200 ", true, "100-200", 200, 201}, - {"0-0", true, "0-0", 0, 1}, - {"", true, "", -1, 0}, - {"100", false, "", -1, -1}, - {"100 - 200", false, "", -1, -1}, - {"-100", false, "", -1, -1}, - {"100-", false, "", -1, -1}, - } - - for i := range testCases { - tc := &testCases[i] - pr := &PortRange{} - var f flag.Value = pr - err := f.Set(tc.input) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - if f.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, f.String()) - } - if tc.included >= 0 && !pr.Contains(tc.included) { - t.Errorf("expected %q to include %d", f.String(), tc.included) - } - if tc.excluded >= 0 && pr.Contains(tc.excluded) { - t.Errorf("expected %q to exclude %d", f.String(), tc.excluded) - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/port_split_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/port_split_test.go deleted file mode 100644 index 2e9e135c0..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/port_split_test.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package net - -import ( - "testing" -) - -func TestSplitSchemeNamePort(t *testing.T) { - table := []struct { - in string - name, port, scheme string - valid bool - normalized bool - }{ - { - in: "aoeu:asdf", - name: "aoeu", - port: "asdf", - valid: true, - }, { - in: "http:aoeu:asdf", - scheme: "http", - name: "aoeu", - port: "asdf", - valid: true, - }, { - in: "https:aoeu:", - scheme: "https", - name: "aoeu", - port: "", - valid: true, - normalized: false, - }, { - in: "https:aoeu:asdf", - scheme: "https", - name: "aoeu", - port: "asdf", - valid: true, - }, { - in: "aoeu:", - name: "aoeu", - valid: true, - normalized: false, - }, { - in: ":asdf", - valid: false, - }, { - in: "aoeu:asdf:htns", - valid: false, - }, { - in: "aoeu", - name: "aoeu", - valid: true, - }, { - in: "", - valid: false, - }, - } - - for _, item := range table { - scheme, name, port, valid := SplitSchemeNamePort(item.in) - if e, a := item.scheme, scheme; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.name, name; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.port, port; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.valid, valid; e != a { - t.Errorf("%q: Wanted %t, got %t", item.in, e, a) - } - - // Make sure valid items round trip through JoinSchemeNamePort - if item.valid { - out := JoinSchemeNamePort(scheme, name, port) - if item.normalized && out != item.in { - t.Errorf("%q: Wanted %s, got %s", item.in, item.in, out) - } - scheme, name, port, valid := SplitSchemeNamePort(out) - if e, a := item.scheme, scheme; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.name, name; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.port, port; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.valid, valid; e != a { - t.Errorf("%q: Wanted %t, got %t", item.in, e, a) - } - } - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/sets/README.md b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/sets/README.md new file mode 100644 index 000000000..b0f238a26 --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/sets/README.md @@ -0,0 +1,17 @@ +This package contains hand-coded set implementations that should be similar to +the autogenerated ones in `pkg/util/sets`. + +We can't simply use net.IPNet as a map-key in Go (because it contains a +`[]byte`). + +We could use the same workaround we use here (a string representation as the +key) to autogenerate sets. If we do that, or decide on an alternate approach, +we should replace the implementations in this package with the autogenerated +versions. + +It is expected that callers will alias this import as `netsets` +i.e. `import netsets "k8s.io/kubernetes/pkg/util/net/sets"` + + + +[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/pkg/util/net/sets/README.md?pixel)]() diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/sets/ipnet.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/sets/ipnet.go new file mode 100644 index 000000000..db117f63e --- /dev/null +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/net/sets/ipnet.go @@ -0,0 +1,119 @@ +/* +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. +*/ + +package sets + +import ( + "net" + "strings" +) + +type IPNet map[string]*net.IPNet + +func ParseIPNets(specs ...string) (IPNet, error) { + ipnetset := make(IPNet) + for _, spec := range specs { + spec = strings.TrimSpace(spec) + _, ipnet, err := net.ParseCIDR(spec) + if err != nil { + return nil, err + } + k := ipnet.String() // In case of normalization + ipnetset[k] = ipnet + } + return ipnetset, nil +} + +// Insert adds items to the set. +func (s IPNet) Insert(items ...*net.IPNet) { + for _, item := range items { + s[item.String()] = item + } +} + +// Delete removes all items from the set. +func (s IPNet) Delete(items ...*net.IPNet) { + for _, item := range items { + delete(s, item.String()) + } +} + +// Has returns true if and only if item is contained in the set. +func (s IPNet) Has(item *net.IPNet) bool { + _, contained := s[item.String()] + return contained +} + +// HasAll returns true if and only if all items are contained in the set. +func (s IPNet) HasAll(items ...*net.IPNet) bool { + for _, item := range items { + if !s.Has(item) { + return false + } + } + return true +} + +// Difference returns a set of objects that are not in s2 +// For example: +// s1 = {a1, a2, a3} +// s2 = {a1, a2, a4, a5} +// s1.Difference(s2) = {a3} +// s2.Difference(s1) = {a4, a5} +func (s IPNet) Difference(s2 IPNet) IPNet { + result := make(IPNet) + for k, i := range s { + _, found := s2[k] + if found { + continue + } + result[k] = i + } + return result +} + +// StringSlice returns a []string with the String representation of each element in the set. +// Order is undefined. +func (s IPNet) StringSlice() []string { + a := make([]string, 0, len(s)) + for k := range s { + a = append(a, k) + } + return a +} + +// IsSuperset returns true if and only if s1 is a superset of s2. +func (s1 IPNet) IsSuperset(s2 IPNet) bool { + for k := range s2 { + _, found := s1[k] + if !found { + return false + } + } + return true +} + +// Equal returns true if and only if s1 is equal (as a set) to s2. +// Two sets are equal if their membership is identical. +// (In practice, this means same elements, order doesn't matter) +func (s1 IPNet) Equal(s2 IPNet) bool { + return len(s1) == len(s2) && s1.IsSuperset(s2) +} + +// Len returns the size of the set. +func (s IPNet) Len() int { + return len(s) +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/node/node.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/node/node.go deleted file mode 100644 index cbc062fc9..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/node/node.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package node - -import ( - "fmt" - "net" - "os/exec" - "strings" - - "github.com/golang/glog" - "k8s.io/kubernetes/pkg/api" -) - -func GetHostname(hostnameOverride string) string { - hostname := hostnameOverride - if string(hostname) == "" { - nodename, err := exec.Command("uname", "-n").Output() - if err != nil { - glog.Fatalf("Couldn't determine hostname: %v", err) - } - hostname = string(nodename) - } - return strings.ToLower(strings.TrimSpace(hostname)) -} - -// GetNodeHostIP returns the provided node's IP, based on the priority: -// 1. NodeInternalIP -// 2. NodeExternalIP -// 3. NodeLegacyHostIP -func GetNodeHostIP(node *api.Node) (net.IP, error) { - addresses := node.Status.Addresses - addressMap := make(map[api.NodeAddressType][]api.NodeAddress) - for i := range addresses { - addressMap[addresses[i].Type] = append(addressMap[addresses[i].Type], addresses[i]) - } - if addresses, ok := addressMap[api.NodeInternalIP]; ok { - return net.ParseIP(addresses[0].Address), nil - } - if addresses, ok := addressMap[api.NodeExternalIP]; ok { - return net.ParseIP(addresses[0].Address), nil - } - if addresses, ok := addressMap[api.NodeLegacyHostIP]; ok { - return net.ParseIP(addresses[0].Address), nil - } - return nil, fmt.Errorf("host IP unknown; known addresses: %v", addresses) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/doc.go deleted file mode 100644 index 539d6c43b..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package oom implements utility functions relating to out of memory management. -package oom diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom.go deleted file mode 100644 index c6d563ab2..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package oom - -// This is a struct instead of an interface to allow injection of process ID listers and -// applying OOM score in tests. -// TODO: make this an interface, and inject a mock ioutil struct for testing. -type OOMAdjuster struct { - pidLister func(cgroupName string) ([]int, error) - ApplyOOMScoreAdj func(pid int, oomScoreAdj int) error - ApplyOOMScoreAdjContainer func(cgroupName string, oomScoreAdj, maxTries int) error -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_fake.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_fake.go deleted file mode 100644 index bd0bf6f45..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_fake.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package oom - -type FakeOOMAdjuster struct{} - -func NewFakeOOMAdjuster() *OOMAdjuster { - return &OOMAdjuster{ - pidLister: func(cgroupName string) ([]int, error) { return make([]int, 0), nil }, - ApplyOOMScoreAdj: fakeApplyOOMScoreAdj, - ApplyOOMScoreAdjContainer: fakeApplyOOMScoreAdjContainer, - } -} - -func fakeApplyOOMScoreAdj(pid int, oomScoreAdj int) error { - return nil -} - -func fakeApplyOOMScoreAdjContainer(cgroupName string, oomScoreAdj, maxTries int) error { - return nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_linux.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_linux.go deleted file mode 100644 index 5503bad8c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_linux.go +++ /dev/null @@ -1,128 +0,0 @@ -// +build cgo,linux - -/* -Copyright 2015 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. -*/ - -package oom - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "strconv" - - "github.com/golang/glog" - "github.com/opencontainers/runc/libcontainer/cgroups/fs" - "github.com/opencontainers/runc/libcontainer/configs" -) - -func NewOOMAdjuster() *OOMAdjuster { - oomAdjuster := &OOMAdjuster{ - pidLister: getPids, - ApplyOOMScoreAdj: applyOOMScoreAdj, - } - oomAdjuster.ApplyOOMScoreAdjContainer = oomAdjuster.applyOOMScoreAdjContainer - return oomAdjuster -} - -func getPids(cgroupName string) ([]int, error) { - fsManager := fs.Manager{ - Cgroups: &configs.Cgroup{ - Parent: "/", - Name: cgroupName, - }, - } - return fsManager.GetPids() -} - -func syscallNotExists(err error) bool { - if err == nil { - return false - } - if e, ok := err.(*os.SyscallError); ok && os.IsNotExist(e) { - return true - } - return false -} - -// Writes 'value' to /proc//oom_score_adj. PID = 0 means self -// Returns os.ErrNotExist if the `pid` does not exist. -func applyOOMScoreAdj(pid int, oomScoreAdj int) error { - if pid < 0 { - return fmt.Errorf("invalid PID %d specified for oom_score_adj", pid) - } - - var pidStr string - if pid == 0 { - pidStr = "self" - } else { - pidStr = strconv.Itoa(pid) - } - - maxTries := 2 - oomScoreAdjPath := path.Join("/proc", pidStr, "oom_score_adj") - value := strconv.Itoa(oomScoreAdj) - var err error - for i := 0; i < maxTries; i++ { - if err = ioutil.WriteFile(oomScoreAdjPath, []byte(value), 0700); err != nil { - if syscallNotExists(err) { - return os.ErrNotExist - } - err = fmt.Errorf("failed to apply oom-score-adj to pid %d (%v)", err) - } - } - return err -} - -// Writes 'value' to /proc//oom_score_adj for all processes in cgroup cgroupName. -// Keeps trying to write until the process list of the cgroup stabilizes, or until maxTries tries. -func (oomAdjuster *OOMAdjuster) applyOOMScoreAdjContainer(cgroupName string, oomScoreAdj, maxTries int) error { - adjustedProcessSet := make(map[int]bool) - for i := 0; i < maxTries; i++ { - continueAdjusting := false - pidList, err := oomAdjuster.pidLister(cgroupName) - if err != nil { - if syscallNotExists(err) { - // Nothing to do since the container doesn't exist anymore. - return os.ErrNotExist - } - continueAdjusting = true - glog.Errorf("Error getting process list for cgroup %s: %+v", cgroupName, err) - } else if len(pidList) == 0 { - continueAdjusting = true - } else { - for _, pid := range pidList { - if !adjustedProcessSet[pid] { - continueAdjusting = true - if err = oomAdjuster.ApplyOOMScoreAdj(pid, oomScoreAdj); err == nil { - adjustedProcessSet[pid] = true - } - // Processes can come and go while we try to apply oom score adjust value. So ignore errors here. - } - } - } - if !continueAdjusting { - return nil - } - // There's a slight race. A process might have forked just before we write its OOM score adjust. - // The fork might copy the parent process's old OOM score, then this function might execute and - // update the parent's OOM score, but the forked process id might not be reflected in cgroup.procs - // for a short amount of time. So this function might return without changing the forked process's - // OOM score. Very unlikely race, so ignoring this for now. - } - return fmt.Errorf("exceeded maxTries, some processes might not have desired OOM score") -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_linux_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_linux_test.go deleted file mode 100644 index c3a850d91..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_linux_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// +build cgo,linux - -/* -Copyright 2015 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. -*/ - -package oom - -import ( - "testing" -) - -// Converts a sequence of PID lists into a PID lister. -// The PID lister returns pidListSequence[i] on the ith call. If i >= length of pidListSequence -// then return the last element of pidListSequence (the sequence is considered to have) stabilized. -func sequenceToPidLister(pidListSequence [][]int) func(string) ([]int, error) { - var numCalls int - return func(cgroupName string) ([]int, error) { - numCalls++ - if len(pidListSequence) == 0 { - return []int{}, nil - } else if numCalls > len(pidListSequence) { - return pidListSequence[len(pidListSequence)-1], nil - } - return pidListSequence[numCalls-1], nil - } -} - -// Tests that applyOOMScoreAdjContainer correctly applies OOM scores to relevant processes, or -// returns the right error. -func applyOOMScoreAdjContainerTester(pidListSequence [][]int, maxTries int, appliedPids []int, expectedError bool, t *testing.T) { - pidOOMs := make(map[int]bool) - - // Mock ApplyOOMScoreAdj and pidLister. - oomAdjuster := NewOOMAdjuster() - oomAdjuster.ApplyOOMScoreAdj = func(pid int, oomScoreAdj int) error { - pidOOMs[pid] = true - return nil - } - oomAdjuster.pidLister = sequenceToPidLister(pidListSequence) - err := oomAdjuster.ApplyOOMScoreAdjContainer("", 100, maxTries) - - // Check error value. - if expectedError && err == nil { - t.Errorf("Expected error %+v when running ApplyOOMScoreAdjContainer but got no error", expectedError) - return - } else if !expectedError && err != nil { - t.Errorf("Expected no error but got error %+v when running ApplyOOMScoreAdjContainer", err) - return - } else if err != nil { - return - } - - // Check that OOM scores were applied to the right processes. - if len(appliedPids) != len(pidOOMs) { - t.Errorf("Applied OOM scores to incorrect number of processes") - return - } - for _, pid := range appliedPids { - if !pidOOMs[pid] { - t.Errorf("Failed to apply OOM scores to process %d", pid) - } - } -} - -func TestOOMScoreAdjContainer(t *testing.T) { - pidListSequenceEmpty := [][]int{} - applyOOMScoreAdjContainerTester(pidListSequenceEmpty, 3, nil, true, t) - - pidListSequence1 := [][]int{ - {1, 2}, - } - applyOOMScoreAdjContainerTester(pidListSequence1, 1, nil, true, t) - applyOOMScoreAdjContainerTester(pidListSequence1, 2, []int{1, 2}, false, t) - applyOOMScoreAdjContainerTester(pidListSequence1, 3, []int{1, 2}, false, t) - - pidListSequence3 := [][]int{ - {1, 2}, - {1, 2, 4, 5}, - {2, 1, 4, 5, 3}, - } - applyOOMScoreAdjContainerTester(pidListSequence3, 1, nil, true, t) - applyOOMScoreAdjContainerTester(pidListSequence3, 2, nil, true, t) - applyOOMScoreAdjContainerTester(pidListSequence3, 3, nil, true, t) - applyOOMScoreAdjContainerTester(pidListSequence3, 4, []int{1, 2, 3, 4, 5}, false, t) - - pidListSequenceLag := [][]int{ - {}, - {}, - {}, - {1, 2, 4}, - {1, 2, 4, 5}, - } - for i := 1; i < 5; i++ { - applyOOMScoreAdjContainerTester(pidListSequenceLag, i, nil, true, t) - } - applyOOMScoreAdjContainerTester(pidListSequenceLag, 6, []int{1, 2, 4, 5}, false, t) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_unsupported.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_unsupported.go deleted file mode 100644 index 9c4473f7e..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/oom/oom_unsupported.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build !cgo !linux - -/* -Copyright 2015 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. -*/ - -package oom - -import ( - "errors" -) - -var unsupportedErr = errors.New("setting OOM scores is unsupported in this build") - -func NewOOMAdjuster() *OOMAdjuster { - return &OOMAdjuster{ - ApplyOOMScoreAdj: unsupportedApplyOOMScoreAdj, - ApplyOOMScoreAdjContainer: unsupportedApplyOOMScoreAdjContainer, - } -} - -func unsupportedApplyOOMScoreAdj(pid int, oomScoreAdj int) error { - return unsupportedErr -} - -func unsupportedApplyOOMScoreAdjContainer(cgroupName string, oomScoreAdj, maxTries int) error { - return unsupportedErr -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/pod/pod.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/pod/pod.go index 576b0cdab..8fb5cadd0 100644 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/pod/pod.go +++ b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/pod/pod.go @@ -17,10 +17,18 @@ limitations under the License. package pod import ( + "fmt" "hash/adler32" + "time" + + "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + unversionedcore "k8s.io/kubernetes/pkg/client/typed/generated/core/unversioned" + errorsutil "k8s.io/kubernetes/pkg/util/errors" hashutil "k8s.io/kubernetes/pkg/util/hash" + "k8s.io/kubernetes/pkg/util/wait" ) func GetPodTemplateSpecHash(template api.PodTemplateSpec) uint32 { @@ -28,3 +36,54 @@ func GetPodTemplateSpecHash(template api.PodTemplateSpec) uint32 { hashutil.DeepHashObject(podTemplateSpecHasher, template) return podTemplateSpecHasher.Sum32() } + +// TODO: use client library instead when it starts to support update retries +// see https://github.com/kubernetes/kubernetes/issues/21479 +type updatePodFunc func(pod *api.Pod) error + +// UpdatePodWithRetries updates a pod with given applyUpdate function. Note that pod not found error is ignored. +// The returned bool value can be used to tell if the pod is actually updated. +func UpdatePodWithRetries(podClient unversionedcore.PodInterface, pod *api.Pod, applyUpdate updatePodFunc) (*api.Pod, bool, error) { + var err error + var podUpdated bool + oldPod := pod + if err = wait.Poll(10*time.Millisecond, 1*time.Minute, func() (bool, error) { + pod, err = podClient.Get(oldPod.Name) + if err != nil { + return false, err + } + // Apply the update, then attempt to push it to the apiserver. + if err = applyUpdate(pod); err != nil { + return false, err + } + if pod, err = podClient.Update(pod); err == nil { + // Update successful. + return true, nil + } + // TODO: don't retry on perm-failed errors and handle them gracefully + // Update could have failed due to conflict error. Try again. + return false, nil + }); err == nil { + // When there's no error, we've updated this pod. + podUpdated = true + } + + // Handle returned error from wait poll + if err == wait.ErrWaitTimeout { + err = fmt.Errorf("timed out trying to update pod: %+v", oldPod) + } + // Ignore the pod not found error, but the pod isn't updated. + if errors.IsNotFound(err) { + glog.V(4).Infof("%s %s/%s is not found, skip updating it.", oldPod.Kind, oldPod.Namespace, oldPod.Name) + err = nil + } + // Ignore the precondition violated error, but the pod isn't updated. + if err == errorsutil.ErrPreconditionViolated { + glog.V(4).Infof("%s %s/%s precondition doesn't hold, skip updating it.", oldPod.Kind, oldPod.Namespace, oldPod.Name) + err = nil + } + + // If the error is non-nil the returned pod cannot be trusted; if podUpdated is false, the pod isn't updated; + // if the error is nil and podUpdated is true, the returned pod contains the applied update. + return pod, podUpdated, err +} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/doc.go deleted file mode 100644 index d94e6687c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2015 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. -*/ - -// Package procfs implements utility functions relating to the /proc mount. -package procfs diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/example_proc_cgroup b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/example_proc_cgroup deleted file mode 100644 index 3e42ce927..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/example_proc_cgroup +++ /dev/null @@ -1,10 +0,0 @@ -11:name=systemd:/user/1000.user/c1.session -10:hugetlb:/user/1000.user/c1.session -9:perf_event:/user/1000.user/c1.session -8:blkio:/user/1000.user/c1.session -7:freezer:/user/1000.user/c1.session -6:devices:/user/1000.user/c1.session -5:memory:/user/1000.user/c1.session -4:cpuacct:/user/1000.user/c1.session -3:cpu:/user/1000.user/c1.session -2:cpuset:/ \ No newline at end of file diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs.go deleted file mode 100644 index cc432255f..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package procfs - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "strconv" - "strings" -) - -type ProcFS struct{} - -func NewProcFS() ProcFSInterface { - return &ProcFS{} -} - -func containerNameFromProcCgroup(content string) (string, error) { - lines := strings.Split(content, "\n") - for _, line := range lines { - entries := strings.SplitN(line, ":", 3) - if len(entries) == 3 && entries[1] == "devices" { - return strings.TrimSpace(entries[2]), nil - } - } - return "", fmt.Errorf("could not find devices cgroup location") -} - -// getFullContainerName gets the container name given the root process id of the container. -// Eg. If the devices cgroup for the container is stored in /sys/fs/cgroup/devices/docker/nginx, -// return docker/nginx. Assumes that the process is part of exactly one cgroup hierarchy. -func (pfs *ProcFS) GetFullContainerName(pid int) (string, error) { - filePath := path.Join("/proc", strconv.Itoa(pid), "cgroup") - content, err := ioutil.ReadFile(filePath) - if err != nil { - if e, ok := err.(*os.SyscallError); ok && os.IsNotExist(e) { - return "", os.ErrNotExist - } - return "", err - } - return containerNameFromProcCgroup(string(content)) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_fake.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_fake.go deleted file mode 100644 index 8d16aa53c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_fake.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package procfs - -type FakeProcFS struct{} - -func NewFakeProcFS() ProcFSInterface { - return &FakeProcFS{} -} - -// GetFullContainerName gets the container name given the root process id of the container. -// Eg. If the devices cgroup for the container is stored in /sys/fs/cgroup/devices/docker/nginx, -// return docker/nginx. Assumes that the process is part of exactly one cgroup hierarchy. -func (fakePfs *FakeProcFS) GetFullContainerName(pid int) (string, error) { - return "", nil -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_interface.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_interface.go deleted file mode 100644 index d3bf14f0c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_interface.go +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package procfs - -type ProcFSInterface interface { - // GetFullContainerName gets the container name given the root process id of the container. - GetFullContainerName(pid int) (string, error) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_test.go deleted file mode 100644 index 609543dca..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/procfs/procfs_test.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package procfs - -import ( - "io/ioutil" - "testing" -) - -func verifyContainerName(procCgroupText, expectedName string, expectedErr bool, t *testing.T) { - name, err := containerNameFromProcCgroup(procCgroupText) - if expectedErr && err == nil { - t.Errorf("Expected error but did not get error in verifyContainerName") - return - } else if !expectedErr && err != nil { - t.Errorf("Expected no error, but got error %+v in verifyContainerName", err) - return - } else if expectedErr { - return - } - if name != expectedName { - t.Errorf("Expected container name %s but got name %s", expectedName, name) - } -} - -func TestContainerNameFromProcCgroup(t *testing.T) { - procCgroupValid := "2:devices:docker/kubelet" - verifyContainerName(procCgroupValid, "docker/kubelet", false, t) - - procCgroupEmpty := "" - verifyContainerName(procCgroupEmpty, "", true, t) - - content, err := ioutil.ReadFile("example_proc_cgroup") - if err != nil { - t.Errorf("Could not read example /proc cgroup file") - } - verifyContainerName(string(content), "/user/1000.user/c1.session", false, t) - - procCgroupNoDevice := "2:freezer:docker/kubelet\n5:cpuacct:pkg/kubectl" - verifyContainerName(procCgroupNoDevice, "", true, t) - - procCgroupInvalid := "devices:docker/kubelet\ncpuacct:pkg/kubectl" - verifyContainerName(procCgroupInvalid, "", true, t) -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/dial.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/dial.go deleted file mode 100644 index 33cecb7ea..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/dial.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2015 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. -*/ - -package proxy - -import ( - "crypto/tls" - "fmt" - "net" - "net/http" - "net/url" - - "github.com/golang/glog" - - utilnet "k8s.io/kubernetes/pkg/util/net" - "k8s.io/kubernetes/third_party/golang/netutil" -) - -func DialURL(url *url.URL, transport http.RoundTripper) (net.Conn, error) { - dialAddr := netutil.CanonicalAddr(url) - - dialer, _ := utilnet.Dialer(transport) - - switch url.Scheme { - case "http": - if dialer != nil { - return dialer("tcp", dialAddr) - } - return net.Dial("tcp", dialAddr) - case "https": - // Get the tls config from the transport if we recognize it - var tlsConfig *tls.Config - var tlsConn *tls.Conn - var err error - tlsConfig, _ = utilnet.TLSClientConfig(transport) - - if dialer != nil { - // We have a dialer; use it to open the connection, then - // create a tls client using the connection. - netConn, err := dialer("tcp", dialAddr) - if err != nil { - return nil, err - } - if tlsConfig == nil { - // tls.Client requires non-nil config - glog.Warningf("using custom dialer with no TLSClientConfig. Defaulting to InsecureSkipVerify") - // tls.Handshake() requires ServerName or InsecureSkipVerify - tlsConfig = &tls.Config{ - InsecureSkipVerify: true, - } - } else if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify { - // tls.Handshake() requires ServerName or InsecureSkipVerify - // infer the ServerName from the hostname we're connecting to. - inferredHost := dialAddr - if host, _, err := net.SplitHostPort(dialAddr); err == nil { - inferredHost = host - } - // Make a copy to avoid polluting the provided config - tlsConfigCopy := *tlsConfig - tlsConfigCopy.ServerName = inferredHost - tlsConfig = &tlsConfigCopy - } - tlsConn = tls.Client(netConn, tlsConfig) - if err := tlsConn.Handshake(); err != nil { - netConn.Close() - return nil, err - } - - } else { - // Dial - tlsConn, err = tls.Dial("tcp", dialAddr, tlsConfig) - if err != nil { - return nil, err - } - } - - // Return if we were configured to skip validation - if tlsConfig != nil && tlsConfig.InsecureSkipVerify { - return tlsConn, nil - } - - // Verify - host, _, _ := net.SplitHostPort(dialAddr) - if err := tlsConn.VerifyHostname(host); err != nil { - tlsConn.Close() - return nil, err - } - - return tlsConn, nil - default: - return nil, fmt.Errorf("Unknown scheme: %s", url.Scheme) - } -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/doc.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/doc.go deleted file mode 100644 index 0d7519a0c..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2014 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. -*/ - -// Package proxy provides transport and upgrade support for proxies -package proxy diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/transport.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/transport.go deleted file mode 100644 index 079670c0a..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/transport.go +++ /dev/null @@ -1,241 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package proxy - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "path" - "strings" - - "github.com/golang/glog" - "golang.org/x/net/html" - "golang.org/x/net/html/atom" - - "k8s.io/kubernetes/pkg/util/net" - "k8s.io/kubernetes/pkg/util/sets" -) - -// atomsToAttrs states which attributes of which tags require URL substitution. -// Sources: http://www.w3.org/TR/REC-html40/index/attributes.html -// http://www.w3.org/html/wg/drafts/html/master/index.html#attributes-1 -var atomsToAttrs = map[atom.Atom]sets.String{ - atom.A: sets.NewString("href"), - atom.Applet: sets.NewString("codebase"), - atom.Area: sets.NewString("href"), - atom.Audio: sets.NewString("src"), - atom.Base: sets.NewString("href"), - atom.Blockquote: sets.NewString("cite"), - atom.Body: sets.NewString("background"), - atom.Button: sets.NewString("formaction"), - atom.Command: sets.NewString("icon"), - atom.Del: sets.NewString("cite"), - atom.Embed: sets.NewString("src"), - atom.Form: sets.NewString("action"), - atom.Frame: sets.NewString("longdesc", "src"), - atom.Head: sets.NewString("profile"), - atom.Html: sets.NewString("manifest"), - atom.Iframe: sets.NewString("longdesc", "src"), - atom.Img: sets.NewString("longdesc", "src", "usemap"), - atom.Input: sets.NewString("src", "usemap", "formaction"), - atom.Ins: sets.NewString("cite"), - atom.Link: sets.NewString("href"), - atom.Object: sets.NewString("classid", "codebase", "data", "usemap"), - atom.Q: sets.NewString("cite"), - atom.Script: sets.NewString("src"), - atom.Source: sets.NewString("src"), - atom.Video: sets.NewString("poster", "src"), - - // TODO: css URLs hidden in style elements. -} - -// Transport is a transport for text/html content that replaces URLs in html -// content with the prefix of the proxy server -type Transport struct { - Scheme string - Host string - PathPrepend string - - http.RoundTripper -} - -// RoundTrip implements the http.RoundTripper interface -func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { - // Add reverse proxy headers. - forwardedURI := path.Join(t.PathPrepend, req.URL.Path) - if strings.HasSuffix(req.URL.Path, "/") { - forwardedURI = forwardedURI + "/" - } - req.Header.Set("X-Forwarded-Uri", forwardedURI) - if len(t.Host) > 0 { - req.Header.Set("X-Forwarded-Host", t.Host) - } - if len(t.Scheme) > 0 { - req.Header.Set("X-Forwarded-Proto", t.Scheme) - } - - rt := t.RoundTripper - if rt == nil { - rt = http.DefaultTransport - } - resp, err := rt.RoundTrip(req) - - if err != nil { - message := fmt.Sprintf("Error: '%s'\nTrying to reach: '%v'", err.Error(), req.URL.String()) - resp = &http.Response{ - StatusCode: http.StatusServiceUnavailable, - Body: ioutil.NopCloser(strings.NewReader(message)), - } - return resp, nil - } - - if redirect := resp.Header.Get("Location"); redirect != "" { - resp.Header.Set("Location", t.rewriteURL(redirect, req.URL)) - return resp, nil - } - - cType := resp.Header.Get("Content-Type") - cType = strings.TrimSpace(strings.SplitN(cType, ";", 2)[0]) - if cType != "text/html" { - // Do nothing, simply pass through - return resp, nil - } - - return t.rewriteResponse(req, resp) -} - -var _ = net.RoundTripperWrapper(&Transport{}) - -func (rt *Transport) WrappedRoundTripper() http.RoundTripper { - return rt.RoundTripper -} - -// rewriteURL rewrites a single URL to go through the proxy, if the URL refers -// to the same host as sourceURL, which is the page on which the target URL -// occurred. If any error occurs (e.g. parsing), it returns targetURL. -func (t *Transport) rewriteURL(targetURL string, sourceURL *url.URL) string { - url, err := url.Parse(targetURL) - if err != nil { - return targetURL - } - - isDifferentHost := url.Host != "" && url.Host != sourceURL.Host - isRelative := !strings.HasPrefix(url.Path, "/") - if isDifferentHost || isRelative { - return targetURL - } - - url.Scheme = t.Scheme - url.Host = t.Host - origPath := url.Path - // Do not rewrite URL if the sourceURL already contains the necessary prefix. - if strings.HasPrefix(url.Path, t.PathPrepend) { - return url.String() - } - url.Path = path.Join(t.PathPrepend, url.Path) - if strings.HasSuffix(origPath, "/") { - // Add back the trailing slash, which was stripped by path.Join(). - url.Path += "/" - } - - return url.String() -} - -// rewriteHTML scans the HTML for tags with url-valued attributes, and updates -// those values with the urlRewriter function. The updated HTML is output to the -// writer. -func rewriteHTML(reader io.Reader, writer io.Writer, urlRewriter func(string) string) error { - // Note: This assumes the content is UTF-8. - tokenizer := html.NewTokenizer(reader) - - var err error - for err == nil { - tokenType := tokenizer.Next() - switch tokenType { - case html.ErrorToken: - err = tokenizer.Err() - case html.StartTagToken, html.SelfClosingTagToken: - token := tokenizer.Token() - if urlAttrs, ok := atomsToAttrs[token.DataAtom]; ok { - for i, attr := range token.Attr { - if urlAttrs.Has(attr.Key) { - token.Attr[i].Val = urlRewriter(attr.Val) - } - } - } - _, err = writer.Write([]byte(token.String())) - default: - _, err = writer.Write(tokenizer.Raw()) - } - } - if err != io.EOF { - return err - } - return nil -} - -// rewriteResponse modifies an HTML response by updating absolute links referring -// to the original host to instead refer to the proxy transport. -func (t *Transport) rewriteResponse(req *http.Request, resp *http.Response) (*http.Response, error) { - origBody := resp.Body - defer origBody.Close() - - newContent := &bytes.Buffer{} - var reader io.Reader = origBody - var writer io.Writer = newContent - encoding := resp.Header.Get("Content-Encoding") - switch encoding { - case "gzip": - var err error - reader, err = gzip.NewReader(reader) - if err != nil { - return nil, fmt.Errorf("errorf making gzip reader: %v", err) - } - gzw := gzip.NewWriter(writer) - defer gzw.Close() - writer = gzw - // TODO: support flate, other encodings. - case "": - // This is fine - default: - // Some encoding we don't understand-- don't try to parse this - glog.Errorf("Proxy encountered encoding %v for text/html; can't understand this so not fixing links.", encoding) - return resp, nil - } - - urlRewriter := func(targetUrl string) string { - return t.rewriteURL(targetUrl, req.URL) - } - err := rewriteHTML(reader, writer, urlRewriter) - if err != nil { - glog.Errorf("Failed to rewrite URLs: %v", err) - return resp, err - } - - resp.Body = ioutil.NopCloser(newContent) - // Update header node with new content-length - // TODO: Remove any hash/signature headers here? - resp.Header.Del("Content-Length") - resp.ContentLength = int64(newContent.Len()) - - return resp, err -} diff --git a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/transport_test.go b/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/transport_test.go deleted file mode 100644 index 5a71bb1b5..000000000 --- a/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/proxy/transport_test.go +++ /dev/null @@ -1,262 +0,0 @@ -/* -Copyright 2014 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. -*/ - -package proxy - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" -) - -func parseURLOrDie(inURL string) *url.URL { - parsed, err := url.Parse(inURL) - if err != nil { - panic(err) - } - return parsed -} - -func TestProxyTransport(t *testing.T) { - testTransport := &Transport{ - Scheme: "http", - Host: "foo.com", - PathPrepend: "/proxy/minion/minion1:10250", - } - testTransport2 := &Transport{ - Scheme: "https", - Host: "foo.com", - PathPrepend: "/proxy/minion/minion1:8080", - } - emptyHostTransport := &Transport{ - Scheme: "https", - PathPrepend: "/proxy/minion/minion1:10250", - } - emptySchemeTransport := &Transport{ - Host: "foo.com", - PathPrepend: "/proxy/minion/minion1:10250", - } - type Item struct { - input string - sourceURL string - transport *Transport - output string - contentType string - forwardedURI string - redirect string - redirectWant string - } - - table := map[string]Item{ - "normal": { - input: `
    kubelet.loggoogle.log
    `, - sourceURL: "http://myminion.com/logs/log.log", - transport: testTransport, - output: `
    kubelet.loggoogle.log
    `, - contentType: "text/html", - forwardedURI: "/proxy/minion/minion1:10250/logs/log.log", - }, - "full document": { - input: `
    kubelet.loggoogle.log
    `, - sourceURL: "http://myminion.com/logs/log.log", - transport: testTransport, - output: `
    kubelet.loggoogle.log
    `, - contentType: "text/html", - forwardedURI: "/proxy/minion/minion1:10250/logs/log.log", - }, - "trailing slash": { - input: `
    kubelet.loggoogle.log
    `, - sourceURL: "http://myminion.com/logs/log.log", - transport: testTransport, - output: `
    kubelet.loggoogle.log
    `, - contentType: "text/html", - forwardedURI: "/proxy/minion/minion1:10250/logs/log.log", - }, - "content-type charset": { - input: `
    kubelet.loggoogle.log
    `, - sourceURL: "http://myminion.com/logs/log.log", - transport: testTransport, - output: `
    kubelet.loggoogle.log
    `, - contentType: "text/html; charset=utf-8", - forwardedURI: "/proxy/minion/minion1:10250/logs/log.log", - }, - "content-type passthrough": { - input: `
    kubelet.loggoogle.log
    `, - sourceURL: "http://myminion.com/logs/log.log", - transport: testTransport, - output: `
    kubelet.loggoogle.log
    `, - contentType: "text/plain", - forwardedURI: "/proxy/minion/minion1:10250/logs/log.log", - }, - "subdir": { - input: `kubelet.loggoogle.log`, - sourceURL: "http://myminion.com/whatever/apt/somelog.log", - transport: testTransport2, - output: `kubelet.loggoogle.log`, - contentType: "text/html", - forwardedURI: "/proxy/minion/minion1:8080/whatever/apt/somelog.log", - }, - "image": { - input: `
    `, - sourceURL: "http://myminion.com/", - transport: testTransport, - output: `
    `, - contentType: "text/html", - forwardedURI: "/proxy/minion/minion1:10250/", - }, - "abs": { - input: `